AnimeService.php 339 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use App\Models\MpGeneratePicTask;
  8. use App\Services\AIGeneration\AIImageGenerationService;
  9. use App\Services\AIGeneration\AIVideoGenerationService;
  10. use App\Services\DeepSeek\DeepSeekService;
  11. use Dflydev\DotAccessData\Util;
  12. use GuzzleHttp\Client;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Redis;
  16. use OSS\Core\OssException;
  17. use OSS\OssClient;
  18. class AnimeService
  19. {
  20. protected $aiImageGenerationService;
  21. protected $aiVideoGenerationService;
  22. protected $DeepSeekService;
  23. private $url;
  24. private $api_key;
  25. private $headers;
  26. public function __construct(
  27. AIImageGenerationService $aiImageGenerationService,
  28. AIVideoGenerationService $aiVideoGenerationService,
  29. DeepSeekService $DeepSeekService
  30. ) {
  31. $this->aiImageGenerationService = $aiImageGenerationService;
  32. $this->aiVideoGenerationService = $aiVideoGenerationService;
  33. $this->DeepSeekService = $DeepSeekService;
  34. $this->url = 'https://api.deepseek.com/chat/completions';
  35. $this->api_key = env('DEEPSEEK_API_KEY');
  36. $this->headers = [
  37. 'Authorization' => 'Bearer '.$this->api_key,
  38. 'Content-Type' => 'application/json; charset=UTF-8'
  39. ];
  40. }
  41. /**
  42. * 构建统一的分镜数据结构(episodeInfo格式)
  43. * @param array $segments 分镜数据数组
  44. * @return array 返回包含acts和total_duration的数组
  45. */
  46. public function buildEpisodeSegmentsStructure($segments) {
  47. $acts = [];
  48. $totalDuration = 0; // 初始化总时长
  49. foreach($segments as $segment) {
  50. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  51. $videoDuration = getProp($segment, 'video_duration');
  52. $audioDuration = getProp($segment, 'audio_duration');
  53. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  54. $totalDuration += floatval($videoDuration);
  55. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  56. $totalDuration += floatval($audioDuration);
  57. } else {
  58. $totalDuration += 5; // 默认5秒
  59. }
  60. $segment_content = getProp($segment, 'segment_content');
  61. // 判断是否有尾帧描述,如果有则去掉这部分内容
  62. if (strpos($segment_content, '尾帧') !== false) {
  63. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  64. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  65. }
  66. // 构建分镜信息
  67. $segmentInfo = [
  68. 'segment_id' => getProp($segment, 'segment_id'),
  69. 'segment_number' => getProp($segment, 'segment_number'),
  70. 'segment_content' => $segment_content,
  71. 'description' => getProp($segment, 'description'),
  72. 'composition' => getProp($segment, 'composition'),
  73. 'camera_movement' => getProp($segment, 'camera_movement'),
  74. 'voice_actor' => getProp($segment, 'voice_actor'),
  75. 'dialogue' => getProp($segment, 'dialogue'),
  76. 'frame_type' => getProp($segment, 'frame_type'),
  77. 'scene' => getProp($segment, 'scene'),
  78. 'characters' => getProp($segment, 'characters'),
  79. 'tail_frame' => getProp($segment, 'tail_frame'),
  80. 'emotion' => getProp($segment, 'emotion'),
  81. 'emotion_type' => getProp($segment, 'emotion_type'),
  82. 'gender' => getProp($segment, 'gender'),
  83. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  84. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  85. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  86. 'pitch' => getProp($segment, 'pitch'),
  87. 'voice_name' => getProp($segment, 'voice_name'),
  88. 'voice_type' => getProp($segment, 'voice_type'),
  89. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  90. 'img_url' => getProp($segment, 'img_url'),
  91. 'audio_url' => getProp($segment, 'audio_url'),
  92. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  93. 'video_url' => getProp($segment, 'video_url'),
  94. 'video_duration' => getProp($segment, 'video_duration', 0),
  95. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  96. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  97. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  98. 'current_type' => getProp($segment, 'current_type'),
  99. ];
  100. $actNumber = getProp($segment, 'act_number');
  101. if (isset($acts[$actNumber])) {
  102. $acts[$actNumber]['segments'][] = $segmentInfo;
  103. } else {
  104. $acts[$actNumber] = [
  105. 'act_number' => $actNumber,
  106. 'act_title' => getProp($segment, 'act_title'),
  107. 'act_duration' => getProp($segment, 'act_duration'),
  108. 'segments' => [$segmentInfo]
  109. ];
  110. }
  111. }
  112. return [
  113. 'acts' => array_values($acts),
  114. 'total_duration' => intval(round($totalDuration))
  115. ];
  116. }
  117. /**
  118. * 构建统一的分段数据结构(episodeInfoForAce格式)
  119. * @param array $segments 分段数据数组
  120. * @return array 返回包含acts和total_duration的数组
  121. */
  122. public function buildEpisodeActsStructureForAce($segments) {
  123. $acts = [];
  124. $totalDuration = 0; // 初始化总时长
  125. foreach($segments as $segment) {
  126. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  127. $videoDuration = getProp($segment, 'video_duration');
  128. $actDuration = getProp($segment, 'act_duration');
  129. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  130. $totalDuration += floatval($videoDuration);
  131. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  132. $totalDuration += floatval($actDuration);
  133. } else {
  134. $totalDuration += 5; // 默认5秒
  135. }
  136. // 构建分镜信息
  137. $segmentInfo = [
  138. 'act_id' => getProp($segment, 'id'),
  139. 'act_number' => getProp($segment, 'act_number'),
  140. 'act_title' => getProp($segment, 'act_title'),
  141. 'act_duration' => getProp($segment, 'act_duration'),
  142. 'act_content' => getProp($segment, 'act_content'),
  143. 'video_url' => getProp($segment, 'video_url'),
  144. 'video_duration' => getProp($segment, 'video_duration', 0),
  145. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  146. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  147. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  148. 'current_type' => getProp($segment, 'current_type'),
  149. ];
  150. $acts[] = $segmentInfo;
  151. }
  152. return [
  153. 'acts' => array_values($acts),
  154. 'total_duration' => intval(round($totalDuration))
  155. ];
  156. }
  157. /**
  158. * 验证画面比例是否有效
  159. * @param string $ratio 画面比例
  160. * @return bool
  161. */
  162. public function validateRatio($ratio) {
  163. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  164. }
  165. /**
  166. * 获取画面比例对应的宽高
  167. * @param string $ratio 画面比例
  168. * @return array ['width' => int, 'height' => int]
  169. * @throws \Exception
  170. */
  171. private function getRatioDimensions($ratio) {
  172. if ($ratio && !$this->validateRatio($ratio)) {
  173. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  174. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  175. }
  176. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  177. }
  178. public function createAnime($data) {
  179. $uid = Site::getUid();
  180. $input_art_style = getProp($data, 'art_style');
  181. $file = getProp($data, 'file');
  182. $content = getProp($data, 'content', '');
  183. $bid = getProp($data, 'bid', 0);
  184. $script_id = getProp($data, 'script_id', 0);
  185. $ace_mode = getProp($data, 'ace_mode', 0);
  186. $extra_products = getProp($data, 'products', []);
  187. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  188. if (!is_array($extra_products)) {
  189. Utils::throwError('20003:传入的资产格式不正确');
  190. }
  191. // 替换美术风格
  192. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  193. // 提取文件内容
  194. if ($file) {
  195. $content = $this->DeepSeekService->extractFileContent($file);
  196. if (!$content) {
  197. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  198. }
  199. } elseif ($script_id) {
  200. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  201. if (!$content) {
  202. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  203. }
  204. } elseif ($bid) {
  205. $content = $this->DeepSeekService->getContentByBid($bid);
  206. if (!$content) {
  207. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  208. }
  209. } elseif ($content) {
  210. $content = filterContent($content);
  211. }else {
  212. $content = '';
  213. }
  214. $anime_data = [
  215. 'user_id' => $uid,
  216. 'anime_name' => '新剧本策划',
  217. 'is_multi' => getProp($data, 'is_multi', 1),
  218. 'content' => $content,
  219. 'art_style_type' => $input_art_style,
  220. 'ace_mode' => $ace_mode,
  221. 'script_id' => $script_id,
  222. 'extra_products' => json_encode($extra_products, 256),
  223. 'created_at' => date('Y-m-d H:i:s'),
  224. 'updated_at' => date('Y-m-d H:i:s'),
  225. ];
  226. // 处理文本模型
  227. $model = getProp($data, 'model');
  228. if (!$model) {
  229. // 用户没有输入,使用默认值
  230. $model = 'doubao-seed-2-0-mini-260215';
  231. }
  232. // 验证模型是否在可用模型表中
  233. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  234. $model = 'doubao-seed-2-0-mini-260215';
  235. }
  236. $anime_data['model'] = $model;
  237. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  238. return DB::table('mp_animes')->insertGetId($anime_data);
  239. }
  240. public function chatList($data) {
  241. $uid = Site::getUid();
  242. $anime_name = getProp($data, 'anime_name');
  243. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  244. if ($anime_name) {
  245. $query->where('anime_name', 'like', "%$anime_name%");
  246. }
  247. return $query->orderBy('id', 'desc')->paginate();
  248. }
  249. public function chatHistory($data) {
  250. $anime_id = getProp($data, 'anime_id');
  251. $sequence = getProp($data, 'sequence', 0);
  252. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  253. $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)
  254. ->where('ar.sequence', $sequence)->where('segment_id', 0)->where('act_id', 0)->select('ar.role', 'ar.content', 'ar.created_at', 'ar.episode_id', 'ae.title as episode_title', 'ae.created_at as episode_created_at');
  255. return $query->orderBy('ar.id')->get()->map(function ($value) {
  256. $value = (array)$value;
  257. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  258. $value['created_at'] = transDate($value['created_at']);
  259. $value['episode_created_at'] = transDate($value['episode_created_at']);
  260. return $value;
  261. })->toArray();
  262. }
  263. public function batchSetRoleImg($data) {
  264. $episode_id = getProp($data, 'episode_id');
  265. if (!$episode_id) Utils::throwError('1002:请选择分集');
  266. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  267. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  268. $art_style = getProp($episode, 'art_style');
  269. $anime_id = getProp($episode, 'anime_id');
  270. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  271. $art_style_type = getProp($anime, 'art_style_type');
  272. $character_prefix = '';
  273. $scene_prefix = '';
  274. if ($art_style_type) {
  275. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  276. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  277. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  278. }
  279. foreach ($roles as &$role) {
  280. $role_name = getProp($role, 'role');
  281. if ($role_name == '旁白') continue;
  282. // 优先使用 pic_prompt,如果没有则使用 description
  283. $pic_prompt = getProp($role, 'pic_prompt');
  284. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  285. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  286. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  287. // 参考图地址
  288. $ref_img_url = getProp($role, 'url');
  289. if ($ref_img_url) continue; // 已有图片则跳过
  290. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  291. try {
  292. $params = [
  293. 'prompt' => $description,
  294. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  295. ];
  296. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  297. $task_id = $task->id;
  298. if (!$task_id) {
  299. Utils::throwError("20003:角色({$role_name})生成图片失败");
  300. }
  301. $role['task_id'] = $task_id;
  302. $role['task_status'] = 'processing';
  303. } catch (\Exception $e) {
  304. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  305. Utils::throwError("20003:" . $e->getMessage());
  306. }
  307. }
  308. // 保存角色信息
  309. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  310. 'roles' => json_encode($roles, 256),
  311. 'generate_status' => '执行中',
  312. 'generate_at' => date('Y-m-d H:i:s'),
  313. 'updated_at' => date('Y-m-d H:i:s')
  314. ]);
  315. if (!$boolen) {
  316. Utils::throwError('20003:保存角色信息失败');
  317. }
  318. return $boolen;
  319. }
  320. public function batchSetSceneImg($data) {
  321. $episode_id = getProp($data, 'episode_id');
  322. if (!$episode_id) Utils::throwError('1002:请选择分集');
  323. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  324. $scenes = json_decode(getProp($episode, 'scenes'), true);
  325. $art_style = getProp($episode, 'art_style');
  326. $target_scene = getProp($data, 'target_scene');
  327. $anime_id = getProp($episode, 'anime_id');
  328. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  329. $art_style_type = getProp($anime, 'art_style_type');
  330. $character_prefix = '';
  331. $scene_prefix = '';
  332. if ($art_style_type) {
  333. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  334. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  335. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  336. }
  337. foreach ($scenes as &$scene) {
  338. $scene_name = getProp($scene, 'scene');
  339. if ($scene_name != $target_scene) continue;
  340. // 优先使用 pic_prompt,如果没有则使用 description
  341. $pic_prompt = getProp($scene, 'pic_prompt');
  342. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  343. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  344. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  345. // 参考图地址
  346. $ref_img_url = getProp($scene, 'url');
  347. if ($ref_img_url) continue; // 已有图片则跳过
  348. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  349. try {
  350. $params = [
  351. 'prompt' => $description,
  352. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  353. ];
  354. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  355. $task_id = $task->id;
  356. if (!$task_id) {
  357. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  358. }
  359. $scene['task_id'] = $task_id;
  360. $scene['task_status'] = 'processing';
  361. } catch (\Exception $e) {
  362. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  363. Utils::throwError("20003:" . $e->getMessage());
  364. }
  365. }
  366. // 保存场景信息
  367. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  368. 'scenes' => json_encode($scenes, 256),
  369. 'generate_status' => '执行中',
  370. 'generate_at' => date('Y-m-d H:i:s'),
  371. 'updated_at' => date('Y-m-d H:i:s')
  372. ]);
  373. if (!$boolen) {
  374. Utils::throwError('20003:保存角色信息失败');
  375. }
  376. return $boolen;
  377. }
  378. public function editAnime($data) {
  379. $anime_id = getProp($data, 'anime_id');
  380. $anime_name = trim(getProp($data, 'anime_name'));
  381. // 确认对话名称唯一性
  382. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  383. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  384. }
  385. if (!$anime_id || !$anime_name) {
  386. Utils::throwError('20003:参数异常');
  387. }
  388. return DB::table('mp_animes')->where('id', $anime_id)->update([
  389. 'anime_name' => $anime_name,
  390. 'updated_at' => date('Y-m-d H:i:s')
  391. ]);
  392. // $script_arr =getProp($data, 'script', []);
  393. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  394. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  395. // $anime_id = getProp($data, 'anime_id');
  396. // try {
  397. // DB::beginTransaction();
  398. // $table_data = [
  399. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  400. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  401. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  402. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  403. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  404. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  405. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  406. // 'status' => 3,
  407. // 'start_episode_sequence' => $start_episode_sequence,
  408. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  409. // 'episode_num' => count($script_arr['episodes']),
  410. // 'updated_at' => date('Y-m-d H:i:s')
  411. // ];
  412. // // 保存剧本内容
  413. // if (!empty($anime_id)) {
  414. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  415. // if (!$boolen) {
  416. // dLog('anime')->info('对话保存失败', $table_data);
  417. // Utils::throwError('20003:对话保存失败');
  418. // }
  419. // }else {
  420. // $table['created_at'] = $table_data['updated_at'];
  421. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  422. // if (!$anime_id) {
  423. // dLog('anime')->info('对话保存失败', $table_data);
  424. // Utils::throwError('20003:对话保存失败');
  425. // }
  426. // }
  427. // // 保存分集内容
  428. // // 删除历史分集内容
  429. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  430. // $episodes = [];
  431. // $sequence = 1;
  432. // foreach ($script_arr['episodes'] as $episode) {
  433. // $segment_number = 1;
  434. // foreach($episode['segments'] as $segment) {
  435. // $episodes[] = [
  436. // 'anime_id' => $anime_id,
  437. // 'episode_number' => $episode['episode_number'],
  438. // 'title' => $episode['title'],
  439. // // 'content' => $episode['content'],
  440. // 'content' => '',
  441. // 'segment_number' => $segment_number,
  442. // 'segment_content' => $segment['segment_content'],
  443. // 'sequence' => $sequence,
  444. // 'created_at' => date('Y-m-d H:i:s'),
  445. // 'updated_at' => date('Y-m-d H:i:s')
  446. // ];
  447. // $sequence++;
  448. // $segment_number++;
  449. // }
  450. // }
  451. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  452. // if (!$boolen2) {
  453. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  454. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  455. // Utils::throwError('20003:分集内容保存失败');
  456. // }
  457. // } catch (\Exception $e) {
  458. // DB::rollBack();
  459. // Utils::throwError('20003:'.$e->getMessage());
  460. // }
  461. // DB::commit();
  462. // return true;
  463. }
  464. public function delAnime($data) {
  465. $anime_id = getProp($data, 'anime_id');
  466. if (!$anime_id) {
  467. Utils::throwError('20003:请选择剧本');
  468. }
  469. return DB::table('mp_animes')->where('id', $anime_id)->update([
  470. 'is_deleted' => 1,
  471. 'updated_at' => date('Y-m-d H:i:s')
  472. ]);
  473. }
  474. public function animeDetail($data) {
  475. $uid = Site::getUid();
  476. $anime_id = getProp($data, 'anime_id');
  477. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  478. ->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();
  479. if (!$anime) Utils::throwError('20003:权限不足');
  480. $anime = (array)$anime;
  481. $anime['roles'] = json_decode($anime['roles']);
  482. $anime['scenes'] = json_decode($anime['scenes']);
  483. // 获取分集信息
  484. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  485. ->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"))
  486. ->orderBy('episode_number')->get()->map(function ($value) {
  487. return (array)$value;
  488. })->toArray();
  489. $anime['episodes'] = $episodes;
  490. return $anime;
  491. }
  492. public function episodeInfo($data) {
  493. $uid = Site::getUid();
  494. $anime_id = getProp($data, 'anime_id');
  495. $episode_id = getProp($data, 'episode_id');
  496. if (!$anime_id || !$episode_id) {
  497. Utils::throwError('1002:请选择剧集');
  498. }
  499. // 验证用户权限
  500. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  501. if (!$anime) Utils::throwError('20003:权限不足');
  502. $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();
  503. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  504. $episode = (array)$episode;
  505. $episode['roles'] = json_decode($episode['roles'], true);
  506. // foreach($episode['roles'] as &$item) {
  507. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  508. // }
  509. $episode['scenes'] = json_decode($episode['scenes'], true);
  510. // foreach($episode['scenes'] as &$item) {
  511. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  512. // }
  513. // 获取分镜信息
  514. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  515. ->select('*')->get()->map(function ($value) {
  516. return (array)$value;
  517. })->toArray();
  518. // 使用公共方法构建分镜结构
  519. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  520. $episode['acts'] = $segmentsStructure['acts'];
  521. $episode['total_duration'] = $segmentsStructure['total_duration'];
  522. return $episode;
  523. }
  524. public function episodeInfoForAce($data) {
  525. $anime_id = getProp($data, 'anime_id');
  526. $episode_id = getProp($data, 'episode_id');
  527. if (!$anime_id || !$episode_id) {
  528. Utils::throwError('1002:请选择剧集');
  529. }
  530. $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();
  531. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  532. $episode = (array)$episode;
  533. $episode['roles'] = json_decode($episode['roles'], true);
  534. // foreach($episode['roles'] as &$item) {
  535. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  536. // }
  537. $episode['scenes'] = json_decode($episode['scenes'], true);
  538. // foreach($episode['scenes'] as &$item) {
  539. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  540. // }
  541. // 获取分镜信息
  542. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  543. ->select('*')->get()->map(function ($value) {
  544. return (array)$value;
  545. })->toArray();
  546. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  547. $episode['acts'] = $segmentsStructure['acts'];
  548. $episode['total_duration'] = $segmentsStructure['total_duration'];
  549. return $episode;
  550. }
  551. public function segmentInfo($data) {
  552. $uid = Site::getUid();
  553. $segment_id = getProp($data, 'segment_id');
  554. if (!$segment_id) {
  555. Utils::throwError('1002:请选择分镜');
  556. }
  557. // 获取分镜信息
  558. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  559. // 验证用户权限
  560. if ($segment) {
  561. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  562. if (!$anime) Utils::throwError('20003:权限不足');
  563. }
  564. $result = [
  565. 'segment_id' => getProp($segment, 'segment_id'),
  566. 'segment_number' => getProp($segment, 'segment_number'),
  567. 'segment_content' => getProp($segment, 'segment_content'),
  568. 'description' => getProp($segment, 'description'),
  569. 'composition' => getProp($segment, 'composition'),
  570. 'camera_movement' => getProp($segment, 'camera_movement'),
  571. 'voice_actor' => getProp($segment, 'voice_actor'),
  572. 'dialogue' => getProp($segment, 'dialogue'),
  573. 'frame_type' => getProp($segment, 'frame_type'),
  574. 'scene' => getProp($segment, 'scene'),
  575. 'characters' => getProp($segment, 'characters'),
  576. 'tail_frame' => getProp($segment, 'tail_frame'),
  577. 'emotion' => getProp($segment, 'emotion'),
  578. 'emotion_type' => getProp($segment, 'emotion_type'),
  579. 'gender' => getProp($segment, 'gender'),
  580. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  581. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  582. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  583. 'pitch' => getProp($segment, 'pitch'),
  584. 'voice_name' => getProp($segment, 'voice_name'),
  585. 'voice_type' => getProp($segment, 'voice_type'),
  586. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  587. 'img_url' => getProp($segment, 'img_url'),
  588. 'video_url' => getProp($segment, 'video_url'),
  589. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  590. ];
  591. return $result;
  592. }
  593. public function copyEpisodeVersion($data) {
  594. $episode_id = getProp($data, 'episode_id');
  595. $uid = Site::getUid();
  596. $cpid = Site::getCpid();
  597. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  598. if (!$episode) Utils::throwError('20003:该剧集不存在');
  599. $episode = (array)$episode;
  600. $anime_id = $episode['anime_id'];
  601. $episode_number = $episode['episode_number'];
  602. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  603. $sequence = $count + 1;
  604. unset($episode['id']);
  605. $now = date('Y-m-d H:i:s');
  606. $episode['created_at'] = $now;
  607. $episode['updated_at'] = $now;
  608. $episode['is_default'] = 1;
  609. // 获取版本中含有"(副本"字样的个数
  610. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  611. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  612. $episode['sequence'] = $sequence;
  613. $episode['is_generated'] = 0;
  614. $episode['cpid'] = $cpid;
  615. // 获取ace_mode
  616. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  617. try {
  618. DB::beginTransaction();
  619. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  620. // 新增副本
  621. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  622. if (!$new_episode_id) {
  623. Utils::throwError('20003:创建副本失败!');
  624. }
  625. // 获取分镜数据并准备插入
  626. $segments_for_insert = DB::table('mp_episode_segments')
  627. ->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')
  628. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  629. $item = (array)$item;
  630. $item['episode_id'] = $new_episode_id;
  631. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  632. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  633. return $item;
  634. })->toArray();
  635. // 写入分镜数据
  636. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  637. if (!$boolen2) {
  638. Utils::throwError('20003:写入分镜数据失败!');
  639. }
  640. // 写入对话历史
  641. $records = [
  642. [
  643. 'uid' => $uid,
  644. 'anime_id' => $anime_id,
  645. 'role' => 'user',
  646. 'content' => '创建副本',
  647. 'sequence' => $episode_number,
  648. 'episode_id' => $new_episode_id,
  649. 'created_at' => $now,
  650. 'updated_at' => $now
  651. ],
  652. [
  653. 'uid' => $uid,
  654. 'anime_id' => $anime_id,
  655. 'role' => 'assistant',
  656. 'content' => '好的,已为您创建副本',
  657. 'sequence' => $episode_number,
  658. 'episode_id' => $new_episode_id,
  659. 'created_at' => $now,
  660. 'updated_at' => $now
  661. ]
  662. ];
  663. $boolen3 = DB::table('mp_anime_records')->insert($records);
  664. if (!$boolen3) {
  665. Utils::throwError('20003:对话记录保存失败');
  666. }
  667. }catch (\Exception $e) {
  668. DB::rollBack();
  669. Utils::throwError('20003:'.$e->getMessage());
  670. }
  671. DB::commit();
  672. // 构建与 episodeInfo 方法一致的返回数据结构
  673. $result = [
  674. 'episode_id' => $new_episode_id,
  675. 'anime_id' => $anime_id,
  676. 'episode_number' => $episode_number,
  677. 'title' => $episode['title'],
  678. 'intro' => $episode['intro'],
  679. 'art_style' => $episode['art_style'],
  680. 'roles' => json_decode($episode['roles'], true),
  681. 'scenes' => json_decode($episode['scenes'], true),
  682. 'is_generated' => (int)$episode['is_generated']
  683. ];
  684. if ((int)$ace_mode === 1) {
  685. // 获取分镜信息
  686. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  687. ->select('*')->get()->map(function ($value) {
  688. return (array)$value;
  689. })->toArray();
  690. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  691. }else {
  692. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  693. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  694. }
  695. $result['acts'] = $segmentsStructure['acts'];
  696. $result['total_duration'] = $segmentsStructure['total_duration'];
  697. return $result;
  698. }
  699. public function episodeVersions($data) {
  700. $anime_id = getProp($data, 'anime_id');
  701. $episode_id = getProp($data, 'episode_id');
  702. if (!$anime_id || !$episode_id) {
  703. Utils::throwError('1002:请选择剧集');
  704. }
  705. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  706. $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) {
  707. return (array)$value;
  708. })->toArray();
  709. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  710. foreach($episodes as &$episode) {
  711. $episode['version'] = 'V'.$episode['sequence'];
  712. $episode['roles'] = json_decode($episode['roles'], true);
  713. $episode['scenes'] = json_decode($episode['scenes'], true);
  714. // 获取分镜信息
  715. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  716. ->select('*')->get()->map(function ($value) {
  717. return (array)$value;
  718. })->toArray();
  719. // 使用公共方法构建分镜结构
  720. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  721. $episode['acts'] = $segmentsStructure['acts'];
  722. $episode['total_duration'] = $segmentsStructure['total_duration'];
  723. }
  724. return $episodes;
  725. }
  726. public function bindEpisodeVersion($data) {
  727. $episode_id = getProp($data, 'episode_id');
  728. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  729. if (!$episode) Utils::throwError('20003:该剧集不存在');
  730. $episode = (array)$episode;
  731. if ((int)$episode['is_default'] === 1) return true;
  732. try {
  733. DB::beginTransaction();
  734. // 移除is_default标志
  735. $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')]);
  736. if (!$boolen) {
  737. Utils::throwError('20003:更新失败!');
  738. }
  739. // 绑定副本
  740. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  741. if (!$boolen2) {
  742. Utils::throwError('20003:绑定失败!');
  743. }
  744. }catch (\Exception $e) {
  745. DB::rollBack();
  746. Utils::throwError('20003:'.$e->getMessage());
  747. }
  748. DB::commit();
  749. return true;
  750. }
  751. public function chatChangeImg($data) {
  752. $segment_id = getProp($data, 'segment_id');
  753. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  754. $prompt = getProp($data, 'prompt');
  755. if (!$prompt || !$segment_id) {
  756. Utils::throwError('1002:请输入提示词,并且选择分镜');
  757. }
  758. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  759. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  760. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  761. else $ref_img_url = '';
  762. // $ref_img_url = '';
  763. if (empty($prompt)) {
  764. if (empty($ref_img_url)) {
  765. $prompt = getProp($segment, 'segment_content');
  766. }else {
  767. $prompt = '请根据图片生成';
  768. }
  769. }
  770. $anime_id = getProp($segment, 'anime_id');
  771. $episode_id = getProp($segment, 'episode_id');
  772. $episode_number = getProp($segment, 'episode_number');
  773. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  774. $ratio = getProp($data, 'ratio');
  775. if (!$ratio) {
  776. $ratio = getProp($episode, 'ratio');
  777. if (!$ratio) $ratio = '9:16';
  778. }
  779. $art_style = getProp($episode, 'art_style');
  780. if ($art_style) {
  781. $prompt = "美术风格:{$art_style}\n{$prompt}";
  782. }
  783. $dimensions = $this->getRatioDimensions($ratio);
  784. $width = $dimensions['width'];
  785. $height = $dimensions['height'];
  786. try {
  787. $params = [
  788. 'alias_segment_id' => $segment_id,
  789. 'prompt' => $prompt,
  790. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  791. 'width' => $width,
  792. 'height' => $height
  793. ];
  794. // 优化提示词(不要生成字幕)
  795. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  796. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  797. $task_id = $task->id;
  798. if (!$task_id) {
  799. Utils::throwError("20003:生成图片失败");
  800. }
  801. // 更新任务ID
  802. $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')]);
  803. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  804. } catch (\Exception $e) {
  805. Utils::throwError("20003:" . $e->getMessage());
  806. }
  807. // 创建任务之后先暂停10s等待异步任务完成
  808. sleep(10);
  809. $img_url = $this->loopGetPicTaskResult($task_id);
  810. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  811. // 图片生成后新增对话记录
  812. try {
  813. $uid = Site::getUid();
  814. $now = date('Y-m-d H:i:s');
  815. // 使用AI反推图片提示词
  816. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  817. // 保存对话记录
  818. $records = [
  819. [
  820. 'uid' => $uid,
  821. 'anime_id' => $anime_id,
  822. 'sequence' => $episode_number,
  823. 'role' => 'user',
  824. 'content' => $prompt,
  825. 'segment_id' => $segment_id,
  826. 'image_url' => '',
  827. 'created_at' => $now,
  828. 'updated_at' => $now
  829. ],
  830. [
  831. 'uid' => $uid,
  832. 'anime_id' => $anime_id,
  833. 'sequence' => $episode_number,
  834. 'role' => 'assistant',
  835. 'content' => $pic_prompt,
  836. 'segment_id' => $segment_id,
  837. 'image_url' => $img_url,
  838. 'created_at' => $now,
  839. 'updated_at' => $now
  840. ]
  841. ];
  842. DB::table('mp_anime_records')->insert($records);
  843. } catch (\Exception $e) {
  844. // 记录日志但不影响主流程
  845. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  846. 'segment_id' => $segment_id,
  847. 'img_url' => $img_url
  848. ]);
  849. logDB('anime', 'error', '保存对话记录失败', [
  850. 'segment_id' => $segment_id,
  851. 'img_url' => $img_url,
  852. 'error' => $e->getMessage()
  853. ]);
  854. }
  855. return $img_url;
  856. }
  857. public function segmentChatHistory($data) {
  858. $segment_id = getProp($data, 'segment_id');
  859. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  860. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'created_at');
  861. $chat = $query->orderBy('id')->get()->map(function ($value) {
  862. $value = (array)$value;
  863. $value['created_at'] = transDate($value['created_at']);
  864. return $value;
  865. })->toArray();
  866. // 获取历史图片
  867. $url = [];
  868. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  869. foreach($pic_history as $task) {
  870. $result_url = getProp($task, 'result_url');
  871. if (is_json($result_url)) {
  872. $url = array_merge($url, json_decode($result_url, true));
  873. }else {
  874. $url[] = $result_url;
  875. }
  876. }
  877. // 获取历史视频
  878. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  879. foreach($video_history as $task) {
  880. $result_url = getProp($task, 'compressed_url');
  881. if (is_json($result_url)) {
  882. $url = array_merge($url, json_decode($result_url, true));
  883. }else {
  884. $url[] = $result_url;
  885. }
  886. }
  887. return compact('chat', 'url');
  888. }
  889. public function changeEpisodeRoles($data) {
  890. $anime_id = getProp($data, 'anime_id');
  891. $episode_id = getProp($data, 'episode_id');
  892. $target_roles = getProp($data, 'roles');
  893. $is_deleted = getProp($data, 'is_deleted', 0);
  894. // 参数验证
  895. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  896. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  897. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  898. // 验证剧集是否存在
  899. $episode = DB::table('mp_anime_episodes')
  900. ->where('anime_id', $anime_id)
  901. ->where('id', $episode_id)
  902. ->first();
  903. if (!$episode) Utils::throwError('20003:该剧集不存在');
  904. $roles = json_decode(getProp($episode, 'roles'), true);
  905. // 获取anime信息,检查是否有关联的script_id
  906. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  907. if (!$anime) Utils::throwError('20003:动漫不存在');
  908. $script_id = getProp($anime, 'script_id');
  909. $episode_number = getProp($episode, 'episode_number', 1);
  910. $uid = Site::getUid();
  911. $cpid = Site::getCpid();
  912. try {
  913. $target_role_name = getProp($target_roles, 'role');
  914. // 如果是删除操作
  915. if ($is_deleted == 1) {
  916. // 从角色列表中移除该角色
  917. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  918. return getProp($role, 'role') !== $target_role_name;
  919. }));
  920. // 更新角色列表
  921. $result = DB::table('mp_anime_episodes')
  922. ->where('anime_id', $anime_id)
  923. ->where('id', $episode_id)
  924. ->update([
  925. 'roles' => json_encode($roles, 256),
  926. 'updated_at' => date('Y-m-d H:i:s')
  927. ]);
  928. if ($result === false) {
  929. Utils::throwError('20003:删除角色失败');
  930. }
  931. } else {
  932. // 新增或更新操作
  933. $role_found = false;
  934. $is_new_role = false;
  935. // 查找并更新已存在的角色
  936. foreach($roles as &$role) {
  937. if (getProp($role, 'role') === $target_role_name) {
  938. $role = $target_roles;
  939. $role_found = true;
  940. break;
  941. }
  942. }
  943. // 如果角色不存在,则新增
  944. if (!$role_found) {
  945. $roles[] = $target_roles;
  946. $is_new_role = true;
  947. }
  948. // 更新角色列表
  949. $result = DB::table('mp_anime_episodes')
  950. ->where('anime_id', $anime_id)
  951. ->where('id', $episode_id)
  952. ->update([
  953. 'roles' => json_encode($roles, 256),
  954. 'updated_at' => date('Y-m-d H:i:s')
  955. ]);
  956. if ($result === false) {
  957. Utils::throwError('20003:更新角色列表失败');
  958. }
  959. // 同步更新分镜表中对应主体的音色信息
  960. $voice_name = getProp($target_roles, 'voice_name');
  961. $voice_type = getProp($target_roles, 'voice_type');
  962. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  963. DB::table('mp_episode_segments')
  964. ->where('anime_id', $anime_id)
  965. ->where('episode_id', $episode_id)
  966. ->where('voice_actor', $target_role_name)
  967. ->update([
  968. 'voice_name' => $voice_name,
  969. 'voice_type' => $voice_type,
  970. 'voice_audio_url' => $voice_audio_url,
  971. 'updated_at' => date('Y-m-d H:i:s')
  972. ]);
  973. // 如果有关联的script_id,则同步到mp_products表
  974. if ($script_id) {
  975. // 查询剧本信息
  976. $script = DB::table('mp_scripts')
  977. ->where('id', $script_id)
  978. ->where('is_deleted', 0)
  979. ->first();
  980. if ($script) {
  981. $script_name = $script->script_name ?? 'script_' . $script_id;
  982. $product_name = getProp($target_roles, 'role');
  983. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  984. $url = getProp($target_roles, 'url', '');
  985. $product_type = 1; // 1=角色
  986. // 查找或创建以script_name命名的文件夹
  987. $folder = DB::table('mp_products')
  988. ->where('cpid', $cpid)
  989. ->where('type', 2) // 文件夹类型
  990. ->where('product', $product_type) // 角色类型
  991. ->where('product_name', $script_name)
  992. ->where('parent_id', 0)
  993. ->where('is_deleted', 0)
  994. ->first();
  995. if (!$folder) {
  996. // 创建文件夹
  997. $folder_id = DB::table('mp_products')->insertGetId([
  998. 'user_id' => $uid,
  999. 'cpid' => $cpid,
  1000. 'type' => 2, // 文件夹
  1001. 'product' => $product_type, // 角色类型
  1002. 'parent_id' => 0,
  1003. 'level' => 1,
  1004. 'product_name' => $script_name,
  1005. 'sort_order' => time(),
  1006. 'is_deleted' => 0,
  1007. 'created_at' => date('Y-m-d H:i:s'),
  1008. 'updated_at' => date('Y-m-d H:i:s')
  1009. ]);
  1010. } else {
  1011. $folder_id = $folder->id;
  1012. }
  1013. // 查找该文件夹下是否已存在同名资产
  1014. $existing_product = DB::table('mp_products')
  1015. ->where('cpid', $cpid)
  1016. ->where('type', 1) // 资产类型
  1017. ->where('product', $product_type)
  1018. ->where('parent_id', $folder_id)
  1019. ->where('product_name', $product_name)
  1020. ->where('is_deleted', 0)
  1021. ->first();
  1022. if ($existing_product) {
  1023. // 更新已存在的资产
  1024. $updateData = [
  1025. 'pic_task_status' => '生成成功',
  1026. ];
  1027. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1028. if ($url) $updateData['url'] = $url;
  1029. // 处理versions字段
  1030. $versions = getProp($target_roles, 'versions', []);
  1031. if ($versions && is_array($versions)) {
  1032. $updateData['versions'] = json_encode($versions, 256);
  1033. }
  1034. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1035. DB::table('mp_products')
  1036. ->where('id', $existing_product->id)
  1037. ->update($updateData);
  1038. $product_id = $existing_product->id;
  1039. } else {
  1040. // 创建新资产
  1041. $versions = getProp($target_roles, 'versions', []);
  1042. $product_id = DB::table('mp_products')->insertGetId([
  1043. 'user_id' => $uid,
  1044. 'cpid' => $cpid,
  1045. 'type' => 1, // 资产
  1046. 'product' => $product_type, // 角色
  1047. 'parent_id' => $folder_id,
  1048. 'level' => 2,
  1049. 'product_name' => $product_name,
  1050. 'url' => $url,
  1051. 'pic_prompt' => $pic_prompt,
  1052. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1053. 'sort_order' => time(),
  1054. 'is_deleted' => 0,
  1055. 'pic_task_status' => '生成成功',
  1056. 'created_at' => date('Y-m-d H:i:s'),
  1057. 'updated_at' => date('Y-m-d H:i:s')
  1058. ]);
  1059. }
  1060. // 建立或更新绑定关系
  1061. $existing_mapping = DB::table('mp_script_product_mappings')
  1062. ->where('script_id', $script_id)
  1063. ->where('product_id', $product_id)
  1064. ->where('episode_number', $episode_number)
  1065. ->first();
  1066. if (!$existing_mapping) {
  1067. // 创建绑定关系
  1068. DB::table('mp_script_product_mappings')->insert([
  1069. 'script_id' => $script_id,
  1070. 'product_id' => $product_id,
  1071. 'episode_number' => $episode_number,
  1072. 'created_at' => date('Y-m-d H:i:s'),
  1073. 'updated_at' => date('Y-m-d H:i:s')
  1074. ]);
  1075. }
  1076. }
  1077. }
  1078. }
  1079. } catch (\Exception $e) {
  1080. dLog('anime')->error('更新剧集角色失败', [
  1081. 'anime_id' => $anime_id,
  1082. 'episode_id' => $episode_id,
  1083. 'error' => $e->getMessage()
  1084. ]);
  1085. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1086. }
  1087. return true;
  1088. }
  1089. public function changeEpisodeScenes($data) {
  1090. $anime_id = getProp($data, 'anime_id');
  1091. $episode_id = getProp($data, 'episode_id');
  1092. $target_scenes = getProp($data, 'scenes');
  1093. $is_deleted = getProp($data, 'is_deleted', 0);
  1094. // 参数验证
  1095. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1096. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1097. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1098. // 验证剧集是否存在
  1099. $episode = DB::table('mp_anime_episodes')
  1100. ->where('anime_id', $anime_id)
  1101. ->where('id', $episode_id)
  1102. ->first();
  1103. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1104. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1105. // 获取anime信息,检查是否有关联的script_id
  1106. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1107. if (!$anime) Utils::throwError('20003:动漫不存在');
  1108. $script_id = getProp($anime, 'script_id');
  1109. $episode_number = getProp($episode, 'episode_number', 1);
  1110. $uid = Site::getUid();
  1111. $cpid = Site::getCpid();
  1112. try {
  1113. $target_scene_name = getProp($target_scenes, 'scene');
  1114. // 如果是删除操作
  1115. if ($is_deleted == 1) {
  1116. // 从场景列表中移除该场景
  1117. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1118. return getProp($scene, 'scene') !== $target_scene_name;
  1119. }));
  1120. // 更新场景列表
  1121. $result = DB::table('mp_anime_episodes')
  1122. ->where('anime_id', $anime_id)
  1123. ->where('id', $episode_id)
  1124. ->update([
  1125. 'scenes' => json_encode($scenes, 256),
  1126. 'updated_at' => date('Y-m-d H:i:s')
  1127. ]);
  1128. if ($result === false) {
  1129. Utils::throwError('20003:删除场景失败');
  1130. }
  1131. } else {
  1132. // 新增或更新操作
  1133. $scene_found = false;
  1134. $is_new_scene = false;
  1135. // 查找并更新已存在的场景
  1136. foreach($scenes as &$scene) {
  1137. if (getProp($scene, 'scene') === $target_scene_name) {
  1138. $scene = $target_scenes;
  1139. $scene_found = true;
  1140. break;
  1141. }
  1142. }
  1143. // 如果场景不存在,则新增
  1144. if (!$scene_found) {
  1145. $scenes[] = $target_scenes;
  1146. $is_new_scene = true;
  1147. }
  1148. // 更新场景列表
  1149. $result = DB::table('mp_anime_episodes')
  1150. ->where('anime_id', $anime_id)
  1151. ->where('id', $episode_id)
  1152. ->update([
  1153. 'scenes' => json_encode($scenes, 256),
  1154. 'updated_at' => date('Y-m-d H:i:s')
  1155. ]);
  1156. if ($result === false) {
  1157. Utils::throwError('20003:更新场景列表失败');
  1158. }
  1159. // 如果有关联的script_id,则同步到mp_products表
  1160. if ($script_id) {
  1161. // 查询剧本信息
  1162. $script = DB::table('mp_scripts')
  1163. ->where('id', $script_id)
  1164. ->where('is_deleted', 0)
  1165. ->first();
  1166. if ($script) {
  1167. $script_name = $script->script_name ?? 'script_' . $script_id;
  1168. $product_name = getProp($target_scenes, 'scene');
  1169. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1170. $url = getProp($target_scenes, 'url', '');
  1171. $product_type = 2; // 2=场景
  1172. // 查找或创建以script_name命名的文件夹
  1173. $folder = DB::table('mp_products')
  1174. ->where('cpid', $cpid)
  1175. ->where('type', 2) // 文件夹类型
  1176. ->where('product', $product_type) // 场景类型
  1177. ->where('product_name', $script_name)
  1178. ->where('parent_id', 0)
  1179. ->where('is_deleted', 0)
  1180. ->first();
  1181. if (!$folder) {
  1182. // 创建文件夹
  1183. $folder_id = DB::table('mp_products')->insertGetId([
  1184. 'user_id' => $uid,
  1185. 'cpid' => $cpid,
  1186. 'type' => 2, // 文件夹
  1187. 'product' => $product_type, // 场景类型
  1188. 'parent_id' => 0,
  1189. 'level' => 1,
  1190. 'product_name' => $script_name,
  1191. 'sort_order' => time(),
  1192. 'is_deleted' => 0,
  1193. 'created_at' => date('Y-m-d H:i:s'),
  1194. 'updated_at' => date('Y-m-d H:i:s')
  1195. ]);
  1196. } else {
  1197. $folder_id = $folder->id;
  1198. }
  1199. // 查找该文件夹下是否已存在同名资产
  1200. $existing_product = DB::table('mp_products')
  1201. ->where('cpid', $cpid)
  1202. ->where('type', 1) // 资产类型
  1203. ->where('product', $product_type)
  1204. ->where('parent_id', $folder_id)
  1205. ->where('product_name', $product_name)
  1206. ->where('is_deleted', 0)
  1207. ->first();
  1208. if ($existing_product) {
  1209. // 更新已存在的资产
  1210. $updateData = [
  1211. 'pic_task_status' => '生成成功'
  1212. ];
  1213. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1214. if ($url) $updateData['url'] = $url;
  1215. // 处理versions字段
  1216. $versions = getProp($target_scenes, 'versions', []);
  1217. if ($versions && is_array($versions)) {
  1218. $updateData['versions'] = json_encode($versions, 256);
  1219. }
  1220. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1221. DB::table('mp_products')
  1222. ->where('id', $existing_product->id)
  1223. ->update($updateData);
  1224. $product_id = $existing_product->id;
  1225. } else {
  1226. // 创建新资产
  1227. $versions = getProp($target_scenes, 'versions', []);
  1228. $product_id = DB::table('mp_products')->insertGetId([
  1229. 'user_id' => $uid,
  1230. 'cpid' => $cpid,
  1231. 'type' => 1, // 资产
  1232. 'product' => $product_type, // 场景
  1233. 'parent_id' => $folder_id,
  1234. 'level' => 2,
  1235. 'product_name' => $product_name,
  1236. 'url' => $url,
  1237. 'pic_prompt' => $pic_prompt,
  1238. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1239. 'sort_order' => time(),
  1240. 'is_deleted' => 0,
  1241. 'pic_task_status' => '生成成功',
  1242. 'created_at' => date('Y-m-d H:i:s'),
  1243. 'updated_at' => date('Y-m-d H:i:s')
  1244. ]);
  1245. }
  1246. // 建立或更新绑定关系
  1247. $existing_mapping = DB::table('mp_script_product_mappings')
  1248. ->where('script_id', $script_id)
  1249. ->where('product_id', $product_id)
  1250. ->where('episode_number', $episode_number)
  1251. ->first();
  1252. if (!$existing_mapping) {
  1253. // 创建绑定关系
  1254. DB::table('mp_script_product_mappings')->insert([
  1255. 'script_id' => $script_id,
  1256. 'product_id' => $product_id,
  1257. 'episode_number' => $episode_number,
  1258. 'created_at' => date('Y-m-d H:i:s'),
  1259. 'updated_at' => date('Y-m-d H:i:s')
  1260. ]);
  1261. }
  1262. }
  1263. }
  1264. }
  1265. } catch (\Exception $e) {
  1266. dLog('anime')->error('更新剧集场景失败', [
  1267. 'anime_id' => $anime_id,
  1268. 'episode_id' => $episode_id,
  1269. 'error' => $e->getMessage()
  1270. ]);
  1271. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1272. }
  1273. return true;
  1274. }
  1275. public function editSegment($data) {
  1276. $segment_id = getProp($data, 'segment_id');
  1277. $segment_content = getProp($data, 'segment_content');
  1278. $image_url = getProp($data, 'image_url');
  1279. $video_url = getProp($data, 'video_url');
  1280. // 参数验证
  1281. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1282. // 验证分镜是否存在
  1283. $segment = DB::table('mp_episode_segments')
  1284. ->where('segment_id', $segment_id)
  1285. ->first();
  1286. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1287. $dubTaskId = 0;
  1288. try {
  1289. DB::beginTransaction();
  1290. // 准备更新数据
  1291. $update_data = [
  1292. 'updated_at' => date('Y-m-d H:i:s')
  1293. ];
  1294. if ($segment_content) {
  1295. // 先将segment_content赋值到update_data
  1296. $update_data['segment_content'] = $segment_content;
  1297. // 使用现有方法分析segment_content,提取各个字段
  1298. $this->handleSegmentContent($update_data);
  1299. // 如果有对话内容,创建视频配音合成任务
  1300. $dialogue = getProp($update_data, 'dialogue');
  1301. if (!empty($dialogue)) {
  1302. $now = date('Y-m-d H:i:s');
  1303. $generate_json = [
  1304. 'text' => $dialogue,
  1305. 'role' => getProp($update_data, 'voice_actor'),
  1306. 'voice_type' => getProp($update_data, 'voice_type'),
  1307. 'voice_name' => getProp($update_data, 'voice_name'),
  1308. 'emotion' => getProp($update_data, 'emotion'),
  1309. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1310. 'gender' => getProp($update_data, 'gender'),
  1311. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1312. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1313. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1314. 'pitch' => getProp($update_data, 'pitch', 0),
  1315. ];
  1316. // 插入视频配音合成任务
  1317. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1318. 'alias_segment_id' => $segment_id,
  1319. 'generate_status' => '执行中',
  1320. 'audio_url' => '',
  1321. 'generate_json' => json_encode($generate_json, 256),
  1322. 'created_at' => $now,
  1323. 'updated_at' => $now,
  1324. ]);
  1325. if (!$dubTaskId) {
  1326. Utils::throwError('20003:创建配音任务失败!');
  1327. }
  1328. $update_data['audio_url'] = '';
  1329. } else {
  1330. // dialogue为空时,直接写入默认音频信息
  1331. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1332. $update_data['audio_duration'] = 2.0;
  1333. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1334. }
  1335. }
  1336. if ($image_url) {
  1337. $update_data['img_url'] = $image_url;
  1338. // 同时写入一个简单的图片生成任务
  1339. $pic_task = [
  1340. 'alias_segment_id' => $segment_id,
  1341. 'ref_img_url' => json_encode([]),
  1342. 'status' => 'success',
  1343. 'result_url' => json_encode([$image_url], 256),
  1344. 'model' => '',
  1345. 'created_at' => date('Y-m-d H:i:s'),
  1346. 'updated_at' => date('Y-m-d H:i:s'),
  1347. ];
  1348. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1349. }
  1350. if ($video_url) {
  1351. $update_data['origin_video_url'] = $video_url;
  1352. $compressed_video_url = compressVideo($video_url);
  1353. $update_data['current_type'] = 2;
  1354. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1355. // 同时写入一个简单的视频生成任务
  1356. $video_task = [
  1357. 'alias_segment_id' => $segment_id,
  1358. 'status' => 'success',
  1359. 'result_url' => $update_data['origin_video_url'],
  1360. 'compressed_url' => $update_data['video_url'],
  1361. 'created_at' => date('Y-m-d H:i:s'),
  1362. 'updated_at' => date('Y-m-d H:i:s'),
  1363. ];
  1364. DB::table('mp_generate_video_tasks')->insert($video_task);
  1365. }
  1366. // 更新分镜信息
  1367. $result = DB::table('mp_episode_segments')
  1368. ->where('segment_id', $segment_id)
  1369. ->update($update_data);
  1370. if ($result === false) {
  1371. Utils::throwError('20003:更新分镜剧本失败');
  1372. }
  1373. DB::commit();
  1374. // 如果有创建音频生成任务则调用API
  1375. if ($dubTaskId) {
  1376. // 请求远程服务器执行生成
  1377. $client = new Client(['timeout' => 300, 'verify' => false]);
  1378. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1379. $response = $result->getBody()->getContents();
  1380. $response_arr = json_decode($response, true);
  1381. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1382. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1383. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1384. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1385. Utils::throwError('20003:火山生成音频失败');
  1386. }
  1387. }
  1388. return true;
  1389. } catch (\Exception $e) {
  1390. DB::rollBack();
  1391. dLog('anime')->error('更新分镜剧本失败', [
  1392. 'segment_id' => $segment_id,
  1393. 'error' => $e->getMessage()
  1394. ]);
  1395. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1396. }
  1397. }
  1398. public function batchSetSegmentPics($data) {
  1399. $anime_id = getProp($data, 'anime_id');
  1400. $episode_id = getProp($data, 'episode_id');
  1401. $ratio = getProp($data, 'ratio');
  1402. $dimensions = $this->getRatioDimensions($ratio);
  1403. $width = $dimensions['width'];
  1404. $height = $dimensions['height'];
  1405. if (!$anime_id || !$episode_id) {
  1406. Utils::throwError('1002:请选择剧集');
  1407. }
  1408. // 获取剧集信息
  1409. $episode = DB::table('mp_anime_episodes')
  1410. ->where('anime_id', $anime_id)
  1411. ->where('id', $episode_id)
  1412. ->where('is_default', 1)
  1413. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1414. ->first();
  1415. if (!$episode) {
  1416. Utils::throwError('20003:该剧集不存在');
  1417. }
  1418. $model = getProp($data, 'model');
  1419. if (!$model) {
  1420. $model = getProp($episode, 'image_model');
  1421. if (!$model) {
  1422. // episode表也没有,使用默认值
  1423. $model = 'doubao-seedream-5-0-lite-260128';
  1424. }
  1425. }
  1426. // 验证模型是否在可用模型表中
  1427. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1428. $model = 'doubao-seedream-5-0-lite-260128';
  1429. }
  1430. $roles = json_decode(getProp($episode, 'roles'), true);
  1431. if (!$roles) {
  1432. Utils::throwError('20003:角色信息格式错误');
  1433. }
  1434. // 构建角色名称到参考图的映射
  1435. $role_map = [];
  1436. foreach ($roles as $role) {
  1437. $role_name = getProp($role, 'role');
  1438. $role_url = getProp($role, 'url');
  1439. if (!empty($role_name) && !empty($role_url)) {
  1440. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1441. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1442. // $role_map[$base_name] = $role_url;
  1443. // 同时保存完整名称的映射
  1444. $role_map[$role_name] = $role_url;
  1445. }
  1446. }
  1447. $scenes = json_decode(getProp($episode, 'roles'), true);
  1448. if (!$scenes) {
  1449. Utils::throwError('20003:场景信息格式错误');
  1450. }
  1451. // 构建角色名称到参考图的映射
  1452. $scene_map = [];
  1453. foreach ($scenes as $scene) {
  1454. $scene_name = getProp($scene, 'scene');
  1455. $scene_url = getProp($scene, 'url');
  1456. if (!empty($scene_name) && !empty($scene_url)) {
  1457. $scene_map[$scene_name] = $scene_url;
  1458. }
  1459. }
  1460. // 获取所有分镜信息
  1461. $segments = DB::table('mp_episode_segments')
  1462. ->where('anime_id', $anime_id)
  1463. ->where('episode_id', $episode_id)
  1464. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1465. ->orderBy('segment_number')
  1466. ->get()
  1467. ->toArray();
  1468. if (empty($segments)) {
  1469. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1470. }
  1471. // 保存图片比例
  1472. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1473. $updated_segments = [];
  1474. $failed_segments = [];
  1475. // 批量为每个分镜生成图片任务
  1476. foreach ($segments as $segment) {
  1477. $segment_id = $segment->segment_id;
  1478. $segment_content = $segment->segment_content;
  1479. if (empty($segment_content)) {
  1480. $failed_segments[] = [
  1481. 'segment_id' => $segment_id,
  1482. 'error' => '分镜内容为空'
  1483. ];
  1484. continue;
  1485. }
  1486. try {
  1487. $dubTaskId = 0;
  1488. // 解析分镜内容,提取画面描述作为主要提示词
  1489. $prompt = $segment_content;
  1490. $ref_img_urls = [];
  1491. // 分镜场景
  1492. $scene = getProp($segment, 'scene');
  1493. $matched_scene = '';
  1494. if (isset($scene_map[$scene])) {
  1495. $img_index = count($ref_img_urls) + 1;
  1496. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1497. $ref_img_urls[] = $scene_map[$scene];
  1498. $matched_scene = $scene;
  1499. }
  1500. // 分镜角色
  1501. $characters = getProp($segment, 'characters');
  1502. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1503. $roles = explode(',', $characters);
  1504. // 从分镜内容中提取涉及的角色
  1505. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1506. // 获取匹配角色的参考图
  1507. foreach ($segment_characters as $character) {
  1508. if (isset($role_map[$character])) {
  1509. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1510. $img_index = count($ref_img_urls) + 1;
  1511. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1512. $ref_img_urls[] = $role_map[$character];
  1513. }
  1514. }
  1515. // 如果没有找到匹配的角色参考图,不使用参考图
  1516. if (empty($ref_img_urls)) {
  1517. $ref_img_urls = [];
  1518. }
  1519. // 准备生成任务参数
  1520. $params = [
  1521. 'model' => $model,
  1522. 'alias_segment_id' => $segment_id,
  1523. 'prompt' => $prompt,
  1524. 'ref_img_urls' => $ref_img_urls,
  1525. 'width' => $width,
  1526. 'height' => $height,
  1527. ];
  1528. // 优化提示词(不要生成字幕)
  1529. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1530. // $task_id = mt_rand(100000, 999999);
  1531. // 调用AI图片生成服务
  1532. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1533. $task_id = $task->id;
  1534. if (!$task_id) {
  1535. $failed_segments[] = [
  1536. 'segment_id' => $segment_id,
  1537. 'error' => '创建生成任务失败'
  1538. ];
  1539. continue;
  1540. }
  1541. $update_data = [
  1542. 'pic_task_id' => $task_id,
  1543. 'pic_task_status' => '生成中',
  1544. 'audio_url' => '',
  1545. 'updated_at' => date('Y-m-d H:i:s')
  1546. ];
  1547. // 如果有对话内容,创建视频配音合成任务
  1548. $dialogue = getProp($segment, 'dialogue');
  1549. if (!empty($dialogue)) {
  1550. $now = date('Y-m-d H:i:s');
  1551. $generate_json = [
  1552. 'text' => $dialogue,
  1553. 'role' => getProp($segment, 'voice_actor'),
  1554. 'voice_type' => getProp($segment, 'voice_type'),
  1555. 'voice_name' => getProp($segment, 'voice_name'),
  1556. 'emotion' => getProp($segment, 'emotion'),
  1557. 'emotion_type' => getProp($segment, 'emotion_type'),
  1558. 'gender' => getProp($segment, 'gender'),
  1559. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1560. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1561. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1562. 'pitch' => getProp($segment, 'pitch', 0),
  1563. ];
  1564. // 插入视频配音合成任务
  1565. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1566. 'alias_segment_id' => $segment_id,
  1567. 'generate_status' => '执行中',
  1568. 'audio_url' => '',
  1569. 'generate_json' => json_encode($generate_json, 256),
  1570. 'created_at' => $now,
  1571. 'updated_at' => $now,
  1572. ]);
  1573. if (!$dubTaskId) {
  1574. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1575. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1576. // Utils::throwError('20003:创建配音任务失败!');
  1577. }
  1578. } else {
  1579. // dialogue为空时,直接写入默认音频信息到分镜表
  1580. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1581. $update_data['audio_duration'] = 2.0;
  1582. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1583. }
  1584. // 更新分镜的任务信息
  1585. $update_result = DB::table('mp_episode_segments')
  1586. ->where('segment_id', $segment_id)
  1587. ->update($update_data);
  1588. // 如果是第一集的首帧图片,则存入待更新数组
  1589. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1590. Redis::sadd('anime_first_frame_urls', $segment_id);
  1591. }
  1592. if ($update_result) {
  1593. $updated_segments[] = [
  1594. 'segment_id' => $segment_id,
  1595. 'task_id' => $task_id,
  1596. 'status' => '生成中',
  1597. 'matched_scenes' => $matched_scene,
  1598. 'matched_roles' => $segment_characters,
  1599. 'ref_urls_count' => count($ref_img_urls)
  1600. ];
  1601. } else {
  1602. $failed_segments[] = [
  1603. 'segment_id' => $segment_id,
  1604. 'error' => '更新分镜任务状态失败'
  1605. ];
  1606. }
  1607. if ($dubTaskId) {
  1608. sleep(1);
  1609. // 请求远程服务器执行生成
  1610. $client = new Client(['timeout' => 300, 'verify' => false]);
  1611. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1612. $response = $result->getBody()->getContents();
  1613. $response_arr = json_decode($response, true);
  1614. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1615. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1616. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1617. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1618. }
  1619. }
  1620. } catch (\Exception $e) {
  1621. $failed_segments[] = [
  1622. 'segment_id' => $segment_id,
  1623. 'error' => $e->getMessage()
  1624. ];
  1625. }
  1626. }
  1627. // 更新剧集生成状态
  1628. if (!empty($updated_segments)) {
  1629. DB::table('mp_anime_episodes')
  1630. ->where('id', $episode_id)
  1631. ->update([
  1632. 'is_generated' => 1,
  1633. 'updated_at' => date('Y-m-d H:i:s')
  1634. ]);
  1635. }
  1636. return [
  1637. 'success_count' => count($updated_segments),
  1638. 'failed_count' => count($failed_segments),
  1639. 'success_segments' => $updated_segments,
  1640. 'failed_segments' => $failed_segments,
  1641. 'total_segments' => count($segments)
  1642. ];
  1643. }
  1644. public function reGenerateSegment($data) {
  1645. $segment_id = getProp($data, 'segment_id');
  1646. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1647. $anime_id = getProp($segment, 'anime_id');
  1648. $episode_id = getProp($segment, 'episode_id');
  1649. $episode_number = getProp($segment, 'episode_number');
  1650. $segment_content = getProp($data, 'segment_content');
  1651. $ratio = getProp($data, 'ratio');
  1652. if (!$ratio) {
  1653. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1654. if (!$ratio) $ratio = '9:16';
  1655. }
  1656. $dimensions = $this->getRatioDimensions($ratio);
  1657. $width = $dimensions['width'];
  1658. $height = $dimensions['height'];
  1659. if (!$anime_id || !$episode_id) {
  1660. Utils::throwError('1002:请选择分镜');
  1661. }
  1662. // 使用文生文模型重新解析segment_content
  1663. if (!empty($segment_content)) {
  1664. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1665. }
  1666. // 获取动漫的角色信息(包含参考图)
  1667. $anime = DB::table('mp_animes')
  1668. ->where('id', $anime_id)
  1669. ->select('roles', 'scenes')
  1670. ->first();
  1671. if (!$anime || !$anime->roles) {
  1672. Utils::throwError('20003:未找到角色信息');
  1673. }
  1674. $roles = json_decode($anime->roles, true);
  1675. if (!$roles) {
  1676. Utils::throwError('20003:角色信息格式错误');
  1677. }
  1678. // 构建角色名称到参考图的映射
  1679. $role_map = [];
  1680. foreach ($roles as $role) {
  1681. $role_name = getProp($role, 'role');
  1682. $role_url = getProp($role, 'url');
  1683. if (!empty($role_name) && !empty($role_url)) {
  1684. $role_map[$role_name] = $role_url;
  1685. }
  1686. }
  1687. $scenes = json_decode($anime->scenes, true);
  1688. if (!$scenes) {
  1689. Utils::throwError('20003:角色信息格式错误');
  1690. }
  1691. // 构建角色名称到参考图的映射
  1692. $scene_map = [];
  1693. foreach ($scenes as $scene) {
  1694. $scene_name = getProp($scene, 'scene');
  1695. $scene_url = getProp($scene, 'url');
  1696. if (!empty($scene_name) && !empty($scene_url)) {
  1697. $scene_map[$scene_name] = $scene_url;
  1698. }
  1699. }
  1700. $segment_id = $segment->segment_id;
  1701. $original_segment_content = $segment->segment_content;
  1702. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1703. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1704. if (empty($final_segment_content)) {
  1705. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1706. }
  1707. try {
  1708. $dubTaskId = 0;
  1709. // 分镜剧本数组
  1710. $update_data = [
  1711. 'segment_content' => $final_segment_content,
  1712. 'pic_task_status' => '生成中',
  1713. 'updated_at' => date('Y-m-d H:i:s')
  1714. ];
  1715. // 解析分镜内容,提取画面描述作为主要提示词
  1716. $prompt = $final_segment_content;
  1717. $ref_img_urls = [];
  1718. // 分镜场景
  1719. $scene = getProp($data, 'scene');
  1720. if ($scene) {
  1721. $matched_scene = '';
  1722. if (isset($scene_map[$scene])) {
  1723. $img_index = count($ref_img_urls) + 1;
  1724. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1725. $ref_img_urls[] = $scene_map[$scene];
  1726. $matched_scene = $scene;
  1727. }
  1728. $update_data['scene'] = $scene;
  1729. }
  1730. // 分镜角色
  1731. $characters = getProp($data, 'characters');
  1732. if ($characters) {
  1733. $update_data['characters'] = $characters;
  1734. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1735. $characters = explode(',', $characters);
  1736. // 从分镜内容中提取涉及的角色
  1737. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1738. // 获取匹配角色的参考图
  1739. foreach ($segment_characters as $character) {
  1740. if (isset($role_map[$character])) {
  1741. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1742. $img_index = count($ref_img_urls) + 1;
  1743. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1744. $ref_img_urls[] = $role_map[$character];
  1745. }
  1746. }
  1747. }
  1748. // 如果没有找到匹配的角色参考图,不使用参考图
  1749. if (empty($ref_img_urls)) {
  1750. $ref_img_urls = [];
  1751. }
  1752. // 准备生成任务参数
  1753. $params = [
  1754. 'alias_segment_id' => $segment_id,
  1755. 'prompt' => $prompt,
  1756. 'ref_img_urls' => $ref_img_urls,
  1757. 'width' => $width,
  1758. 'height' => $height,
  1759. ];
  1760. // 优化提示词(不要生成字幕)
  1761. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1762. // 调用AI图片生成服务
  1763. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1764. $task_id = $task->id;
  1765. if (!$task_id) {
  1766. Utils::throwError('20003:创建生成任务失败!');
  1767. }
  1768. $update_data['pic_task_id'] = $task_id;
  1769. // 更新分镜剧本信息
  1770. $this->handleSegmentContent($update_data);
  1771. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1772. if ($segment_content) {
  1773. $dialogue = getProp($update_data, 'dialogue');
  1774. if (!empty($dialogue)) {
  1775. $now = date('Y-m-d H:i:s');
  1776. $generate_json = [
  1777. 'text' => $dialogue,
  1778. 'role' => getProp($update_data, 'voice_actor'),
  1779. 'voice_type' => getProp($update_data, 'voice_type'),
  1780. 'voice_name' => getProp($update_data, 'voice_name'),
  1781. 'emotion' => getProp($update_data, 'emotion'),
  1782. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1783. 'gender' => getProp($update_data, 'gender'),
  1784. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1785. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1786. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1787. 'pitch' => getProp($update_data, 'pitch', 0),
  1788. ];
  1789. // 插入视频配音合成任务
  1790. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1791. 'alias_segment_id' => $segment_id,
  1792. 'generate_status' => '执行中',
  1793. 'audio_url' => '',
  1794. 'generate_json' => json_encode($generate_json, 256),
  1795. 'created_at' => date('Y-m-d H:i:s'),
  1796. 'updated_at' => date('Y-m-d H:i:s'),
  1797. ]);
  1798. if (!$dubTaskId) {
  1799. Utils::throwError('20003:创建配音任务失败!');
  1800. }
  1801. $update_data['audio_url'] = '';
  1802. } else {
  1803. // dialogue为空时,直接写入默认音频信息
  1804. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1805. $update_data['audio_duration'] = 2.0;
  1806. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1807. }
  1808. }
  1809. $boolen = DB::table('mp_episode_segments')
  1810. ->where('segment_id', $segment_id)
  1811. ->update($update_data);
  1812. // 如果是第一集的首帧图片,则存入待更新数组
  1813. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1814. Redis::sadd('anime_first_frame_urls', $segment_id);
  1815. }
  1816. if ($dubTaskId) {
  1817. // 请求远程服务器执行生成
  1818. $client = new Client(['timeout' => 300, 'verify' => false]);
  1819. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1820. $response = $result->getBody()->getContents();
  1821. $response_arr = json_decode($response, true);
  1822. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1823. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1824. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  1825. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  1826. Utils::throwError('20003:火山生成音频失败');
  1827. }
  1828. }
  1829. } catch (\Exception $e) {
  1830. $failed_segments[] = [
  1831. 'segment_id' => $segment_id,
  1832. 'error' => $e->getMessage()
  1833. ];
  1834. }
  1835. // 创建任务之后先暂停10s等待异步任务完成
  1836. sleep(10);
  1837. $img_url = $this->loopGetPicTaskResult($task_id);
  1838. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  1839. // 图片生成后新增对话记录
  1840. try {
  1841. $uid = Site::getUid();
  1842. $now = date('Y-m-d H:i:s');
  1843. // 使用AI反推图片提示词
  1844. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  1845. // 保存对话记录
  1846. $records = [
  1847. [
  1848. 'uid' => $uid,
  1849. 'anime_id' => $anime_id,
  1850. 'sequence' => $episode_number,
  1851. 'role' => 'user',
  1852. 'content' => '重新生成',
  1853. 'segment_id' => $segment_id,
  1854. 'image_url' => '',
  1855. 'created_at' => $now,
  1856. 'updated_at' => $now
  1857. ],
  1858. [
  1859. 'uid' => $uid,
  1860. 'anime_id' => $anime_id,
  1861. 'sequence' => $episode_number,
  1862. 'role' => 'assistant',
  1863. 'content' => $pic_prompt,
  1864. 'segment_id' => $segment_id,
  1865. 'image_url' => $img_url,
  1866. 'created_at' => $now,
  1867. 'updated_at' => $now
  1868. ]
  1869. ];
  1870. DB::table('mp_anime_records')->insert($records);
  1871. } catch (\Exception $e) {
  1872. // 记录日志但不影响主流程
  1873. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  1874. 'segment_id' => $segment_id,
  1875. 'img_url' => $img_url
  1876. ]);
  1877. }
  1878. return $img_url;
  1879. }
  1880. public function addSegment($data) {
  1881. $prev_segment_id = getProp($data, 'prev_segment_id');
  1882. $img_url = getProp($data, 'img_url');
  1883. $video_url = getProp($data, 'video_url');
  1884. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  1885. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1886. $anime_id = getProp($segment, 'anime_id');
  1887. $episode_id = getProp($segment, 'episode_id');
  1888. $episode_number = getProp($segment, 'episode_number');
  1889. $segment_number = getProp($segment, 'segment_number');
  1890. $new_segment_number = $segment_number + 1;
  1891. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  1892. // 分镜剧本数组
  1893. $insert_data = [
  1894. 'anime_id' => $anime_id,
  1895. 'episode_id' => $episode_id,
  1896. 'episode_number' => $episode_number,
  1897. 'act_number' => getProp($segment, 'act_number'),
  1898. 'act_title' => getProp($segment, 'act_title'),
  1899. 'segment_id' => $segment_id,
  1900. 'segment_number' => $new_segment_number,
  1901. 'segment_content' => '',
  1902. 'img_url' => '',
  1903. 'video_url' => '',
  1904. 'created_at' => date('Y-m-d H:i:s'),
  1905. 'updated_at' => date('Y-m-d H:i:s')
  1906. ];
  1907. if ($img_url) $insert_data['img_url'] = $img_url;
  1908. if ($video_url) {
  1909. $insert_data['origin_video_url'] = $video_url;
  1910. $insert_data['current_type'] = 2;
  1911. $compressed_video_url = compressVideo($video_url);
  1912. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  1913. }
  1914. try {
  1915. DB::beginTransaction();
  1916. // 先更新序号
  1917. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  1918. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  1919. if (!$id) {
  1920. Utils::throwError('20003:新增分镜失败!');
  1921. }
  1922. }catch (\Exception $e) {
  1923. DB::rollBack();
  1924. Utils::throwError('20003:'.$e->getMessage());
  1925. }
  1926. DB::commit();
  1927. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  1928. $segment = $segment ? (array)$segment : [];
  1929. return $segment;
  1930. // 以下代码暂弃用
  1931. $anime_id = getProp($segment, 'anime_id');
  1932. $episode_id = getProp($segment, 'episode_id');
  1933. $episode_number = getProp($segment, 'episode_number');
  1934. $segment_number = getProp($segment, 'segment_number');
  1935. $segment_content = getProp($data, 'segment_content');
  1936. $img_url = getProp($data, 'img_url');
  1937. $video_url = getProp($data, 'video_url');
  1938. $ratio = getProp($data, 'ratio');
  1939. $dimensions = $this->getRatioDimensions($ratio);
  1940. $width = $dimensions['width'];
  1941. $height = $dimensions['height'];
  1942. if (!$anime_id || !$episode_id) {
  1943. Utils::throwError('1002:请选择分镜');
  1944. }
  1945. // 使用文生文模型重新解析segment_content
  1946. if (!empty($segment_content)) {
  1947. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1948. }
  1949. // 获取动漫的角色信息(包含参考图)
  1950. $anime = DB::table('mp_animes')
  1951. ->where('id', $anime_id)
  1952. ->select('roles', 'scenes')
  1953. ->first();
  1954. if (!$anime || !$anime->roles) {
  1955. Utils::throwError('20003:未找到角色信息');
  1956. }
  1957. $roles = json_decode($anime->roles, true);
  1958. if (!$roles) {
  1959. Utils::throwError('20003:角色信息格式错误');
  1960. }
  1961. // 构建角色名称到参考图的映射
  1962. $role_map = [];
  1963. foreach ($roles as $role) {
  1964. $role_name = getProp($role, 'role');
  1965. $role_url = getProp($role, 'url');
  1966. if (!empty($role_name) && !empty($role_url)) {
  1967. $role_map[$role_name] = $role_url;
  1968. }
  1969. }
  1970. $scenes = json_decode($anime->scenes, true);
  1971. if (!$scenes) {
  1972. Utils::throwError('20003:角色信息格式错误');
  1973. }
  1974. // 构建角色名称到参考图的映射
  1975. $scene_map = [];
  1976. foreach ($scenes as $scene) {
  1977. $scene_name = getProp($scene, 'scene');
  1978. $scene_url = getProp($scene, 'url');
  1979. if (!empty($scene_name) && !empty($scene_url)) {
  1980. $scene_map[$scene_name] = $scene_url;
  1981. }
  1982. }
  1983. $segment_id = $segment->segment_id;
  1984. $original_segment_content = $segment->segment_content;
  1985. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1986. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1987. if (empty($final_segment_content)) {
  1988. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1989. }
  1990. try {
  1991. $dubTaskId = 0;
  1992. DB::beginTransaction();
  1993. $new_segment_number = $segment_number + 1;
  1994. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  1995. // 分镜剧本数组
  1996. $insert_data = [
  1997. 'anime_id' => $anime_id,
  1998. 'episode_id' => $episode_id,
  1999. 'episode_number' => $episode_number,
  2000. 'act_number' => getProp($segment, 'act_number'),
  2001. 'act_title' => getProp($segment, 'act_title'),
  2002. 'segment_id' => $segment_id,
  2003. 'segment_number' => $new_segment_number,
  2004. 'segment_content' => $final_segment_content,
  2005. 'img_url' => $img_url,
  2006. 'video_url' => $video_url,
  2007. 'created_at' => date('Y-m-d H:i:s'),
  2008. 'updated_at' => date('Y-m-d H:i:s')
  2009. ];
  2010. // 更新分镜剧本信息
  2011. $this->handleSegmentContent($insert_data);
  2012. // 如果有对话内容,创建视频配音合成任务
  2013. $dialogue = getProp($insert_data, 'dialogue');
  2014. if (!empty($dialogue)) {
  2015. $now = date('Y-m-d H:i:s');
  2016. $generate_json = [
  2017. 'text' => $dialogue,
  2018. 'role' => getProp($insert_data, 'voice_actor'),
  2019. 'voice_type' => getProp($insert_data, 'voice_type'),
  2020. 'voice_name' => getProp($insert_data, 'voice_name'),
  2021. 'emotion' => getProp($insert_data, 'emotion'),
  2022. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2023. 'gender' => getProp($insert_data, 'gender'),
  2024. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2025. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2026. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2027. 'pitch' => getProp($insert_data, 'pitch', 0),
  2028. ];
  2029. // 插入视频配音合成任务
  2030. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2031. 'alias_segment_id' => $segment_id,
  2032. 'generate_status' => '执行中',
  2033. 'audio_url' => '',
  2034. 'generate_json' => json_encode($generate_json, 256),
  2035. 'created_at' => $now,
  2036. 'updated_at' => $now,
  2037. ]);
  2038. if (!$dubTaskId) {
  2039. Utils::throwError('20003:创建配音任务失败!');
  2040. }
  2041. $insert_data['audio_url'] = '';
  2042. } else {
  2043. // dialogue为空时,直接写入默认音频信息
  2044. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2045. $insert_data['audio_duration'] = 2.0;
  2046. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2047. }
  2048. // 如果没有上传图片则使用当前描述进行生成
  2049. if (!$img_url) {
  2050. // 解析分镜内容,提取画面描述作为主要提示词
  2051. $prompt = $final_segment_content;
  2052. $ref_img_urls = [];
  2053. // 分镜场景
  2054. $scene = getProp($insert_data, 'scene');
  2055. if ($scene) {
  2056. $matched_scene = '';
  2057. if (isset($scene_map[$scene])) {
  2058. $img_index = count($ref_img_urls) + 1;
  2059. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2060. $ref_img_urls[] = $scene_map[$scene];
  2061. $matched_scene = $scene;
  2062. }
  2063. $update_data['scene'] = $scene;
  2064. }
  2065. // 分镜角色
  2066. $characters = getProp($insert_data, 'characters');
  2067. if ($characters) {
  2068. $update_data['characters'] = $characters;
  2069. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2070. $characters = explode(',', $characters);
  2071. // 从分镜内容中提取涉及的角色
  2072. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2073. // 获取匹配角色的参考图
  2074. foreach ($segment_characters as $character) {
  2075. if (isset($role_map[$character])) {
  2076. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2077. $img_index = count($ref_img_urls) + 1;
  2078. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2079. $ref_img_urls[] = $role_map[$character];
  2080. }
  2081. }
  2082. }
  2083. // 如果没有找到匹配的角色参考图,不使用参考图
  2084. if (empty($ref_img_urls)) {
  2085. $ref_img_urls = [];
  2086. }
  2087. // 准备生成任务参数
  2088. $params = [
  2089. 'alias_segment_id' => $segment_id,
  2090. 'prompt' => $prompt,
  2091. 'ref_img_urls' => $ref_img_urls,
  2092. 'width' => $width,
  2093. 'height' => $height,
  2094. ];
  2095. // 调用AI图片生成服务
  2096. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2097. $task_id = $task->id;
  2098. // $task_id = 'whatever';
  2099. if (!$task_id) {
  2100. Utils::throwError('20003:创建生成任务失败!');
  2101. }
  2102. $insert_data['pic_task_status'] = '生成中';
  2103. $insert_data['pic_task_id'] = $task_id;
  2104. }
  2105. // 先更新序号
  2106. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2107. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2108. if (!$boolen) {
  2109. Utils::throwError('20003:新增分镜失败!');
  2110. }
  2111. // 如果是第一集的首帧图片,则存入待更新数组
  2112. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2113. Redis::sadd('anime_first_frame_urls', $segment_id);
  2114. }
  2115. if ($dubTaskId) {
  2116. // 请求远程服务器执行生成
  2117. $client = new Client(['timeout' => 300, 'verify' => false]);
  2118. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2119. $response = $result->getBody()->getContents();
  2120. $response_arr = json_decode($response, true);
  2121. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2122. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2123. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2124. Utils::throwError('20003:火山生成音频失败');
  2125. }
  2126. }
  2127. } catch (\Exception $e) {
  2128. DB::rollBack();
  2129. Utils::throwError('20003:'.$e->getMessage());
  2130. }
  2131. DB::commit();
  2132. // 创建任务之后先暂停10s等待异步任务完成
  2133. sleep(10);
  2134. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2135. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2136. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2137. $segment = $segment ? (array)$segment : [];
  2138. return $segment;
  2139. }
  2140. public function copySegment($data) {
  2141. $segment_id = getProp($data, 'segment_id');
  2142. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2143. if (!$segment) Utils::throwError('20003:请选择分镜');
  2144. $anime_id = getProp($segment, 'anime_id');
  2145. $episode_id = getProp($segment, 'episode_id');
  2146. $episode_number = getProp($segment, 'episode_number');
  2147. $segment_number = getProp($segment, 'segment_number');
  2148. $new_segment_id = 0;
  2149. try {
  2150. DB::beginTransaction();
  2151. $segment = (array)$segment;
  2152. unset($segment['id']);
  2153. $segment['segment_number'] += 1;
  2154. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2155. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2156. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2157. // 更新其他分镜序号
  2158. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2159. // 复制分镜
  2160. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2161. if (!$id) {
  2162. Utils::throwError('20003:复制分镜失败');
  2163. }
  2164. }catch (\Exception $e) {
  2165. DB::rollBack();
  2166. Utils::throwError('20003:'.$e->getMessage());
  2167. }
  2168. DB::commit();
  2169. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2170. $segment = $segment ? (array)$segment : [];
  2171. return $segment;
  2172. }
  2173. public function moveSegment($data) {
  2174. $segment_id = getProp($data, 'segment_id');
  2175. $target_segment_id = getProp($data, 'target_segment_id');
  2176. // 获取源分镜信息
  2177. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2178. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2179. // 获取目标分镜信息
  2180. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2181. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2182. $anime_id = getProp($source_segment, 'anime_id');
  2183. $episode_id = getProp($source_segment, 'episode_id');
  2184. $episode_number = getProp($source_segment, 'episode_number');
  2185. $source_segment_number = getProp($source_segment, 'segment_number');
  2186. $target_segment_number = getProp($target_segment, 'segment_number');
  2187. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2188. $target_anime_id = getProp($target_segment, 'anime_id');
  2189. $target_episode_number = getProp($target_segment, 'episode_number');
  2190. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2191. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2192. }
  2193. // 如果源分镜和目标分镜相同,无需移动
  2194. if ($source_segment_number == $target_segment_number) {
  2195. return true;
  2196. }
  2197. try {
  2198. DB::beginTransaction();
  2199. if ($source_segment_number < $target_segment_number) {
  2200. // 向后移动:源分镜移动到目标分镜之后
  2201. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2202. DB::table('mp_episode_segments')
  2203. ->where('anime_id', $anime_id)
  2204. ->where('episode_id', $episode_id)
  2205. ->where('segment_number', '>', $source_segment_number)
  2206. ->where('segment_number', '<=', $target_segment_number)
  2207. ->decrement('segment_number');
  2208. // 2. 将源分镜移动到目标分镜之后
  2209. $new_segment_number = $target_segment_number;
  2210. } else {
  2211. // 向前移动:源分镜移动到目标分镜之后
  2212. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2213. DB::table('mp_episode_segments')
  2214. ->where('anime_id', $anime_id)
  2215. ->where('episode_id', $episode_id)
  2216. ->where('segment_number', '>', $target_segment_number)
  2217. ->where('segment_number', '<', $source_segment_number)
  2218. ->increment('segment_number');
  2219. // 2. 将源分镜移动到目标分镜之后
  2220. $new_segment_number = $target_segment_number + 1;
  2221. }
  2222. // 3. 更新源分镜的序号
  2223. $update_result = DB::table('mp_episode_segments')
  2224. ->where('segment_id', $segment_id)
  2225. ->update([
  2226. 'segment_number' => $new_segment_number,
  2227. 'updated_at' => date('Y-m-d H:i:s')
  2228. ]);
  2229. if (!$update_result) {
  2230. Utils::throwError('20003:更新分镜序号失败');
  2231. }
  2232. DB::commit();
  2233. return true;
  2234. } catch (\Exception $e) {
  2235. DB::rollBack();
  2236. Utils::throwError('20003:' . $e->getMessage());
  2237. }
  2238. }
  2239. public function delSegment($data) {
  2240. $segment_id = getProp($data, 'segment_id');
  2241. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2242. if (!$segment) Utils::throwError('20003:请选择分镜');
  2243. $anime_id = getProp($segment, 'anime_id');
  2244. $episode_id = getProp($segment, 'episode_id');
  2245. $episode_number = getProp($segment, 'episode_number');
  2246. $segment_number = getProp($segment, 'segment_number');
  2247. try {
  2248. DB::beginTransaction();
  2249. // 删除分镜
  2250. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2251. if (!$boolen) {
  2252. Utils::throwError('20003:删除分镜失败');
  2253. }
  2254. // 更新其他分镜序号
  2255. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2256. }catch (\Exception $e) {
  2257. DB::rollBack();
  2258. Utils::throwError('20003:'.$e->getMessage());
  2259. }
  2260. DB::commit();
  2261. return true;
  2262. }
  2263. public function applySegment($data) {
  2264. $segment_id = getProp($data, 'segment_id');
  2265. $url = getProp($data, 'url');
  2266. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2267. if (!$url) Utils::throwError('20003:URL不能为空');
  2268. // 获取URL的文件扩展名
  2269. $urlPath = parse_url($url, PHP_URL_PATH);
  2270. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2271. // 定义图片和视频的扩展名
  2272. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2273. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2274. // 判断是图片还是视频
  2275. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2276. if (in_array($extension, $imageExtensions)) {
  2277. // 图片类型
  2278. $updateData['img_url'] = $url;
  2279. $updateData['current_type'] = 1;
  2280. } elseif (in_array($extension, $videoExtensions)) {
  2281. // 视频类型
  2282. $updateData['video_url'] = $url;
  2283. $updateData['current_type'] = 2;
  2284. } else {
  2285. Utils::throwError('20003:不支持的文件类型');
  2286. }
  2287. // 更新分镜表
  2288. $result = DB::table('mp_episode_segments')
  2289. ->where('segment_id', $segment_id)
  2290. ->update($updateData);
  2291. if (!$result) {
  2292. Utils::throwError('20003:更新分镜失败');
  2293. }
  2294. return true;
  2295. }
  2296. public function segmentHistory($data) {
  2297. $segment_id = getProp($data, 'segment_id');
  2298. // 获取历史图片
  2299. $pics = [];
  2300. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2301. foreach($pic_history as $task) {
  2302. $result_url = getProp($task, 'result_url');
  2303. if (is_json($result_url)) {
  2304. $pics = array_merge($pics, json_decode($result_url, true));
  2305. }else {
  2306. $pics[] = $result_url;
  2307. }
  2308. }
  2309. // 获取历史视频
  2310. $videos = [];
  2311. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2312. foreach($video_history as $task) {
  2313. $result_url = getProp($task, 'result_url');
  2314. if (is_json($result_url)) {
  2315. $videos = array_merge($videos, json_decode($result_url, true));
  2316. }else {
  2317. $videos[] = $result_url;
  2318. }
  2319. }
  2320. return compact('pics', 'videos');
  2321. }
  2322. public function addAct($data) {
  2323. $prev_act_id = getProp($data, 'prev_act_id');
  2324. $act_title = getProp($data, 'act_title', '');
  2325. $act_content = getProp($data, 'act_content', '');
  2326. $act_duration = getProp($data, 'act_duration', 5);
  2327. $video_url = getProp($data, 'video_url');
  2328. // 根据prev_act_id获取记录
  2329. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2330. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2331. $anime_id = getProp($prev_segment, 'anime_id');
  2332. $episode_id = getProp($prev_segment, 'episode_id');
  2333. $episode_number = getProp($prev_segment, 'episode_number');
  2334. $prev_act_number = getProp($prev_segment, 'act_number');
  2335. // 获取新的act_number
  2336. $new_act_number = $prev_act_number + 1;
  2337. try {
  2338. DB::beginTransaction();
  2339. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2340. DB::table('mp_episode_segments')
  2341. ->where('anime_id', $anime_id)
  2342. ->where('episode_id', $episode_id)
  2343. ->where('act_number', '>', $prev_act_number)
  2344. ->increment('act_number');
  2345. // 插入新片段记录
  2346. $insert_data = [
  2347. 'anime_id' => $anime_id,
  2348. 'episode_id' => $episode_id,
  2349. 'episode_number' => $episode_number,
  2350. 'act_number' => $new_act_number,
  2351. 'created_at' => date('Y-m-d H:i:s'),
  2352. 'updated_at' => date('Y-m-d H:i:s')
  2353. ];
  2354. if ($act_title) {
  2355. $insert_data['act_title'] = $act_title;
  2356. }
  2357. if ($act_content) {
  2358. $insert_data['act_content'] = $act_content;
  2359. }
  2360. if ($act_duration) {
  2361. $insert_data['act_duration'] = $act_duration;
  2362. }
  2363. if ($video_url) {
  2364. $insert_data['origin_video_url'] = $video_url;
  2365. $insert_data['current_type'] = 2;
  2366. $compressed_video_url = compressVideo($video_url);
  2367. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2368. }
  2369. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2370. if (!$id) {
  2371. Utils::throwError('20003:新增片段失败!');
  2372. }
  2373. DB::commit();
  2374. }catch (\Exception $e) {
  2375. DB::rollBack();
  2376. Utils::throwError('20003:'.$e->getMessage());
  2377. }
  2378. $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();
  2379. $segment = $segment ? (array)$segment : [];
  2380. return $segment;
  2381. }
  2382. public function editAct($data) {
  2383. $act_id = getProp($data, 'act_id');
  2384. $act_content = getProp($data, 'act_content');
  2385. $act_duration = getProp($data, 'act_duration');
  2386. $act_title = getProp($data, 'act_title');
  2387. $image_url = getProp($data, 'image_url');
  2388. $video_url = getProp($data, 'video_url');
  2389. // 参数验证
  2390. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2391. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2392. $segment = DB::table('mp_episode_segments')
  2393. ->where('id', $act_id)
  2394. ->first();
  2395. if (!$segment) Utils::throwError('20003:该片段不存在');
  2396. try {
  2397. DB::beginTransaction();
  2398. // 准备更新数据
  2399. $update_data = [
  2400. 'updated_at' => date('Y-m-d H:i:s')
  2401. ];
  2402. // 更新act相关字段
  2403. if (!empty($act_content)) {
  2404. $update_data['act_content'] = $act_content;
  2405. }
  2406. if (!empty($act_duration)) {
  2407. $update_data['act_duration'] = $act_duration;
  2408. }
  2409. if (!empty($act_title)) {
  2410. $update_data['act_title'] = $act_title;
  2411. }
  2412. // 处理图片上传
  2413. if ($image_url) {
  2414. $update_data['img_url'] = $image_url;
  2415. $update_data['current_type'] = 1;
  2416. // 同时写入一个图片生成任务记录
  2417. if ($act_id) {
  2418. $pic_task = [
  2419. 'alias_act_id' => $act_id,
  2420. 'ref_img_url' => json_encode([]),
  2421. 'status' => 'success',
  2422. 'result_url' => json_encode([$image_url], 256),
  2423. 'model' => '',
  2424. 'created_at' => date('Y-m-d H:i:s'),
  2425. 'updated_at' => date('Y-m-d H:i:s'),
  2426. ];
  2427. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2428. }
  2429. }
  2430. // 处理视频上传
  2431. if ($video_url) {
  2432. $update_data['origin_video_url'] = $video_url;
  2433. $compressed_video_url = compressVideo($video_url);
  2434. $update_data['current_type'] = 2;
  2435. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2436. // 同时写入一个视频生成任务记录
  2437. if ($act_id) {
  2438. $video_task = [
  2439. 'alias_act_id' => $act_id,
  2440. 'status' => 'success',
  2441. 'result_url' => $update_data['origin_video_url'],
  2442. 'compressed_url' => $update_data['video_url'],
  2443. 'created_at' => date('Y-m-d H:i:s'),
  2444. 'updated_at' => date('Y-m-d H:i:s'),
  2445. ];
  2446. DB::table('mp_generate_video_tasks')->insert($video_task);
  2447. }
  2448. }
  2449. // 更新片段信息
  2450. $result = DB::table('mp_episode_segments')
  2451. ->where('id', $act_id)
  2452. ->update($update_data);
  2453. if ($result === false) {
  2454. Utils::throwError('20003:更新片段失败');
  2455. }
  2456. DB::commit();
  2457. return true;
  2458. } catch (\Exception $e) {
  2459. DB::rollBack();
  2460. dLog('anime')->error('更新片段失败', [
  2461. 'act_id' => $act_id,
  2462. 'error' => $e->getMessage()
  2463. ]);
  2464. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2465. }
  2466. }
  2467. public function copyAct($data) {
  2468. $act_id = getProp($data, 'act_id');
  2469. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2470. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2471. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2472. $video_url = getProp($source_segment, 'video_url');
  2473. if (!$video_url) Utils::throwError('20003:该片段没有视频无法复制');
  2474. $anime_id = getProp($source_segment, 'anime_id');
  2475. $episode_id = getProp($source_segment, 'episode_id');
  2476. $episode_number = getProp($source_segment, 'episode_number');
  2477. $act_number = getProp($source_segment, 'act_number');
  2478. try {
  2479. DB::beginTransaction();
  2480. // 新act的编号
  2481. $new_act_number = $act_number + 1;
  2482. // 更新后续所有act的act_number
  2483. DB::table('mp_episode_segments')
  2484. ->where('anime_id', $anime_id)
  2485. ->where('episode_id', $episode_id)
  2486. ->where('act_number', '>', $act_number)
  2487. ->increment('act_number');
  2488. // 复制该片段记录
  2489. $segment_data = (array)$source_segment;
  2490. unset($segment_data['id']);
  2491. $segment_data['act_number'] = $new_act_number;
  2492. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2493. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2494. if (!$id) {
  2495. Utils::throwError('20003:复制片段失败');
  2496. }
  2497. DB::commit();
  2498. }catch (\Exception $e) {
  2499. DB::rollBack();
  2500. Utils::throwError('20003:'.$e->getMessage());
  2501. }
  2502. // 返回新复制的记录
  2503. $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();
  2504. $new_segment = $new_segment ? (array)$new_segment : [];
  2505. $new_segment['act_id'] = $id;
  2506. return $new_segment;
  2507. }
  2508. public function moveAct($data) {
  2509. $act_id = getProp($data, 'act_id');
  2510. $target_act_id = getProp($data, 'target_act_id');
  2511. // 获取源片段信息
  2512. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2513. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2514. // 获取目标片段信息
  2515. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2516. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2517. $anime_id = getProp($source_segment, 'anime_id');
  2518. $episode_id = getProp($source_segment, 'episode_id');
  2519. $source_act_number = getProp($source_segment, 'act_number');
  2520. $target_act_number = getProp($target_segment, 'act_number');
  2521. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2522. $target_anime_id = getProp($target_segment, 'anime_id');
  2523. $target_episode_id = getProp($target_segment, 'episode_id');
  2524. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2525. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2526. }
  2527. // 如果源片段和目标片段相同,无需移动
  2528. if ($source_act_number == $target_act_number) {
  2529. return true;
  2530. }
  2531. try {
  2532. DB::beginTransaction();
  2533. if ($source_act_number < $target_act_number) {
  2534. // 向后移动:源片段移动到目标片段之后
  2535. // 1. 将源片段和目标片段之间的所有片段编号减1
  2536. DB::table('mp_episode_segments')
  2537. ->where('anime_id', $anime_id)
  2538. ->where('episode_id', $episode_id)
  2539. ->where('act_number', '>', $source_act_number)
  2540. ->where('act_number', '<=', $target_act_number)
  2541. ->decrement('act_number');
  2542. // 2. 将源片段移动到目标片段之后
  2543. $new_act_number = $target_act_number;
  2544. } else {
  2545. // 向前移动:源片段移动到目标片段之后
  2546. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2547. DB::table('mp_episode_segments')
  2548. ->where('anime_id', $anime_id)
  2549. ->where('episode_id', $episode_id)
  2550. ->where('act_number', '>', $target_act_number)
  2551. ->where('act_number', '<', $source_act_number)
  2552. ->increment('act_number');
  2553. // 2. 将源片段移动到目标片段之后
  2554. $new_act_number = $target_act_number + 1;
  2555. }
  2556. // 3. 更新源片段的编号
  2557. $update_result = DB::table('mp_episode_segments')
  2558. ->where('id', $act_id)
  2559. ->update([
  2560. 'act_number' => $new_act_number,
  2561. 'updated_at' => date('Y-m-d H:i:s')
  2562. ]);
  2563. if (!$update_result) {
  2564. Utils::throwError('20003:更新片段编号失败');
  2565. }
  2566. DB::commit();
  2567. return true;
  2568. } catch (\Exception $e) {
  2569. DB::rollBack();
  2570. Utils::throwError('20003:' . $e->getMessage());
  2571. }
  2572. }
  2573. public function delAct($data) {
  2574. $act_id = getProp($data, 'act_id');
  2575. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2576. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2577. if (!$segment) Utils::throwError('20003:请选择片段');
  2578. $anime_id = getProp($segment, 'anime_id');
  2579. $episode_id = getProp($segment, 'episode_id');
  2580. $act_number = getProp($segment, 'act_number');
  2581. try {
  2582. DB::beginTransaction();
  2583. // 删除该片段记录
  2584. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2585. if (!$deleted) {
  2586. Utils::throwError('20003:删除片段失败');
  2587. }
  2588. // 更新后续act的编号
  2589. DB::table('mp_episode_segments')
  2590. ->where('anime_id', $anime_id)
  2591. ->where('episode_id', $episode_id)
  2592. ->where('act_number', '>', $act_number)
  2593. ->decrement('act_number');
  2594. DB::commit();
  2595. }catch (\Exception $e) {
  2596. DB::rollBack();
  2597. Utils::throwError('20003:'.$e->getMessage());
  2598. }
  2599. return true;
  2600. }
  2601. public function applyAct($data) {
  2602. $act_id = getProp($data, 'act_id');
  2603. $url = getProp($data, 'url');
  2604. if (!$act_id) Utils::throwError('20003:请选择片段');
  2605. if (!$url) Utils::throwError('20003:URL不能为空');
  2606. // 获取URL的文件扩展名
  2607. $urlPath = parse_url($url, PHP_URL_PATH);
  2608. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2609. // 定义图片和视频的扩展名
  2610. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2611. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2612. // 判断是图片还是视频
  2613. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2614. if (in_array($extension, $imageExtensions)) {
  2615. // 图片类型
  2616. $updateData['img_url'] = $url;
  2617. $updateData['current_type'] = 1;
  2618. } elseif (in_array($extension, $videoExtensions)) {
  2619. // 视频类型
  2620. $updateData['video_url'] = $url;
  2621. $updateData['current_type'] = 2;
  2622. } else {
  2623. Utils::throwError('20003:不支持的文件类型');
  2624. }
  2625. // 更新片段记录(全能模式下每个act只有一条记录)
  2626. $result = DB::table('mp_episode_segments')
  2627. ->where('id', $act_id)
  2628. ->update($updateData);
  2629. if (!$result) {
  2630. Utils::throwError('20003:更新片段失败');
  2631. }
  2632. return true;
  2633. }
  2634. public function actChatHistory($data) {
  2635. $act_id = getProp($data, 'act_id');
  2636. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2637. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'reference_images', 'created_at');
  2638. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2639. $value = (array)$value;
  2640. $value['created_at'] = transDate($value['created_at']);
  2641. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2642. else $value['reference_images'] = [];
  2643. return $value;
  2644. })->toArray();
  2645. // 获取历史图片
  2646. $url = [];
  2647. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2648. foreach($pic_history as $task) {
  2649. $result_url = getProp($task, 'result_url');
  2650. if (is_json($result_url)) {
  2651. $url = array_merge($url, json_decode($result_url, true));
  2652. }else {
  2653. $url[] = $result_url;
  2654. }
  2655. }
  2656. // 获取历史视频
  2657. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2658. foreach($video_history as $task) {
  2659. $result_url = getProp($task, 'result_url');
  2660. if (is_json($result_url)) {
  2661. $url = array_merge($url, json_decode($result_url, true));
  2662. }else {
  2663. $url[] = $result_url;
  2664. }
  2665. }
  2666. // 获取资产库
  2667. $products = [];
  2668. // 通过act_id查询片段信息获取episode_id
  2669. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2670. if ($segment) {
  2671. $episode_id = getProp($segment, 'episode_id');
  2672. // 查询剧集信息获取roles、scenes和extra_products
  2673. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2674. if ($episode) {
  2675. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2676. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2677. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2678. // 先合并roles和scenes
  2679. // 处理角色数组
  2680. foreach ($roles as $role) {
  2681. $product = $role;
  2682. // 将role字段重命名为product_name
  2683. if (isset($product['role'])) {
  2684. $product['product_name'] = $product['role'];
  2685. unset($product['role']);
  2686. }
  2687. $product['product'] = 1; // 标记类型为角色
  2688. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2689. }
  2690. // 处理场景数组
  2691. foreach ($scenes as $scene) {
  2692. $product = $scene;
  2693. // 将scene字段重命名为product_name
  2694. if (isset($product['scene'])) {
  2695. $product['product_name'] = $product['scene'];
  2696. unset($product['scene']);
  2697. }
  2698. $product['product'] = 2; // 标记类型为场景
  2699. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2700. }
  2701. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2702. foreach ($extra_products as $extra_product) {
  2703. $product_name = getProp($extra_product, 'product_name');
  2704. if ($product_name) {
  2705. $products[$product_name] = $extra_product; // 覆盖同名数据
  2706. }
  2707. }
  2708. // 重新索引数组(去除key)
  2709. $products = array_values($products);
  2710. }
  2711. }
  2712. // 获取执行中的任务
  2713. $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) {
  2714. $value = (array)$value;
  2715. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2716. else $value['ref_image_url'] = [];
  2717. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2718. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2719. if (!empty($value['prompt'])) {
  2720. $prompt = $value['prompt'];
  2721. // 查找第一个【镜头】的位置
  2722. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2723. // 从【镜头】开始截取
  2724. $prompt = substr($prompt, $matches[0][1]);
  2725. }
  2726. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2727. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2728. $value['prompt'] = $prompt;
  2729. }
  2730. return $value;
  2731. })->toArray();
  2732. return compact('chat', 'url', 'products', 'tasks');
  2733. }
  2734. public function applyAudioData($data) {
  2735. $segment_id = getProp($data, 'segment_id');
  2736. $global_data = getProp($data, 'global_data');
  2737. $segment_data = getProp($data, 'segment_data');
  2738. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2739. $global_data = is_array($global_data) ? $global_data : [];
  2740. $segment_data = is_array($segment_data) ? $segment_data : [];
  2741. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2742. $dialogue_item = null;
  2743. foreach ($global_data as $key => $item) {
  2744. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2745. $dialogue_item = $item;
  2746. unset($global_data[$key]);
  2747. break;
  2748. }
  2749. }
  2750. if ($dialogue_item) {
  2751. $segment_data[] = $dialogue_item;
  2752. }
  2753. // 特殊参数: audio_url,audio_duration,subtitle_info
  2754. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2755. // 如果不是全部存在,则仍需创建音频任务
  2756. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2757. $special_update_data = [];
  2758. $has_all_special_params = false;
  2759. // 从segment_data中提取特殊参数
  2760. $filtered_segment_data = [];
  2761. foreach ($segment_data as $item) {
  2762. $field_name = trim((string)getProp($item, 'name'));
  2763. if (in_array($field_name, $special_fields)) {
  2764. $special_update_data[$field_name] = getProp($item, 'value');
  2765. } else {
  2766. // 非特殊参数保留,继续后续处理
  2767. $filtered_segment_data[] = $item;
  2768. }
  2769. }
  2770. // 检查是否三个特殊参数都存在
  2771. if (count($special_update_data) === 3 &&
  2772. isset($special_update_data['audio_url']) &&
  2773. isset($special_update_data['audio_duration']) &&
  2774. isset($special_update_data['subtitle_info'])) {
  2775. $has_all_special_params = true;
  2776. // 立即更新到当前分镜
  2777. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  2778. DB::table('mp_episode_segments')
  2779. ->where('segment_id', $segment_id)
  2780. ->update($special_update_data);
  2781. }
  2782. // 使用过滤后的segment_data继续处理其他参数
  2783. $segment_data = $filtered_segment_data;
  2784. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  2785. $global_update_data = [];
  2786. $segment_update_data = [];
  2787. $global_voice_type = '';
  2788. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2789. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  2790. $episode_id = getProp($target_segment, 'episode_id');
  2791. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  2792. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2793. if (!$episode) Utils::throwError('20003:分集不存在');
  2794. foreach ($global_data as $item) {
  2795. $field_name = trim((string)getProp($item, 'name'));
  2796. if (!$field_name || !in_array($field_name, $allow_fields)) {
  2797. continue;
  2798. }
  2799. $global_update_data[$field_name] = getProp($item, 'value');
  2800. if ($field_name === 'voice_type') {
  2801. $global_voice_type = trim((string)getProp($item, 'value'));
  2802. }
  2803. }
  2804. foreach ($segment_data as $item) {
  2805. $field_name = trim((string)getProp($item, 'name'));
  2806. if (!$field_name || !in_array($field_name, $allow_fields)) {
  2807. continue;
  2808. }
  2809. $segment_update_data[$field_name] = getProp($item, 'value');
  2810. }
  2811. if ($global_voice_type) {
  2812. $timbre_info = DB::table('mp_timbres')
  2813. ->where('timbre_type', $global_voice_type)
  2814. ->select('audio_url', 'timbre_name')
  2815. ->first();
  2816. if ($timbre_info) {
  2817. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  2818. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  2819. }
  2820. }
  2821. try {
  2822. DB::beginTransaction();
  2823. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  2824. $segment_ids_to_create_task = [];
  2825. $segments_data = [];
  2826. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  2827. if (!empty($global_update_data)) {
  2828. // 如果角色不存在,则只更新当前分镜
  2829. if (!$target_voice_actor) {
  2830. // 只处理当前分镜
  2831. $affected_segments = DB::table('mp_episode_segments')
  2832. ->where('segment_id', $segment_id)
  2833. ->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')
  2834. ->get();
  2835. } else {
  2836. // 获取该角色的所有分镜
  2837. $affected_segments = DB::table('mp_episode_segments')
  2838. ->where('episode_id', $episode_id)
  2839. ->where('voice_actor', $target_voice_actor)
  2840. ->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')
  2841. ->get();
  2842. }
  2843. foreach ($affected_segments as $seg) {
  2844. $seg = (array)$seg;
  2845. $sid = getProp($seg, 'segment_id');
  2846. // 检查参数是否发生变化
  2847. $has_changed = false;
  2848. foreach ($global_update_data as $field => $new_value) {
  2849. $old_value = getProp($seg, $field);
  2850. if ($old_value != $new_value) {
  2851. $has_changed = true;
  2852. break;
  2853. }
  2854. }
  2855. if ($has_changed) {
  2856. $segment_ids_to_create_task[] = $sid;
  2857. $segments_data[$sid] = $seg;
  2858. }
  2859. }
  2860. // 只有在有变化的分镜时才更新
  2861. if (!empty($segment_ids_to_create_task)) {
  2862. $global_segment_update_data = $global_update_data;
  2863. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  2864. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  2865. DB::table('mp_episode_segments')
  2866. ->where('episode_id', $episode_id)
  2867. ->where('voice_actor', $target_voice_actor)
  2868. ->whereIn('segment_id', $segment_ids_to_create_task)
  2869. ->update($global_segment_update_data);
  2870. }
  2871. if ($global_voice_type) {
  2872. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  2873. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  2874. $roles_updated = false;
  2875. foreach ($episode_roles as &$role) {
  2876. // 通过 role 字段匹配角色名,而不是 voice_name
  2877. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  2878. continue;
  2879. }
  2880. $role['voice_type'] = $global_voice_type;
  2881. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  2882. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  2883. $roles_updated = true;
  2884. }
  2885. unset($role);
  2886. if ($roles_updated) {
  2887. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  2888. 'roles' => json_encode($episode_roles, 256),
  2889. 'updated_at' => date('Y-m-d H:i:s'),
  2890. ]);
  2891. }
  2892. }
  2893. }
  2894. // 如果有单个分镜更新,检查是否有变化
  2895. if (!empty($segment_update_data)) {
  2896. // 获取当前分镜数据
  2897. $current_segment = DB::table('mp_episode_segments')
  2898. ->where('segment_id', $segment_id)
  2899. ->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')
  2900. ->first();
  2901. if ($current_segment) {
  2902. $current_segment = (array)$current_segment;
  2903. // 检查参数是否发生变化
  2904. $has_changed = false;
  2905. foreach ($segment_update_data as $field => $new_value) {
  2906. $old_value = getProp($current_segment, $field);
  2907. if ($old_value != $new_value) {
  2908. $has_changed = true;
  2909. break;
  2910. }
  2911. }
  2912. if ($has_changed) {
  2913. // 如果该分镜还未在列表中,添加进去
  2914. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  2915. $segment_ids_to_create_task[] = $segment_id;
  2916. $segments_data[$segment_id] = $current_segment;
  2917. }
  2918. // 更新分镜数据并清空音频URL
  2919. $segment_update_data['audio_url'] = '';
  2920. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  2921. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  2922. }
  2923. }
  2924. }
  2925. // 为所有有变化的分镜创建音频合成任务
  2926. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  2927. if (!empty($segment_ids_to_create_task)) {
  2928. foreach ($segment_ids_to_create_task as $sid) {
  2929. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  2930. if ($sid === $segment_id && $has_all_special_params) {
  2931. continue;
  2932. }
  2933. // 重新获取更新后的分镜数据
  2934. $updated_segment = DB::table('mp_episode_segments')
  2935. ->where('segment_id', $sid)
  2936. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  2937. ->first();
  2938. if (!$updated_segment) continue;
  2939. $updated_segment = (array)$updated_segment;
  2940. // 检查dialogue是否为空
  2941. $dialogue = getProp($updated_segment, 'dialogue');
  2942. if (empty($dialogue)) {
  2943. // dialogue为空时,直接写入默认音频信息
  2944. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  2945. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  2946. 'audio_duration' => 2.0,
  2947. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  2948. 'updated_at' => date('Y-m-d H:i:s')
  2949. ]);
  2950. continue;
  2951. }
  2952. $generate_json = [
  2953. 'text' => $dialogue,
  2954. 'role' => getProp($updated_segment, 'voice_actor'),
  2955. 'voice_type' => getProp($updated_segment, 'voice_type'),
  2956. 'voice_name' => getProp($updated_segment, 'voice_name'),
  2957. 'emotion' => getProp($updated_segment, 'emotion'),
  2958. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  2959. 'gender' => getProp($updated_segment, 'gender'),
  2960. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  2961. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  2962. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  2963. 'pitch' => getProp($updated_segment, 'pitch', 0),
  2964. ];
  2965. // 插入视频配音合成任务
  2966. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2967. 'alias_segment_id' => $sid,
  2968. 'generate_status' => '执行中',
  2969. 'audio_url' => '',
  2970. 'generate_json' => json_encode($generate_json, 256),
  2971. 'created_at' => date('Y-m-d H:i:s'),
  2972. 'updated_at' => date('Y-m-d H:i:s'),
  2973. ]);
  2974. if (!$dubTaskId) {
  2975. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  2976. continue;
  2977. }
  2978. // 将任务ID添加到Redis列表中
  2979. Redis::lpush('dub_video_task_queue', $dubTaskId);
  2980. // 请求远程服务器执行生成
  2981. try {
  2982. sleep(1);
  2983. $client = new Client(['timeout' => 300, 'verify' => false]);
  2984. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2985. $response = $result->getBody()->getContents();
  2986. $response_arr = json_decode($response, true);
  2987. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2988. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2989. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  2990. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  2991. }
  2992. } catch (\Exception $e) {
  2993. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  2994. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  2995. }
  2996. }
  2997. }
  2998. DB::commit();
  2999. } catch (\Exception $e) {
  3000. DB::rollBack();
  3001. Utils::throwError('20003:'.$e->getMessage());
  3002. }
  3003. return true;
  3004. }
  3005. public function episodePicsInfo($data) {
  3006. $anime_id = getProp($data, 'anime_id');
  3007. $episode_id = getProp($data, 'episode_id');
  3008. // 参数验证
  3009. if (!$anime_id && !$episode_id) {
  3010. Utils::throwError('20003:请提供动漫ID或分集ID');
  3011. }
  3012. // 根据参数获取数据源
  3013. if ($episode_id) {
  3014. // 从剧集表获取
  3015. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3016. if (!$source) Utils::throwError('20003:该剧集不存在');
  3017. $table_name = 'mp_anime_episodes';
  3018. $id_field = 'id';
  3019. $id_value = $episode_id;
  3020. // 获取剧集的anime_id用于继承全局数据
  3021. $anime_id = getProp($source, 'anime_id');
  3022. } else {
  3023. // 从动漫表获取
  3024. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3025. if (!$source) Utils::throwError('20003:该动漫不存在');
  3026. $table_name = 'mp_animes';
  3027. $id_field = 'id';
  3028. $id_value = $anime_id;
  3029. }
  3030. $source = (array)$source;
  3031. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3032. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3033. // 如果是分集数据,需要处理继承和任务创建逻辑
  3034. if ($episode_id) {
  3035. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3036. }
  3037. // 返回生成器函数,用于 SSE 流式输出
  3038. return function() use ($roles, $scenes, $table_name, $id_field, $id_value) {
  3039. $startTime = time();
  3040. $maxDuration = 600; // 10分钟超时
  3041. $checkInterval = 3; // 每3秒检查一次
  3042. // Redis 缓存键
  3043. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3044. // 生成当前数据的哈希值用于比较
  3045. $generateHash = function($roles, $scenes) {
  3046. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes], JSON_UNESCAPED_UNICODE));
  3047. };
  3048. // 发送初始数据
  3049. $currentHash = $generateHash($roles, $scenes);
  3050. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3051. echo "data: " . json_encode([
  3052. 'type' => 'init',
  3053. 'data' => [
  3054. 'roles' => $roles,
  3055. 'scenes' => $scenes,
  3056. 'start_time' => $startTime
  3057. ]
  3058. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3059. ob_flush();
  3060. flush();
  3061. // 持续轮询任务状态
  3062. while (time() - $startTime < $maxDuration) {
  3063. $hasProcessing = false;
  3064. $updated = false;
  3065. // 检查角色任务状态
  3066. foreach ($roles as $index => &$role) {
  3067. $task_id = getProp($role, 'task_id');
  3068. $task_status = getProp($role, 'task_status');
  3069. $existing_url = getProp($role, 'url');
  3070. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3071. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3072. $hasProcessing = ($task_status === 'processing');
  3073. // 查询任务状态
  3074. $task = DB::table('mp_generate_pic_tasks')
  3075. ->where('id', $task_id)
  3076. ->select('id', 'status', 'result_url', 'error_message')
  3077. ->first();
  3078. if ($task) {
  3079. $task = (array)$task;
  3080. $status = getProp($task, 'status');
  3081. // 如果任务完成或失败
  3082. if (in_array($status, ['success', 'failed'])) {
  3083. $role['task_status'] = $status;
  3084. if ($status === 'success') {
  3085. $result_url = getProp($task, 'result_url');
  3086. if ($result_url) {
  3087. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3088. if (is_array($result_urls) && !empty($result_urls[0])) {
  3089. $role['url'] = $result_urls[0];
  3090. }
  3091. }
  3092. }
  3093. $updated = true;
  3094. } else if ($status === 'processing') {
  3095. $hasProcessing = true;
  3096. }
  3097. }
  3098. }
  3099. }
  3100. // 检查场景任务状态
  3101. foreach ($scenes as $index => &$scene) {
  3102. $task_id = getProp($scene, 'task_id');
  3103. $task_status = getProp($scene, 'task_status');
  3104. $existing_url = getProp($scene, 'url');
  3105. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3106. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3107. $hasProcessing = ($task_status === 'processing');
  3108. // 查询任务状态
  3109. $task = DB::table('mp_generate_pic_tasks')
  3110. ->where('id', $task_id)
  3111. ->select('id', 'status', 'result_url', 'error_message')
  3112. ->first();
  3113. if ($task) {
  3114. $task = (array)$task;
  3115. $status = getProp($task, 'status');
  3116. // 如果任务完成或失败
  3117. if (in_array($status, ['success', 'failed'])) {
  3118. $scene['task_status'] = $status;
  3119. if ($status === 'success') {
  3120. $result_url = getProp($task, 'result_url');
  3121. if ($result_url) {
  3122. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3123. if (is_array($result_urls) && !empty($result_urls[0])) {
  3124. $scene['url'] = $result_urls[0];
  3125. }
  3126. }
  3127. }
  3128. $updated = true;
  3129. } else if ($status === 'processing') {
  3130. $hasProcessing = true;
  3131. }
  3132. }
  3133. }
  3134. }
  3135. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3136. if ($updated) {
  3137. $newHash = $generateHash($roles, $scenes);
  3138. $cachedHash = Redis::get($cacheKey);
  3139. // 只有当数据真正变化时才更新数据库和发送事件
  3140. if ($newHash !== $cachedHash) {
  3141. try {
  3142. // 更新数据库
  3143. DB::table($table_name)->where($id_field, $id_value)->update([
  3144. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3145. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3146. 'updated_at' => date('Y-m-d H:i:s')
  3147. ]);
  3148. // 更新缓存
  3149. Redis::setex($cacheKey, 600, $newHash);
  3150. // 发送更新事件
  3151. echo "data: " . json_encode([
  3152. 'type' => 'update',
  3153. 'data' => [
  3154. 'roles' => $roles,
  3155. 'scenes' => $scenes,
  3156. 'elapsed_time' => time() - $startTime
  3157. ]
  3158. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3159. ob_flush();
  3160. flush();
  3161. } catch (\Exception $e) {
  3162. dLog('anime')->error('更新角色/场景信息失败: ' . $e->getMessage());
  3163. }
  3164. } else {
  3165. // 即使哈希相同,如果有URL更新也要发送事件
  3166. $hasUrlUpdate = false;
  3167. foreach ($roles as $role) {
  3168. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3169. $hasUrlUpdate = true;
  3170. break;
  3171. }
  3172. }
  3173. if (!$hasUrlUpdate) {
  3174. foreach ($scenes as $scene) {
  3175. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3176. $hasUrlUpdate = true;
  3177. break;
  3178. }
  3179. }
  3180. }
  3181. if ($hasUrlUpdate) {
  3182. // 强制更新数据库和发送事件
  3183. try {
  3184. DB::table($table_name)->where($id_field, $id_value)->update([
  3185. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3186. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3187. 'updated_at' => date('Y-m-d H:i:s')
  3188. ]);
  3189. // 更新缓存
  3190. Redis::setex($cacheKey, 600, $newHash);
  3191. // 发送更新事件
  3192. echo "data: " . json_encode([
  3193. 'type' => 'update',
  3194. 'data' => [
  3195. 'roles' => $roles,
  3196. 'scenes' => $scenes,
  3197. 'elapsed_time' => time() - $startTime
  3198. ]
  3199. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3200. ob_flush();
  3201. flush();
  3202. } catch (\Exception $e) {
  3203. dLog('anime')->error('强制更新角色/场景信息失败: ' . $e->getMessage());
  3204. }
  3205. }
  3206. }
  3207. }
  3208. // 如果所有任务都已完成,发送完成事件并退出
  3209. if (!$hasProcessing) {
  3210. // 查询数据库中的最终数据,确保返回最新的完整数据
  3211. try {
  3212. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3213. if ($finalSource) {
  3214. $finalSource = (array)$finalSource;
  3215. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3216. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3217. // 使用数据库中的最终数据
  3218. $roles = $finalRoles;
  3219. $scenes = $finalScenes;
  3220. }
  3221. } catch (\Exception $e) {
  3222. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3223. // 如果查询失败,继续使用内存中的数据
  3224. }
  3225. // 清理缓存
  3226. Redis::del($cacheKey);
  3227. echo "data: " . json_encode([
  3228. 'type' => 'completed',
  3229. 'data' => [
  3230. 'roles' => $roles,
  3231. 'scenes' => $scenes,
  3232. 'total_time' => time() - $startTime
  3233. ]
  3234. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3235. ob_flush();
  3236. flush();
  3237. break;
  3238. }
  3239. // 等待下次检查
  3240. sleep($checkInterval);
  3241. }
  3242. // 超时处理
  3243. if (time() - $startTime >= $maxDuration) {
  3244. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3245. try {
  3246. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3247. if ($finalSource) {
  3248. $finalSource = (array)$finalSource;
  3249. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3250. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3251. // 使用数据库中的最终数据
  3252. $roles = $finalRoles;
  3253. $scenes = $finalScenes;
  3254. }
  3255. } catch (\Exception $e) {
  3256. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3257. // 如果查询失败,继续使用内存中的数据
  3258. }
  3259. // 清理缓存
  3260. Redis::del($cacheKey);
  3261. echo "data: " . json_encode([
  3262. 'type' => 'timeout',
  3263. 'message' => '轮询超时,请刷新页面查看最新状态',
  3264. 'data' => [
  3265. 'roles' => $roles,
  3266. 'scenes' => $scenes
  3267. ]
  3268. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3269. ob_flush();
  3270. flush();
  3271. }
  3272. };
  3273. }
  3274. public function clipSegmentVideo($data) {
  3275. $segment_id = getProp($data, 'segment_id');
  3276. $video_time_point_start = getProp($data, 'video_time_point_start');
  3277. $video_time_point_end = getProp($data, 'video_time_point_end');
  3278. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3279. Utils::throwError('20003:参数异常');
  3280. }
  3281. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3282. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3283. }
  3284. $video_duration = $video_time_point_end - $video_time_point_start;
  3285. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3286. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3287. 'video_duration' => $video_duration,
  3288. 'video_time_point_start' => $video_time_point_start,
  3289. 'video_time_point_end' => $video_time_point_end,
  3290. 'updated_at' => date('Y-m-d H:i:s')
  3291. ]);
  3292. }
  3293. // 轮训获取图片任务结果
  3294. private function loopGetPicTaskResult($task_id) {
  3295. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3296. if (!$task) {
  3297. return '';
  3298. }
  3299. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3300. $model = getProp($task, 'model');
  3301. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3302. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3303. $isSyncModel = $isVolcModel || $isGptModel;
  3304. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3305. $start_count = 0;
  3306. $img_url = '';
  3307. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3308. sleep(3);
  3309. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3310. // 如果任务已经完成,直接返回结果
  3311. if ($task->status === 'success' && $task->result_url) {
  3312. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3313. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3314. }
  3315. // 如果任务已失败,返回空
  3316. if ($task->status === 'failed') {
  3317. return '';
  3318. }
  3319. if ($isSyncModel) continue;
  3320. // 查询任务状态
  3321. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3322. if ($statusInfo['status'] === 'success') {
  3323. $task->updateStatus('success', [
  3324. 'result_url' => $statusInfo['result_url'],
  3325. 'result_json' => $statusInfo['result_json'] ?? []
  3326. ]);
  3327. // 同步调整分镜图片状态和结果
  3328. if (getProp($task, 'alias_segment_id')) {
  3329. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3330. 'img_url' => $statusInfo['result_url'][0],
  3331. 'pic_task_status' => '已完成',
  3332. ]);
  3333. }
  3334. $img_url = $statusInfo['result_url'][0];
  3335. break;
  3336. } elseif ($statusInfo['status'] === 'failed') {
  3337. $task->updateStatus('failed', [
  3338. 'error_message' => $statusInfo['error_message'],
  3339. 'result_json' => $statusInfo['result_json'] ?? []
  3340. ]);
  3341. if (getProp($task, 'alias_segment_id')) {
  3342. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3343. 'pic_task_status' => '失败',
  3344. ]);
  3345. }
  3346. break;
  3347. }
  3348. $start_count++;
  3349. }
  3350. return $img_url;
  3351. }
  3352. /**
  3353. * 从分镜内容中提取涉及的角色
  3354. */
  3355. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3356. $found_characters = [];
  3357. foreach ($available_characters as $character) {
  3358. // 检查角色名称是否在分镜内容中出现
  3359. if (strpos($segment_content, $character) !== false) {
  3360. $found_characters[] = $character;
  3361. }
  3362. }
  3363. if (!$found_characters) {
  3364. foreach ($roles as $character) {
  3365. // 检查角色名称是否在分镜内容中出现
  3366. if (strpos($segment_content, $character) !== false) {
  3367. $found_characters[] = $character;
  3368. }
  3369. }
  3370. }
  3371. return array_unique($found_characters);
  3372. }
  3373. // 从分镜剧本中提取关键字段
  3374. private function handleSegmentContent(&$data) {
  3375. $segmentContent = getProp($data, 'segment_content');
  3376. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3377. $segmentData = [
  3378. 'description' => '',
  3379. 'composition' => '',
  3380. 'camera_movement' => '',
  3381. 'voice_actor' => '',
  3382. 'dialogue' => '',
  3383. 'frame_type' => '',
  3384. 'scene' => '', // 场景
  3385. 'characters' => '', // 出镜角色
  3386. 'tail_frame' => '', // 尾帧描述
  3387. 'emotion' => '中性', // 情感
  3388. 'gender' => '0', // 性别(0未知,1男,2女)
  3389. 'speed_ratio' => 0, // 语速
  3390. 'loudness_ratio' => 0, // 音量
  3391. 'emotion_scale' => 4, // 情感强度
  3392. 'pitch' => 0, // 音调
  3393. ];
  3394. // 用于存储需要从 segment_content 中移除的匹配项
  3395. $replaceEmptyArr = [];
  3396. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3397. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3398. $segmentData['description'] = trim($descMatch[1]);
  3399. $data['description'] = trim($descMatch[1]);
  3400. }
  3401. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3402. $segmentData['composition'] = trim($compMatch[1]);
  3403. $data['composition'] = trim($compMatch[1]);
  3404. }
  3405. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3406. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3407. $data['camera_movement'] = trim($cameraMatch[1]);
  3408. }
  3409. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3410. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3411. $data['voice_actor'] = trim($voiceMatch[1]);
  3412. }
  3413. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3414. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3415. $data['dialogue'] = trim($dialogueMatch[1]);
  3416. }
  3417. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3418. $segmentData['frame_type'] = trim($frameMatch[1]);
  3419. $data['frame_type'] = trim($frameMatch[1]);
  3420. }
  3421. // 场景字段
  3422. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3423. $segmentData['scene'] = trim($sceneMatch[1]);
  3424. $data['scene'] = trim($sceneMatch[1]);
  3425. }
  3426. // 出镜角色字段
  3427. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3428. $segmentData['characters'] = trim($charactersMatch[1]);
  3429. $data['characters'] = trim($charactersMatch[1]);
  3430. }
  3431. // 尾帧描述字段
  3432. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3433. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3434. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3435. }
  3436. // 情感字段
  3437. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3438. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3439. $segmentData['emotion'] = trim($emotionMatch[1]);
  3440. $data['emotion'] = trim($emotionMatch[1]);
  3441. }
  3442. // 性别字段
  3443. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3444. $replaceEmptyArr[] = trim($genderMatch[0]);
  3445. $genderStr = trim($genderMatch[1]);
  3446. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3447. $segmentData['gender'] = '1';
  3448. $data['gender'] = '1';
  3449. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3450. $segmentData['gender'] = '2';
  3451. $data['gender'] = '2';
  3452. } else {
  3453. $segmentData['gender'] = '0';
  3454. $data['gender'] = '0';
  3455. }
  3456. }
  3457. // 语速字段
  3458. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3459. $replaceEmptyArr[] = trim($speedMatch[0]);
  3460. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3461. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3462. }
  3463. // 音量字段
  3464. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3465. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3466. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3467. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3468. }
  3469. // 情感强度字段
  3470. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3471. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3472. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3473. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3474. }
  3475. // 音调字段
  3476. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3477. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3478. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3479. $data['pitch'] = (int)trim($pitchMatch[1]);
  3480. }
  3481. // 从 segment_content 中移除已提取的配音参数字段
  3482. if (!empty($replaceEmptyArr)) {
  3483. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3484. }
  3485. // 如果有配音角色,查询音色信息并验证情感
  3486. $voice_actor = $segmentData['voice_actor'];
  3487. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3488. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3489. $anime_id = getProp($data, 'anime_id');
  3490. $episode_id = getProp($data, 'episode_id');
  3491. // 优先从剧集的角色列表中查找
  3492. $roles = [];
  3493. if ($episode_id) {
  3494. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3495. if ($episode && getProp($episode, 'roles')) {
  3496. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3497. }
  3498. }
  3499. // 如果剧集中没有,从动漫的角色列表中查找
  3500. if (empty($roles) && $anime_id) {
  3501. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3502. if ($anime && getProp($anime, 'roles')) {
  3503. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3504. }
  3505. }
  3506. // 查找匹配的角色音色信息
  3507. $timbre_info = null;
  3508. foreach ($roles as $role) {
  3509. if (getProp($role, 'role') === $voice_actor) {
  3510. $timbre_info = $role;
  3511. break;
  3512. }
  3513. }
  3514. // 如果找到音色信息,添加到数据中
  3515. if ($timbre_info) {
  3516. $voice_type = getProp($timbre_info, 'voice_type');
  3517. $voice_name = getProp($timbre_info, 'voice_name');
  3518. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3519. if ($voice_type) {
  3520. $data['voice_type'] = $voice_type;
  3521. $segmentData['voice_type'] = $voice_type;
  3522. }
  3523. if ($voice_name) {
  3524. $data['voice_name'] = $voice_name;
  3525. $segmentData['voice_name'] = $voice_name;
  3526. }
  3527. if ($voice_audio_url) {
  3528. $data['voice_audio_url'] = $voice_audio_url;
  3529. $segmentData['voice_audio_url'] = $voice_audio_url;
  3530. }
  3531. // 验证情感是否在音色支持的情感列表中
  3532. if ($voice_type) {
  3533. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3534. if ($timbre_emotion) {
  3535. $timbre_emotion = explode(',', $timbre_emotion);
  3536. } else {
  3537. $timbre_emotion = [];
  3538. }
  3539. $emotion = getProp($segmentData, 'emotion', '中性');
  3540. if (!in_array($emotion, $timbre_emotion)) {
  3541. $emotion = '中性';
  3542. }
  3543. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3544. $emotion_list = array_flip($emotion_list);
  3545. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3546. $data['emotion_type'] = $emotion_type;
  3547. $segmentData['emotion_type'] = $emotion_type;
  3548. }
  3549. }
  3550. }
  3551. return $segmentData;
  3552. }
  3553. public function createSegmentVideoTask($data) {
  3554. $segment_id = getProp($data, 'segment_id');
  3555. $tail_frame = getProp($data, 'tail_frame');
  3556. $first_frame_url = getProp($data, 'first_frame_url');
  3557. $tail_frame_url = getProp($data, 'tail_frame_url');
  3558. $generate_audio = getProp($data, 'generate_audio', 0);
  3559. if (!$segment_id) {
  3560. Utils::throwError('1002:分镜ID不能为空');
  3561. }
  3562. // 获取分镜信息
  3563. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3564. if (!$segment) {
  3565. Utils::throwError('20003:分镜不存在');
  3566. }
  3567. $segment = (array)$segment;
  3568. $episode_id = getProp($segment, 'episode_id');
  3569. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3570. if (!$ratio) $ratio = '9:16';
  3571. // 获取分镜内容
  3572. $segmentContent = getProp($segment, 'segment_content', '');
  3573. // 检查 $segmentContent 中是否已有尾帧描述
  3574. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3575. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3576. $finalTailFrame = '';
  3577. if ($tail_frame) {
  3578. // 用户输入了尾帧描述,优先使用
  3579. $finalTailFrame = $tail_frame;
  3580. // 如果 segmentContent 中已有尾帧描述,需要替换
  3581. if ($contentHasTailFrame) {
  3582. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3583. }
  3584. } elseif ($contentHasTailFrame) {
  3585. // segmentContent 中有尾帧描述,使用它
  3586. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3587. } else {
  3588. // 两者都没有,使用分镜表中的尾帧描述
  3589. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3590. }
  3591. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3592. $hasDialogue = false;
  3593. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3594. $dialogue = trim($dialogueMatch[1]);
  3595. // 如果台词不为空且不是"无"
  3596. if (!empty($dialogue) && $dialogue !== '无') {
  3597. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3598. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3599. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3600. $hasDialogue = true;
  3601. }
  3602. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3603. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3604. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3605. if (!preg_match('/^[“]/', $dialogue)) {
  3606. $dialogue = '“' . $dialogue;
  3607. }
  3608. if (!preg_match('/[”]$/', $dialogue)) {
  3609. $dialogue .= '”';
  3610. }
  3611. // 将修改后的台词替换回 $segmentContent
  3612. $originalDialogue = $dialogueMatch[1];
  3613. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3614. }
  3615. }
  3616. // 构建完整的提示词
  3617. $fullPrompt = $segmentContent;
  3618. if ($finalTailFrame && !$contentHasTailFrame) {
  3619. // 只有当 segmentContent 中没有尾帧描述时才追加
  3620. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3621. }
  3622. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3623. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3624. $fullPrompt = trim($fullPrompt);
  3625. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3626. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3627. // 智能选择视频时长
  3628. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3629. $videoDuration = -1;
  3630. // 处理视频模型
  3631. $model = getProp($data, 'model');
  3632. if (!$model) {
  3633. // 用户没有输入,从episode表获取
  3634. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3635. $model = getProp($episode, 'video_model');
  3636. if (!$model) {
  3637. // episode表也没有,使用默认值
  3638. $model = 'doubao-seedance-1-5-pro-251215';
  3639. }
  3640. }
  3641. // 验证模型是否在可用模型表中
  3642. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3643. $model = 'doubao-seedance-1-5-pro-251215';
  3644. }
  3645. // 保存到episode表
  3646. $episode_id = getProp($segment, 'episode_id');
  3647. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3648. 'video_model' => $model,
  3649. 'updated_at' => date('Y-m-d H:i:s')
  3650. ]);
  3651. // 构建视频生成参数
  3652. $videoParams = [
  3653. 'model' => $model,
  3654. 'alias_segment_id' => $segment_id,
  3655. 'prompt' => trim($fullPrompt),
  3656. 'video_duration' => $videoDuration,
  3657. 'video_resolution' => '720P',
  3658. 'seed' => -1,
  3659. 'ratio' => $ratio,
  3660. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3661. 'draft' => false,
  3662. 'watermark' => false,
  3663. 'camera_fixed' => false,
  3664. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3665. ];
  3666. // 如果分镜有图片,作为首帧
  3667. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3668. $hasVideo = !empty(getProp($segment, 'video_url'));
  3669. if ($hasImage) {
  3670. if ($first_frame_url) {
  3671. $videoParams['first_frame_url'] = $first_frame_url;
  3672. }else {
  3673. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3674. }
  3675. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3676. }
  3677. // 构建content数组
  3678. $videoParams['content'] = [
  3679. [
  3680. 'type' => 'text',
  3681. 'text' => $videoParams['prompt'],
  3682. ]
  3683. ];
  3684. // 如果有首帧图片,添加到content中
  3685. if ($hasImage) {
  3686. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3687. $videoParams['content'][] = [
  3688. 'type' => 'image_url',
  3689. 'image_url' => [
  3690. 'url' => $videoParams['first_frame_url'],
  3691. ],
  3692. 'role' => 'reference_image',
  3693. ];
  3694. if (isset($videoParams['tail_frame_url'])) {
  3695. $videoParams['content'][] = [
  3696. 'type' => 'image_url',
  3697. 'image_url' => [
  3698. 'url' => $videoParams['tail_frame_url'],
  3699. ],
  3700. 'role' => 'reference_image',
  3701. ];
  3702. }
  3703. }else {
  3704. $videoParams['content'][] = [
  3705. 'type' => 'image_url',
  3706. 'image_url' => [
  3707. 'url' => $videoParams['first_frame_url'],
  3708. ],
  3709. 'role' => 'first_frame',
  3710. ];
  3711. if (isset($videoParams['tail_frame_url'])) {
  3712. $videoParams['content'][] = [
  3713. 'type' => 'image_url',
  3714. 'image_url' => [
  3715. 'url' => $videoParams['tail_frame_url'],
  3716. ],
  3717. 'role' => 'last_frame',
  3718. ];
  3719. }
  3720. }
  3721. }
  3722. // 获取配音音频URL
  3723. $audioUrl = getProp($segment, 'audio_url');
  3724. $audioDuration = getProp($segment, 'audio_duration');
  3725. // 音频传入的前提:必须有至少一张图片或一个视频
  3726. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  3727. // dd($videoParams);
  3728. // 根据模型选择不同的视频生成方法
  3729. if (strpos($model, 'jimeng') !== false) {
  3730. // 即梦模型参数调整
  3731. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  3732. unset($videoParams['content']); // 即梦不使用content格式
  3733. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  3734. } elseif (strpos($model, 'kling') !== false) {
  3735. // Keling模型参数调整
  3736. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  3737. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  3738. unset($videoParams['ratio']);
  3739. unset($videoParams['content']); // Keling不使用content格式
  3740. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  3741. } elseif (strpos($model, 'zhizhen') !== false) {
  3742. // 智帧20等新模型使用统一API
  3743. // 构建统一API参数
  3744. $unifiedParams = [
  3745. 'model_code' => $model,
  3746. 'alias_segment_id' => $segment_id,
  3747. 'prompt' => trim($fullPrompt),
  3748. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  3749. 'video_resolution' => strtolower($videoParams['video_resolution']),
  3750. 'video_ratio' => $ratio,
  3751. 'seed' => -1,
  3752. ];
  3753. // 构建parameters参数
  3754. $parameters = [
  3755. 'seconds' => $unifiedParams['video_duration'],
  3756. 'resolution' => $unifiedParams['video_resolution'],
  3757. 'ratio' => $ratio,
  3758. // 'video_mode' => 'multi_image',
  3759. // 'mode' => 'multi_image',
  3760. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  3761. ];
  3762. $hasImage = false;
  3763. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  3764. if ($hasImage) {
  3765. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  3766. if (isset($videoParams['tail_frame_url'])) {
  3767. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  3768. }
  3769. // 只有在有图片的情况下才能添加参考音频
  3770. if ($audioUrl) {
  3771. // $parameters['reference_audios'] = [$audioUrl];
  3772. }
  3773. } else {
  3774. // 没有图片时,记录错误日志
  3775. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  3776. 'segment_id' => $segment_id,
  3777. 'model' => $model
  3778. ]);
  3779. }
  3780. $unifiedParams['parameters'] = $parameters;
  3781. // 调用统一API创建任务
  3782. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  3783. } else {
  3784. // Seedance模型(默认)
  3785. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  3786. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3787. // 添加配音音频到content中
  3788. $videoParams['content'][] = [
  3789. 'type' => 'audio_url',
  3790. 'audio_url' => [
  3791. 'url' => $audioUrl,
  3792. ],
  3793. 'role' => 'reference_audio',
  3794. ];
  3795. // 优化提示词,增加音频相关描述
  3796. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  3797. $videoParams['prompt'] = $audioPrompt;
  3798. $videoParams['content'][0]['text'] = $audioPrompt;
  3799. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  3800. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  3801. }
  3802. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  3803. }
  3804. // 更新分镜表的视频任务信息
  3805. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3806. 'video_task_id' => $task->id,
  3807. 'video_task_status' => '生成中',
  3808. 'generate_audio' => $generate_audio,
  3809. 'updated_at' => date('Y-m-d H:i:s')
  3810. ]);
  3811. return [
  3812. 'task_id' => $task->id,
  3813. 'status' => $task->status,
  3814. 'segment_id' => $segment_id,
  3815. 'video_duration' => $videoDuration
  3816. ];
  3817. }
  3818. public function createActVideoTask($data) {
  3819. $act_id = getProp($data, 'act_id');
  3820. $first_frame_url = getProp($data, 'first_frame_url');
  3821. $tail_frame_url = getProp($data, 'tail_frame_url');
  3822. $generate_audio = getProp($data, 'generate_audio', 1);
  3823. $video_duration = getProp($data, 'video_duration');
  3824. $video_resolution = getProp($data, 'video_resolution');
  3825. $ratio = getProp($data, 'ratio');
  3826. $products = getProp($data, 'products', []);
  3827. $reference_images = array_unique(getProp($data, 'reference_images', []));
  3828. if (!is_array($reference_images) || !is_array($products)) {
  3829. Utils::throwError('20003:传入的参考图或资产格式不正确');
  3830. }
  3831. if (!$act_id) {
  3832. Utils::throwError('1002:片段ID不能为空');
  3833. }
  3834. // 获取片段信息
  3835. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  3836. if (!$act) {
  3837. Utils::throwError('20003:片段不存在');
  3838. }
  3839. $act = (array)$act;
  3840. $anime_id = getProp($act, 'anime_id');
  3841. $episode_id = getProp($act, 'episode_id');
  3842. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3843. $ace_mode = getProp($anime, 'ace_mode');
  3844. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3845. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  3846. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  3847. // 将资产中新出现的资产放到extra_products中
  3848. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles和scenes做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  3849. if (!empty($products) && $episode) {
  3850. // 获取剧集中的角色和场景列表
  3851. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  3852. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  3853. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  3854. // 构建角色名称列表
  3855. $role_names = array_column($roles, 'role');
  3856. // 构建场景名称列表
  3857. $scene_names = array_column($scenes, 'scene');
  3858. // 遍历传入的products
  3859. foreach ($products as $product) {
  3860. $product_name = getProp($product, 'product_name');
  3861. // 如果product_name不在roles和scenes中
  3862. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names)) {
  3863. // 查找是否在extra_products中存在同名的
  3864. $found = false;
  3865. foreach ($extra_products as $key => $extra_product) {
  3866. if (getProp($extra_product, 'product_name') === $product_name) {
  3867. // 有同名的则覆盖
  3868. $extra_products[$key] = $product;
  3869. $found = true;
  3870. break;
  3871. }
  3872. }
  3873. // 没有则新增
  3874. if (!$found) {
  3875. $extra_products[] = $product;
  3876. }
  3877. }
  3878. }
  3879. if ($extra_products) {
  3880. // 保存到数据库
  3881. DB::table('mp_anime_episodes')
  3882. ->where('id', $episode_id)
  3883. ->update([
  3884. 'extra_products' => json_encode($extra_products, 256),
  3885. 'updated_at' => date('Y-m-d H:i:s')
  3886. ]);
  3887. }
  3888. }
  3889. // 获取分镜内容
  3890. $actContent = getProp($act, 'act_show_content', '');
  3891. // 音效同出(默认使用)
  3892. $current_generate_audio = $generate_audio ? 1 : 0;
  3893. // 构建完整的提示词
  3894. $processResult = $this->processActContentWithProducts($actContent, $products);
  3895. $fullPrompt = $processResult['content'];
  3896. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  3897. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  3898. // 处理视频模型
  3899. $model = getProp($data, 'model');
  3900. if (!$model) {
  3901. $model = getProp($episode, 'video_model');
  3902. if (!$model) {
  3903. // episode表也没有,使用默认值
  3904. $model = 'zhizhen-20-mini';
  3905. }
  3906. }
  3907. // 验证模型是否在可用模型表中
  3908. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3909. $model = 'zhizhen-20-mini';
  3910. }
  3911. // 保存到episode表
  3912. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3913. 'video_model' => $model,
  3914. 'updated_at' => date('Y-m-d H:i:s')
  3915. ]);
  3916. // 构建视频生成参数
  3917. $videoParams = [
  3918. 'model' => $model,
  3919. 'alias_act_id' => $act_id,
  3920. 'prompt' => trim($fullPrompt),
  3921. 'video_duration' => $videoDuration,
  3922. 'video_resolution' => $video_resolution,
  3923. 'seed' => -1,
  3924. 'ratio' => $ratio,
  3925. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3926. 'draft' => false,
  3927. 'watermark' => false,
  3928. 'camera_fixed' => false,
  3929. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3930. ];
  3931. // 如果分镜有图片,作为首帧
  3932. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  3933. $hasVideo = !empty(getProp($act, 'video_url'));
  3934. if ($hasImage) {
  3935. if ($first_frame_url) {
  3936. $videoParams['first_frame_url'] = $first_frame_url;
  3937. }else {
  3938. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  3939. }
  3940. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3941. }
  3942. // 构建content数组
  3943. $videoParams['content'] = [
  3944. [
  3945. 'type' => 'text',
  3946. 'text' => $videoParams['prompt'],
  3947. ]
  3948. ];
  3949. // 如果有首帧图片,添加到content中
  3950. if ($hasImage) {
  3951. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3952. $videoParams['content'][] = [
  3953. 'type' => 'image_url',
  3954. 'image_url' => [
  3955. 'url' => $videoParams['first_frame_url'],
  3956. ],
  3957. 'role' => 'reference_image',
  3958. ];
  3959. if (isset($videoParams['tail_frame_url'])) {
  3960. $videoParams['content'][] = [
  3961. 'type' => 'image_url',
  3962. 'image_url' => [
  3963. 'url' => $videoParams['tail_frame_url'],
  3964. ],
  3965. 'role' => 'reference_image',
  3966. ];
  3967. }
  3968. }else {
  3969. $videoParams['content'][] = [
  3970. 'type' => 'image_url',
  3971. 'image_url' => [
  3972. 'url' => $videoParams['first_frame_url'],
  3973. ],
  3974. 'role' => 'first_frame',
  3975. ];
  3976. if (isset($videoParams['tail_frame_url'])) {
  3977. $videoParams['content'][] = [
  3978. 'type' => 'image_url',
  3979. 'image_url' => [
  3980. 'url' => $videoParams['tail_frame_url'],
  3981. ],
  3982. 'role' => 'last_frame',
  3983. ];
  3984. }
  3985. }
  3986. }
  3987. // dd($videoParams);
  3988. // 根据模型选择不同的视频生成方法
  3989. if (strpos($model, 'jimeng') !== false) {
  3990. // 即梦模型参数调整
  3991. unset($videoParams['content']); // 即梦不使用content格式
  3992. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  3993. } elseif (strpos($model, 'kling') !== false) {
  3994. // Keling模型参数调整
  3995. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  3996. unset($videoParams['ratio']);
  3997. unset($videoParams['content']); // Keling不使用content格式
  3998. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  3999. } elseif (strpos($model, 'zhizhen') !== false) {
  4000. // 智帧20等新模型使用统一API
  4001. // 构建统一API参数
  4002. $unifiedParams = [
  4003. 'model_code' => $model,
  4004. 'alias_act_id' => $act_id,
  4005. 'prompt' => trim($fullPrompt),
  4006. 'video_duration' => $videoDuration,
  4007. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4008. 'video_ratio' => $ratio,
  4009. 'seed' => -1,
  4010. ];
  4011. // 构建parameters参数
  4012. $parameters = [
  4013. 'seconds' => $unifiedParams['video_duration'],
  4014. 'resolution' => $unifiedParams['video_resolution'],
  4015. 'ratio' => $ratio,
  4016. // 'video_mode' => 'multi_image',
  4017. // 'mode' => 'multi_image',
  4018. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4019. ];
  4020. $hasImage = false;
  4021. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4022. if ($hasImage) {
  4023. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4024. if (isset($videoParams['tail_frame_url'])) {
  4025. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4026. }
  4027. } else {
  4028. // 没有图片时,记录错误日志
  4029. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4030. 'act_id' => $act_id,
  4031. 'model' => $model
  4032. ]);
  4033. }
  4034. if ($reference_images) {
  4035. // 限制只传入9张参考图
  4036. $reference_images = array_slice($reference_images, 0, 9);
  4037. // 在处理之前先保存原始reference_images到任务参数中
  4038. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4039. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4040. $parameters['reference_images'] = $reference_images;
  4041. $parameters['video_mode'] = 'multi_image';
  4042. $parameters['mode'] = 'multi_image';
  4043. }
  4044. $unifiedParams['parameters'] = $parameters;
  4045. // 调用统一API创建任务
  4046. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4047. } else {
  4048. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4049. }
  4050. // 更新分镜表的视频任务信息
  4051. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4052. 'video_task_id' => $task->id,
  4053. 'video_task_status' => '生成中',
  4054. 'generate_audio' => $generate_audio,
  4055. 'updated_at' => date('Y-m-d H:i:s')
  4056. ]);
  4057. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4058. $episode_number = getProp($act, 'episode_number');
  4059. $act_number = getProp($act, 'act_number');
  4060. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4061. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4062. }
  4063. return [
  4064. 'task_id' => $task->id,
  4065. 'status' => $task->status,
  4066. 'act_id' => $act_id,
  4067. 'video_duration' => $videoDuration
  4068. ];
  4069. }
  4070. /**
  4071. * 根据提示词内容智能计算最优视频时长
  4072. *
  4073. * @param string $segmentContent 分镜内容
  4074. * @param string $tailFrame 尾帧描述
  4075. * @return int 视频时长(2-12秒)
  4076. */
  4077. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4078. // 合并所有文本内容
  4079. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4080. // 如果没有内容,返回默认时长
  4081. if (empty($fullText)) {
  4082. return 5;
  4083. }
  4084. // 计算文本长度(中文字符按2个字符计算)
  4085. $textLength = mb_strlen($fullText, 'UTF-8');
  4086. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4087. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4088. // 分析内容复杂度
  4089. $complexityScore = $this->analyzeContentComplexity($fullText);
  4090. // 基础时长计算(根据文本长度)
  4091. $baseDuration = 3; // 默认2秒
  4092. // if ($adjustedLength <= 20) {
  4093. // $baseDuration = 3;
  4094. // } elseif ($adjustedLength <= 40) {
  4095. // $baseDuration = 4;
  4096. // } elseif ($adjustedLength <= 60) {
  4097. // $baseDuration = 5;
  4098. // } elseif ($adjustedLength <= 80) {
  4099. // $baseDuration = 6;
  4100. // } elseif ($adjustedLength <= 100) {
  4101. // $baseDuration = 7;
  4102. // } elseif ($adjustedLength <= 120) {
  4103. // $baseDuration = 8;
  4104. // } else {
  4105. // $baseDuration = 9;
  4106. // }
  4107. // 根据内容复杂度调整时长
  4108. $finalDuration = $baseDuration + $complexityScore;
  4109. // 确保时长在2-12秒范围内
  4110. return max(4, min(12, $finalDuration));
  4111. }
  4112. /**
  4113. * 分析内容复杂度,返回时长调整值
  4114. *
  4115. * @param string $text 文本内容
  4116. * @return int 调整值(-2到+3)
  4117. */
  4118. private function analyzeContentComplexity($text) {
  4119. $score = 0;
  4120. // 动作关键词(需要更长时间展现)
  4121. $actionKeywords = [
  4122. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4123. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4124. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4125. ];
  4126. // 静态关键词(可以用较短时间)
  4127. $staticKeywords = [
  4128. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4129. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4130. ];
  4131. // 复杂场景关键词(需要更长时间)
  4132. $complexSceneKeywords = [
  4133. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4134. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4135. ];
  4136. // 情感关键词(需要适中时间表现)
  4137. $emotionKeywords = [
  4138. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4139. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4140. ];
  4141. // 检查动作关键词
  4142. foreach ($actionKeywords as $keyword) {
  4143. if (strpos($text, $keyword) !== false) {
  4144. $score += 1;
  4145. break; // 避免重复加分
  4146. }
  4147. }
  4148. // 检查静态关键词
  4149. foreach ($staticKeywords as $keyword) {
  4150. if (strpos($text, $keyword) !== false) {
  4151. $score -= 1;
  4152. break;
  4153. }
  4154. }
  4155. // 检查复杂场景关键词
  4156. foreach ($complexSceneKeywords as $keyword) {
  4157. if (strpos($text, $keyword) !== false) {
  4158. $score += 1;
  4159. break;
  4160. }
  4161. }
  4162. // 检查情感关键词
  4163. foreach ($emotionKeywords as $keyword) {
  4164. if (strpos($text, $keyword) !== false) {
  4165. $score += 1;
  4166. break;
  4167. }
  4168. }
  4169. // 检查时间相关词汇
  4170. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4171. $score += 1;
  4172. }
  4173. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4174. $score -= 1;
  4175. }
  4176. // 检查转场词汇
  4177. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4178. $score += 1;
  4179. }
  4180. // 检查环境描述(复杂环境需要更多时间)
  4181. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4182. $score += 1;
  4183. }
  4184. // 检查对话内容(对话需要更多时间)
  4185. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4186. $score += 1;
  4187. }
  4188. // 限制调整范围
  4189. return max(-1, min(4, $score));
  4190. }
  4191. /**
  4192. * 创建完整视频合成任务
  4193. *
  4194. * @param array $data
  4195. * @return array
  4196. */
  4197. public function createCompleteVideoTask($data)
  4198. {
  4199. $animeId = getProp($data, 'anime_id');
  4200. $episodeId = getProp($data, 'episode_id');
  4201. // 验证参数
  4202. if (!$animeId || !$episodeId) {
  4203. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4204. }
  4205. // 检查是否已存在处理中的任务
  4206. $existingTask = DB::table('mp_complete_video_tasks')
  4207. ->where('anime_id', $animeId)
  4208. ->where('episode_id', $episodeId)
  4209. ->whereIn('generate_status', ['执行中'])
  4210. ->first();
  4211. if ($existingTask) {
  4212. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4213. }
  4214. // 获取全能模式状态
  4215. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4216. if ((int)$ace_mode === 1) {
  4217. // 获取所有片段的配音视频,按 act_number 排序
  4218. $segments = DB::table('mp_episode_segments')
  4219. ->where('anime_id', $animeId)
  4220. ->where('episode_id', $episodeId)
  4221. ->orderBy('segment_number')
  4222. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4223. ->get();
  4224. // 检查是否所有片段都有视频
  4225. $missingVideos = $segments->filter(function($segment) {
  4226. return empty($segment->video_url);
  4227. });
  4228. if ($missingVideos->isNotEmpty()) {
  4229. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4230. }
  4231. }else {
  4232. // 获取所有分镜的配音视频,按 segment_number 排序
  4233. $segments = DB::table('mp_episode_segments')
  4234. ->where('anime_id', $animeId)
  4235. ->where('episode_id', $episodeId)
  4236. ->orderBy('segment_number')
  4237. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4238. ->get();
  4239. // 检查是否所有分镜都有配音和视频
  4240. $missingVideos = $segments->filter(function($segment) {
  4241. return empty($segment->audio_url) || empty($segment->video_url);
  4242. });
  4243. if ($missingVideos->isNotEmpty()) {
  4244. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4245. }
  4246. }
  4247. if ($segments->isEmpty()) {
  4248. Utils::throwError('20003:未找到该剧集的分镜数据');
  4249. }
  4250. // 获取当前完整视频url
  4251. $completeVideoUrl = DB::table('mp_anime_episodes')
  4252. ->where('anime_id', $animeId)
  4253. ->where('id', $episodeId)
  4254. ->value('complete_video_url');
  4255. // 构建 generate_json
  4256. $generateJson = [];
  4257. $sequence = 1;
  4258. foreach ($segments as $segment) {
  4259. if ((int)$ace_mode === 1) {
  4260. $generateJson[] = [
  4261. 'sequence' => $sequence++,
  4262. 'video_url' => $segment->video_url,
  4263. 'video_time_point_start' => $segment->video_time_point_start,
  4264. 'video_time_point_end' => $segment->video_time_point_end
  4265. ];
  4266. }else {
  4267. $generateJson[] = [
  4268. 'sequence' => $sequence++,
  4269. 'video_url' => $segment->video_url,
  4270. 'audio_url' => $segment->audio_url,
  4271. 'video_time_point_start' => $segment->video_time_point_start,
  4272. 'video_time_point_end' => $segment->video_time_point_end
  4273. ];
  4274. }
  4275. }
  4276. // 创建任务
  4277. $now = date('Y-m-d H:i:s');
  4278. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4279. 'anime_id' => $animeId,
  4280. 'episode_id' => $episodeId,
  4281. 'generate_json' => json_encode($generateJson, 256),
  4282. 'generate_status' => '执行中',
  4283. 'complete_video_url' => '',
  4284. 'created_at' => $now,
  4285. 'updated_at' => $now
  4286. ]);
  4287. if (!$taskId) {
  4288. Utils::throwError('20003:创建任务失败');
  4289. }
  4290. // 更新剧集表的任务ID和状态
  4291. $boolen = DB::table('mp_anime_episodes')
  4292. ->where('anime_id', $animeId)
  4293. ->where('id', $episodeId)
  4294. ->update([
  4295. 'complete_video_task_id' => $taskId,
  4296. 'complete_video_task_status' => '执行中',
  4297. 'updated_at' => $now
  4298. ]);
  4299. if (!$boolen) {
  4300. Utils::throwError('20003:更新剧集表失败');
  4301. }
  4302. dLog('anime')->info('创建完整视频合成任务', [
  4303. 'task_id' => $taskId,
  4304. 'anime_id' => $animeId,
  4305. 'episode_id' => $episodeId,
  4306. 'segment_count' => count($generateJson)
  4307. ]);
  4308. // 请求远程服务器执行生成
  4309. $client = new Client(['timeout' => 600, 'verify' => false]);
  4310. try {
  4311. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4312. $response = $result->getBody()->getContents();
  4313. $response_arr = json_decode($response, true);
  4314. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4315. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4316. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4317. // // 更新任务状态为失败
  4318. // DB::table('mp_complete_video_tasks')
  4319. // ->where('id', $taskId)
  4320. // ->update([
  4321. // 'generate_status' => '执行失败',
  4322. // 'error_message' => $error_msg,
  4323. // 'updated_at' => date('Y-m-d H:i:s')
  4324. // ]);
  4325. // // 同步更新剧集表状态
  4326. // DB::table('mp_anime_episodes')
  4327. // ->where('complete_video_task_id', $taskId)
  4328. // ->update([
  4329. // 'complete_video_task_status' => '执行失败',
  4330. // 'updated_at' => date('Y-m-d H:i:s')
  4331. // ]);
  4332. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4333. }
  4334. } catch (\Exception $e) {
  4335. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4336. // 更新任务状态为失败
  4337. DB::table('mp_complete_video_tasks')
  4338. ->where('id', $taskId)
  4339. ->update([
  4340. 'generate_status' => '执行失败',
  4341. 'error_message' => $e->getMessage(),
  4342. 'updated_at' => date('Y-m-d H:i:s')
  4343. ]);
  4344. // 同步更新剧集表状态
  4345. DB::table('mp_anime_episodes')
  4346. ->where('complete_video_task_id', $taskId)
  4347. ->update([
  4348. 'complete_video_task_status' => '执行失败',
  4349. 'updated_at' => date('Y-m-d H:i:s')
  4350. ]);
  4351. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4352. }
  4353. // 开始轮询任务状态
  4354. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4355. $pollInterval = 5; // 每5秒轮询一次
  4356. $attempt = 0;
  4357. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4358. while ($attempt < $maxAttempts) {
  4359. sleep($pollInterval);
  4360. $attempt++;
  4361. // 查询任务状态
  4362. $task = DB::table('mp_complete_video_tasks')
  4363. ->where('id', $taskId)
  4364. ->first();
  4365. if (!$task) {
  4366. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4367. Utils::throwError('20003:任务不存在');
  4368. }
  4369. dLog('anime')->info('轮询任务状态', [
  4370. 'task_id' => $taskId,
  4371. 'attempt' => $attempt,
  4372. 'status' => $task->generate_status
  4373. ]);
  4374. // 检查任务是否完成
  4375. if ($task->generate_status === '执行成功') {
  4376. // 同步更新剧集表状态
  4377. $boolen3 = DB::table('mp_anime_episodes')
  4378. ->where('anime_id', $animeId)
  4379. ->where('id', $episodeId)
  4380. ->update([
  4381. 'complete_video_url' => $task->complete_video_url,
  4382. 'complete_video_task_status' => '执行成功',
  4383. 'updated_at' => date('Y-m-d H:i:s')
  4384. ]);
  4385. dLog('anime')->info('视频合成任务完成', [
  4386. 'task_id' => $taskId,
  4387. 'video_url' => $task->complete_video_url,
  4388. 'attempts' => $attempt
  4389. ]);
  4390. // 如果更新成功则远程删除之前的文件
  4391. if ($boolen3 && $completeVideoUrl) {
  4392. $encode_url = urlencode($completeVideoUrl);
  4393. $client = new Client(['timeout' => 300, 'verify' => false]);
  4394. // 根据ID通过API通知合成音频
  4395. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4396. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4397. $response = $result->getBody()->getContents();
  4398. $response_arr = json_decode($response, true);
  4399. Log::info('火山删除音频返回: '.$response);
  4400. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4401. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4402. Log::info('火山删除音频失败: '.$error_msg);
  4403. // Utils::throwError('20003:火山删除音频失败');
  4404. }
  4405. }
  4406. return [
  4407. 'task_id' => $taskId,
  4408. 'anime_id' => $animeId,
  4409. 'episode_id' => $episodeId,
  4410. 'segment_count' => count($generateJson),
  4411. 'generate_status' => '执行成功',
  4412. 'complete_video_url' => $task->complete_video_url,
  4413. ];
  4414. }
  4415. // 检查任务是否失败
  4416. if ($task->generate_status === '执行失败') {
  4417. // 同步更新剧集表状态
  4418. DB::table('mp_anime_episodes')
  4419. ->where('anime_id', $animeId)
  4420. ->where('id', $episodeId)
  4421. ->update([
  4422. 'complete_video_task_status' => '执行失败',
  4423. 'updated_at' => date('Y-m-d H:i:s')
  4424. ]);
  4425. $errorMessage = $task->error_message ?? '未知错误';
  4426. dLog('anime')->error('视频合成任务失败', [
  4427. 'task_id' => $taskId,
  4428. 'error' => $errorMessage,
  4429. 'attempts' => $attempt
  4430. ]);
  4431. return [
  4432. 'task_id' => $taskId,
  4433. 'anime_id' => $animeId,
  4434. 'episode_id' => $episodeId,
  4435. 'segment_count' => count($generateJson),
  4436. 'generate_status' => '执行失败',
  4437. 'error_message' => $errorMessage
  4438. ];
  4439. }
  4440. }
  4441. // 超时处理
  4442. dLog('anime')->warning('视频合成任务超时', [
  4443. 'task_id' => $taskId,
  4444. 'max_attempts' => $maxAttempts,
  4445. 'timeout_seconds' => $maxAttempts * $pollInterval
  4446. ]);
  4447. // 更新任务状态为超时
  4448. DB::table('mp_complete_video_tasks')
  4449. ->where('id', $taskId)
  4450. ->update([
  4451. 'generate_status' => '超时',
  4452. 'error_message' => '任务执行超时(5分钟)',
  4453. 'updated_at' => date('Y-m-d H:i:s')
  4454. ]);
  4455. return [
  4456. 'task_id' => $taskId,
  4457. 'anime_id' => $animeId,
  4458. 'episode_id' => $episodeId,
  4459. 'segment_count' => count($generateJson),
  4460. 'generate_status' => '超时',
  4461. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4462. ];
  4463. }
  4464. public function generateImg($data) {
  4465. $prompt = getProp($data, 'prompt');
  4466. $episode_id = getProp($data, 'episode_id');
  4467. $ref_img_urls = getProp($data, 'ref_img_urls');
  4468. $ratio = getProp($data, 'ratio', '9:16');
  4469. $resolution = getProp($data, 'resolution', '2k');
  4470. // 定义分辨率和宽高比对应的尺寸映射表
  4471. $sizeMap = [
  4472. '2k' => [
  4473. '1:1' => ['width' => 2048, 'height' => 2048],
  4474. '4:3' => ['width' => 2304, 'height' => 1728],
  4475. '3:4' => ['width' => 1728, 'height' => 2304],
  4476. '16:9' => ['width' => 2848, 'height' => 1600],
  4477. '9:16' => ['width' => 1600, 'height' => 2848],
  4478. '3:2' => ['width' => 2496, 'height' => 1664],
  4479. '2:3' => ['width' => 1664, 'height' => 2496],
  4480. '21:9' => ['width' => 3136, 'height' => 1344],
  4481. ],
  4482. '3k' => [
  4483. '1:1' => ['width' => 3072, 'height' => 3072],
  4484. '4:3' => ['width' => 3456, 'height' => 2592],
  4485. '3:4' => ['width' => 2592, 'height' => 3456],
  4486. '16:9' => ['width' => 4096, 'height' => 2304],
  4487. '9:16' => ['width' => 2304, 'height' => 4096],
  4488. '2:3' => ['width' => 2496, 'height' => 3744],
  4489. '3:2' => ['width' => 3744, 'height' => 2496],
  4490. '21:9' => ['width' => 4704, 'height' => 2016],
  4491. ],
  4492. '4k' => [
  4493. '1:1' => ['width' => 4096, 'height' => 4096],
  4494. '3:4' => ['width' => 3520, 'height' => 4704],
  4495. '4:3' => ['width' => 4704, 'height' => 3520],
  4496. '16:9' => ['width' => 5504, 'height' => 3040],
  4497. '9:16' => ['width' => 3040, 'height' => 5504],
  4498. '2:3' => ['width' => 3328, 'height' => 4992],
  4499. '3:2' => ['width' => 4992, 'height' => 3328],
  4500. '21:9' => ['width' => 6240, 'height' => 2656],
  4501. ],
  4502. ];
  4503. // 参数验证
  4504. $resolution = strtolower($resolution);
  4505. if (!isset($sizeMap[$resolution])) {
  4506. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  4507. }
  4508. if (!isset($sizeMap[$resolution][$ratio])) {
  4509. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  4510. }
  4511. // 根据 ratio 和 resolution 确定宽高
  4512. $width = $sizeMap[$resolution][$ratio]['width'];
  4513. $height = $sizeMap[$resolution][$ratio]['height'];
  4514. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  4515. if (is_json($ref_img_urls)) {
  4516. $ref_img_urls = json_decode($ref_img_urls, true);
  4517. }else {
  4518. $ref_img_urls = explode(',', $ref_img_urls);
  4519. }
  4520. }
  4521. // 处理图片模型
  4522. $model = getProp($data, 'model');
  4523. if (!$model) {
  4524. // 用户没有输入,从episode表获取
  4525. if ($episode_id) {
  4526. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4527. $model = getProp($episode, 'image_model');
  4528. }
  4529. if (!$model) {
  4530. // episode表也没有,使用默认值
  4531. $model = 'doubao-seedream-5-0-lite-260128';
  4532. }
  4533. }
  4534. // 验证模型是否在可用模型表中
  4535. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4536. // $model = 'doubao-seedream-5-0-lite-260128';
  4537. Utils::throwError('20003:该模型已不可用,请更换!');
  4538. }
  4539. // 保存到episode表
  4540. if ($episode_id) {
  4541. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4542. 'image_model' => $model,
  4543. 'updated_at' => date('Y-m-d H:i:s')
  4544. ]);
  4545. }
  4546. // 参数验证
  4547. if (!$prompt) Utils::throwError('20003:请提供提示词');
  4548. try {
  4549. // 创建图片生成任务
  4550. $params = [
  4551. 'prompt' => $prompt,
  4552. 'model' => $model,
  4553. 'ref_img_urls' => '',
  4554. 'width' => $width,
  4555. 'height' => $height
  4556. ];
  4557. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  4558. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4559. $task_id = $task->id;
  4560. if (!$task_id) {
  4561. Utils::throwError('20003:创建图片生成任务失败');
  4562. }
  4563. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  4564. $model = getProp($task, 'model');
  4565. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  4566. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  4567. $isSyncModel = $isVolcModel || $isGptModel;
  4568. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  4569. $start_time = time();
  4570. $timeout = 300; // 5分钟
  4571. $img_url = '';
  4572. while (time() - $start_time < $timeout) {
  4573. sleep(3);
  4574. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  4575. if ($isSyncModel) {
  4576. // 刷新任务状态
  4577. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4578. if ($task->status === 'success' && $task->result_url) {
  4579. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  4580. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  4581. break;
  4582. } elseif ($task->status === 'failed') {
  4583. $errorMsg = mapErrorMessage($task->error_message ?? '');
  4584. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4585. }
  4586. // // 如果还在处理中,提示用户稍后查看
  4587. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  4588. }else {
  4589. $task = MpGeneratePicTask::where('id', $task_id)->first();
  4590. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  4591. if ($statusInfo['status'] === 'success') {
  4592. $task->updateStatus('success', [
  4593. 'result_url' => $statusInfo['result_url'],
  4594. 'result_json' => $statusInfo['result_json'] ?? []
  4595. ]);
  4596. $img_url = $statusInfo['result_url'][0];
  4597. break;
  4598. } elseif ($statusInfo['status'] === 'failed') {
  4599. $task->updateStatus('failed', [
  4600. 'error_message' => $statusInfo['error_message'],
  4601. 'result_json' => $statusInfo['result_json'] ?? []
  4602. ]);
  4603. dLog('anime')->error('图片生成失败,', [
  4604. 'error' => $statusInfo['error_message'] ?? '未知错误'
  4605. ]);
  4606. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  4607. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  4608. }
  4609. }
  4610. }
  4611. if (empty($img_url)) {
  4612. Utils::throwError('20003:图片生成超时,请稍后重试');
  4613. }
  4614. return $img_url;
  4615. } catch (\Exception $e) {
  4616. dLog('anime')->error('更新角色或场景失败', [
  4617. 'error' => $e->getMessage()
  4618. ]);
  4619. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  4620. Utils::throwError('20003:' . $e->getMessage());
  4621. }
  4622. }
  4623. /**
  4624. * 使用文生文模型解析分镜内容
  4625. */
  4626. private function parseSegmentContentWithAI($segment_content) {
  4627. try {
  4628. // 使用DeepSeek服务的公开方法解析分镜内容
  4629. return $this->DeepSeekService->parseSegmentContent($segment_content);
  4630. } catch (\Exception $e) {
  4631. // 如果AI解析失败,记录日志并返回原内容
  4632. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  4633. return $segment_content;
  4634. }
  4635. }
  4636. /**
  4637. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  4638. *
  4639. * @param int $episode_id 分集ID
  4640. * @param int $anime_id 动漫ID
  4641. * @param array $roles 分集角色数组(引用传递)
  4642. * @param array $scenes 分集场景数组(引用传递)
  4643. * @param array $episode 分集数据
  4644. */
  4645. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  4646. // 获取全局动漫的角色和场景数据
  4647. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4648. if (!$anime) return;
  4649. $art_style_type = getProp($anime, 'art_style_type');
  4650. $character_prefix = '';
  4651. $scene_prefix = '';
  4652. if ($art_style_type) {
  4653. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  4654. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  4655. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  4656. }
  4657. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  4658. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  4659. $roles_updated = false;
  4660. $scenes_updated = false;
  4661. // 处理角色
  4662. foreach ($roles as &$role) {
  4663. $role_name = getProp($role, 'role');
  4664. $role_description = getProp($role, 'description');
  4665. $role_pic_prompt = getProp($role, 'pic_prompt');
  4666. $role_url = getProp($role, 'url');
  4667. $role_task_id = getProp($role, 'task_id');
  4668. // 如果已有URL或已有任务ID,跳过
  4669. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  4670. continue;
  4671. }
  4672. $url_inherited = false;
  4673. // 尝试从全局数据中继承
  4674. foreach ($global_roles as $global_role) {
  4675. $global_role_name = getProp($global_role, 'role');
  4676. $global_role_description = getProp($global_role, 'description');
  4677. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  4678. $global_role_url = getProp($global_role, 'url');
  4679. $global_role_task_id = getProp($global_role, 'task_id');
  4680. $global_role_task_status = getProp($global_role, 'task_status');
  4681. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  4682. if ($role_name === $global_role_name
  4683. && $role_description === $global_role_description
  4684. && $role_pic_prompt === $global_role_pic_prompt
  4685. && !empty($global_role_url)) {
  4686. // 继承 task_id、task_status 和 url
  4687. $role['task_id'] = $global_role_task_id;
  4688. $role['task_status'] = $global_role_task_status;
  4689. $role['url'] = $global_role_url;
  4690. $roles_updated = true;
  4691. $url_inherited = true;
  4692. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  4693. break;
  4694. }
  4695. }
  4696. // 如果无法继承且没有任务ID,创建新任务
  4697. if (!$url_inherited && empty($role_task_id)) {
  4698. try {
  4699. $art_style = getProp($episode, 'art_style');
  4700. // 优先使用 pic_prompt,如果没有则使用 description
  4701. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  4702. // if ($art_style) {
  4703. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4704. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  4705. // }
  4706. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  4707. $params = [
  4708. 'prompt' => $description,
  4709. 'ref_img_urls' => []
  4710. ];
  4711. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4712. $task_id = $task->id;
  4713. if ($task_id) {
  4714. $role['task_id'] = $task_id;
  4715. $role['task_status'] = 'processing';
  4716. $roles_updated = true;
  4717. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  4718. }
  4719. } catch (\Exception $e) {
  4720. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  4721. }
  4722. }
  4723. }
  4724. // 处理场景
  4725. foreach ($scenes as &$scene) {
  4726. $scene_name = getProp($scene, 'scene');
  4727. $scene_description = getProp($scene, 'description');
  4728. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  4729. $scene_url = getProp($scene, 'url');
  4730. $scene_task_id = getProp($scene, 'task_id');
  4731. // 如果已有URL或已有任务ID,跳过
  4732. if (!empty($scene_url) || !empty($scene_task_id)) {
  4733. continue;
  4734. }
  4735. $url_inherited = false;
  4736. // 尝试从全局数据中继承
  4737. foreach ($global_scenes as $global_scene) {
  4738. $global_scene_name = getProp($global_scene, 'scene');
  4739. $global_scene_description = getProp($global_scene, 'description');
  4740. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  4741. $global_scene_url = getProp($global_scene, 'url');
  4742. $global_scene_task_id = getProp($global_scene, 'task_id');
  4743. $global_scene_task_status = getProp($global_scene, 'task_status');
  4744. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  4745. if ($scene_name === $global_scene_name
  4746. && $scene_description === $global_scene_description
  4747. && $scene_pic_prompt === $global_scene_pic_prompt
  4748. && !empty($global_scene_url)) {
  4749. // 继承 task_id、task_status 和 url
  4750. $scene['task_id'] = $global_scene_task_id;
  4751. $scene['task_status'] = $global_scene_task_status;
  4752. $scene['url'] = $global_scene_url;
  4753. $scenes_updated = true;
  4754. $url_inherited = true;
  4755. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  4756. break;
  4757. }
  4758. }
  4759. // 如果无法继承且没有任务ID,创建新任务
  4760. if (!$url_inherited && empty($scene_task_id)) {
  4761. try {
  4762. $art_style = getProp($episode, 'art_style');
  4763. // 优先使用 pic_prompt,如果没有则使用 description
  4764. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  4765. // if ($art_style) {
  4766. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  4767. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  4768. // }
  4769. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  4770. $params = [
  4771. 'prompt' => $description,
  4772. 'ref_img_urls' => []
  4773. ];
  4774. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4775. $task_id = $task->id;
  4776. if ($task_id) {
  4777. $scene['task_id'] = $task_id;
  4778. $scene['task_status'] = 'processing';
  4779. $scenes_updated = true;
  4780. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  4781. }
  4782. } catch (\Exception $e) {
  4783. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  4784. }
  4785. }
  4786. }
  4787. // 如果有更新,保存到数据库
  4788. if ($roles_updated || $scenes_updated) {
  4789. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  4790. if ($roles_updated) {
  4791. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  4792. }
  4793. if ($scenes_updated) {
  4794. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  4795. }
  4796. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  4797. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  4798. }
  4799. }
  4800. /**
  4801. * 根据图片URL使用AI反推图片提示词
  4802. *
  4803. * @param string $img_url 图片URL
  4804. * @return string 反推的提示词
  4805. */
  4806. private function generateImagePromptFromUrl($img_url) {
  4807. try {
  4808. // 获取默认模型
  4809. $model = 'doubao-seed-2-0-mini-260215';
  4810. // 构建messages参数
  4811. $messages = [
  4812. [
  4813. 'role' => 'user',
  4814. 'content' => [
  4815. [
  4816. 'type' => 'text',
  4817. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  4818. ],
  4819. [
  4820. 'type' => 'image_url',
  4821. 'image_url' => [
  4822. 'url' => $img_url
  4823. ]
  4824. ]
  4825. ]
  4826. ]
  4827. ];
  4828. // 构建请求参数
  4829. $params = [
  4830. 'model' => $model,
  4831. 'messages' => $messages,
  4832. 'stream' => false,
  4833. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  4834. ];
  4835. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  4836. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  4837. // 返回生成的内容
  4838. return getProp($result, 'fullContent', '图片描述生成失败');
  4839. } catch (\Exception $e) {
  4840. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  4841. 'img_url' => $img_url
  4842. ]);
  4843. logDB('anime', 'error', 'AI反推图片提示词失败', [
  4844. 'error' => $e->getMessage(),
  4845. 'img_url' => $img_url
  4846. ]);
  4847. return '图片描述生成失败: ' . $e->getMessage();
  4848. }
  4849. }
  4850. /**
  4851. * 音频试听接口
  4852. * 创建音频任务并轮询获取结果
  4853. *
  4854. * @param array $data 参数数组
  4855. * @return array 返回音频URL或错误信息
  4856. */
  4857. public function previewAudio($data) {
  4858. $dialogue = getProp($data, 'dialogue');
  4859. // 必填参数验证
  4860. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  4861. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  4862. $voice_type = getProp($data, 'voice_type');
  4863. $voice_name = getProp($data, 'voice_name');
  4864. $voice_actor = getProp($data, 'voice_actor');
  4865. $emotion_type = getProp($data, 'emotion_type');
  4866. $gender = getProp($data, 'gender', 0);
  4867. $emotion = getProp($data, 'emotion');
  4868. $speed_ratio = getProp($data, 'speed_ratio', 0);
  4869. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  4870. $emotion_scale = getProp($data, 'emotion_scale', 0);
  4871. $pitch = getProp($data, 'pitch', 0);
  4872. try {
  4873. $now = date('Y-m-d H:i:s');
  4874. // 构建生成参数
  4875. $generate_json = json_encode([
  4876. 'text' => $dialogue,
  4877. 'role' => $voice_actor,
  4878. 'voice_type' => $voice_type,
  4879. 'voice_name' => $voice_name,
  4880. 'emotion' => $emotion,
  4881. 'emotion_type' => $emotion_type,
  4882. 'gender' => $gender,
  4883. 'speed_ratio' => $speed_ratio,
  4884. 'loudness_ratio' => $loudness_ratio,
  4885. 'emotion_scale' => $emotion_scale,
  4886. 'pitch' => $pitch,
  4887. ], 256);
  4888. // 请求远程服务器执行生成
  4889. $client = new Client(['timeout' => 600, 'verify' => false]);
  4890. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  4891. $response = $result->getBody()->getContents();
  4892. $response_arr = json_decode($response, true);
  4893. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4894. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4895. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  4896. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  4897. }
  4898. $arr = $response_arr['data'];
  4899. $subtitle_info = $arr['subtitle_info'];
  4900. $audio_duration = json_decode($subtitle_info, true)['duration'];
  4901. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  4902. return [
  4903. 'audio_url' => $arr['url'],
  4904. 'subtitle_info' => $subtitle_info,
  4905. 'audio_duration' => round($audio_duration, 2)
  4906. ];
  4907. } catch (\Exception $e) {
  4908. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  4909. Utils::throwError('20003:' . $e->getMessage());
  4910. }
  4911. }
  4912. /**
  4913. * 获取角色库列表(支持文件夹递归查询)
  4914. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)
  4915. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  4916. */
  4917. public function globalProducts($data) {
  4918. $uid = Site::getUid();
  4919. $cpid = Site::getCpid();
  4920. $id = getProp($data, 'id', 0);
  4921. $parent_id = getProp($data, 'parent_id', 0);
  4922. $product_name = getProp($data, 'product_name');
  4923. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  4924. if (!$product) {
  4925. Utils::throwError('20003:请选择产品类型');
  4926. }
  4927. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  4928. if ($id || $product_name) {
  4929. $query = DB::table('mp_products')
  4930. ->where('cpid', $cpid)
  4931. ->where('user_id', $uid)
  4932. ->where('is_deleted', 0);
  4933. // 如果指定了 id,按 id 精确查询
  4934. if ($id) {
  4935. $query->where('id', $id);
  4936. }
  4937. // 如果指定了 product_name,按名称模糊查询
  4938. if ($product_name) {
  4939. $query->where('product_name', 'like', "%{$product_name}%");
  4940. }
  4941. // 如果指定了 product,添加筛选条件
  4942. if ($product) {
  4943. $query->where('product', $product);
  4944. }
  4945. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'created_at')
  4946. ->orderByRaw('sort_order DESC, created_at DESC')
  4947. ->get()
  4948. ->map(function($value) {
  4949. $value = (array)$value;
  4950. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  4951. $value['type'] = (int)$value['type'];
  4952. $value['parent_id'] = (int)$value['parent_id'];
  4953. $value['level'] = (int)$value['level'];
  4954. $value['product'] = (int)($value['product'] ?? 1);
  4955. $value['versions'] = json_decode($value['versions'], true) ?: [];
  4956. return $value;
  4957. })
  4958. ->toArray();
  4959. return $result;
  4960. }
  4961. // 递归获取所有子目录和角色
  4962. return $this->getChildrenRecursive($cpid, $parent_id, $product, $uid);
  4963. }
  4964. /**
  4965. * 递归获取指定目录下的所有子目录和角色
  4966. * @param int $cpid 公司ID
  4967. * @param int $parent_id 父目录ID
  4968. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  4969. * @param int $uid 用户ID
  4970. * @return array
  4971. */
  4972. private function getChildrenRecursive($cpid, $parent_id, $product = null, $uid = null) {
  4973. // 查询当前层级的所有项(文件夹和角色)
  4974. $query = DB::table('mp_products')
  4975. ->where('cpid', $cpid)
  4976. ->where('is_deleted', 0)
  4977. ->where('parent_id', $parent_id);
  4978. // 添加用户ID验证
  4979. if ($uid) {
  4980. $query->where('user_id', $uid);
  4981. }
  4982. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  4983. if ($product) {
  4984. $query->where('product', $product);
  4985. }
  4986. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'created_at')
  4987. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  4988. ->get();
  4989. $result = [];
  4990. foreach ($items as $item) {
  4991. $itemArray = [
  4992. 'id' => $item->id,
  4993. 'type' => (int)$item->type,
  4994. 'parent_id' => (int)$item->parent_id,
  4995. 'level' => (int)$item->level,
  4996. 'product_name' => $item->product_name,
  4997. 'url' => $item->url,
  4998. 'pic_prompt' => $item->pic_prompt ?? '',
  4999. 'three_view_image_url' => $item->three_view_image_url,
  5000. 'product' => (int)($item->product ?? 1),
  5001. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5002. ];
  5003. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5004. // 如果是文件夹,递归获取其子项
  5005. if ($item->type == 2) {
  5006. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $uid);
  5007. if (!empty($children)) {
  5008. $itemArray['children'] = $children;
  5009. }
  5010. }
  5011. $result[] = $itemArray;
  5012. }
  5013. return $result;
  5014. }
  5015. /**
  5016. * 创建文件夹
  5017. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5018. * @return int 返回新建文件夹ID
  5019. */
  5020. public function createFolder($data) {
  5021. $uid = Site::getUid();
  5022. $cpid = Site::getCpid();
  5023. $parent_id = getProp($data, 'parent_id', 0);
  5024. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5025. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5026. $product = getProp($data, 'product');
  5027. if (!in_array($product, [1, 2, 3])) {
  5028. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5029. }
  5030. // 验证父文件夹
  5031. $parent_level = 0;
  5032. if ($parent_id > 0) {
  5033. $parent = DB::table('mp_products')
  5034. ->where('id', $parent_id)
  5035. ->where('type', 2)
  5036. ->where('is_deleted', 0)
  5037. ->first();
  5038. if (!$parent) {
  5039. Utils::throwError('20003:父文件夹不存在');
  5040. }
  5041. // 检查父文件夹的 product 类型是否一致
  5042. if ($parent->product != $product) {
  5043. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5044. }
  5045. $parent_level = $parent->level;
  5046. // 检查层级限制(最多3层)
  5047. if ($parent_level >= 3) {
  5048. Utils::throwError('20003:文件夹层级不能超过3层');
  5049. }
  5050. }
  5051. // 检查当前目录下是否已存在空白文件夹
  5052. $empty_folder_exists = DB::table('mp_products')
  5053. ->where('parent_id', $parent_id)
  5054. ->where('type', 2)
  5055. ->where('product', $product)
  5056. ->where('product_name', '新建文件夹')
  5057. ->where('is_deleted', 0)
  5058. ->exists();
  5059. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5060. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5061. }
  5062. // 创建文件夹
  5063. $folder_id = DB::table('mp_products')->insertGetId([
  5064. 'user_id' => $uid,
  5065. 'cpid' => $cpid,
  5066. 'type' => 2,
  5067. 'parent_id' => $parent_id,
  5068. 'level' => $parent_level + 1,
  5069. 'product_name' => $folder_name,
  5070. 'product' => $product,
  5071. 'sort_order' => time(), // 使用时间戳作为排序权重
  5072. 'is_deleted' => 0,
  5073. 'created_at' => date('Y-m-d H:i:s'),
  5074. 'updated_at' => date('Y-m-d H:i:s')
  5075. ]);
  5076. return [
  5077. 'id' => $folder_id,
  5078. 'type' => 2,
  5079. 'parent_id' => $parent_id,
  5080. 'level' => $parent_level + 1,
  5081. 'product_name' => $folder_name,
  5082. 'product' => $product,
  5083. ];
  5084. }
  5085. /**
  5086. * 重命名文件夹或角色
  5087. * @param array $data 包含 id、product_name(新名称)
  5088. * @return bool
  5089. */
  5090. public function renameFolder($data) {
  5091. $uid = Site::getUid();
  5092. $cpid = Site::getCpid();
  5093. $id = getProp($data, 'id');
  5094. $new_name = getProp($data, 'product_name');
  5095. if (!$id || !$new_name) {
  5096. Utils::throwError('20003:参数不完整');
  5097. }
  5098. // 检查是否存在
  5099. $item = DB::table('mp_products')
  5100. ->where('id', $id)
  5101. ->where('cpid', $cpid)
  5102. ->where('is_deleted', 0)
  5103. ->first();
  5104. if (!$item) {
  5105. Utils::throwError('20003:项目不存在');
  5106. }
  5107. return DB::table('mp_products')
  5108. ->where('id', $id)
  5109. ->where('cpid', $cpid)
  5110. ->update([
  5111. 'product_name' => $new_name,
  5112. 'updated_at' => date('Y-m-d H:i:s')
  5113. ]);
  5114. }
  5115. /**
  5116. * 移动角色或文件夹到指定文件夹
  5117. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5118. * @return bool
  5119. */
  5120. public function moveProductOrFolder($data) {
  5121. $cpid = Site::getCpid();
  5122. $id = getProp($data, 'id');
  5123. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5124. if (!$id) {
  5125. Utils::throwError('20003:请选择要移动的项目');
  5126. }
  5127. // 检查要移动的项目
  5128. $item = DB::table('mp_products')
  5129. ->where('id', $id)
  5130. ->where('cpid', $cpid)
  5131. ->where('is_deleted', 0)
  5132. ->first();
  5133. if (!$item) {
  5134. Utils::throwError('20003:项目不存在');
  5135. }
  5136. // 验证目标文件夹
  5137. $target_level = 0;
  5138. $target_product = $item->product; // 默认使用当前项目的 product
  5139. if ($target_parent_id > 0) {
  5140. $target_parent = DB::table('mp_products')
  5141. ->where('id', $target_parent_id)
  5142. ->where('cpid', $cpid)
  5143. ->where('type', 2)
  5144. ->where('is_deleted', 0)
  5145. ->first();
  5146. if (!$target_parent) {
  5147. Utils::throwError('20003:目标文件夹不存在');
  5148. }
  5149. // 检查 product 类型是否一致
  5150. if ($target_parent->product != $item->product) {
  5151. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5152. }
  5153. $target_level = $target_parent->level;
  5154. $target_product = $target_parent->product;
  5155. // 如果移动的是文件夹,需要检查层级
  5156. if ($item->type == 2) {
  5157. // 计算移动后的最大层级
  5158. $max_child_level = $this->getMaxChildLevel($id);
  5159. $depth = $max_child_level - $item->level;
  5160. if ($target_level + 1 + $depth > 3) {
  5161. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5162. }
  5163. // 不能移动到自己或自己的子文件夹下
  5164. if ($this->isDescendant($target_parent_id, $id)) {
  5165. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5166. }
  5167. }
  5168. }
  5169. // 更新父文件夹和层级
  5170. $new_level = $target_level + 1;
  5171. DB::table('mp_products')
  5172. ->where('id', $id)
  5173. ->update([
  5174. 'parent_id' => $target_parent_id,
  5175. 'level' => $new_level,
  5176. 'updated_at' => date('Y-m-d H:i:s')
  5177. ]);
  5178. // 如果是文件夹,需要递归更新所有子项的层级
  5179. if ($item->type == 2) {
  5180. $this->updateChildrenLevel($id, $new_level);
  5181. }
  5182. return true;
  5183. }
  5184. /**
  5185. * 获取文件夹下最大子层级
  5186. * @param int $folder_id
  5187. * @return int
  5188. */
  5189. private function getMaxChildLevel($folder_id) {
  5190. $max_level = DB::table('mp_products')
  5191. ->where('parent_id', $folder_id)
  5192. ->where('is_deleted', 0)
  5193. ->max('level');
  5194. if (!$max_level) {
  5195. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5196. }
  5197. // 递归查找子文件夹
  5198. $children = DB::table('mp_products')
  5199. ->where('parent_id', $folder_id)
  5200. ->where('type', 2)
  5201. ->where('is_deleted', 0)
  5202. ->pluck('id');
  5203. foreach ($children as $child_id) {
  5204. $child_max = $this->getMaxChildLevel($child_id);
  5205. if ($child_max > $max_level) {
  5206. $max_level = $child_max;
  5207. }
  5208. }
  5209. return $max_level;
  5210. }
  5211. /**
  5212. * 检查 target_id 是否是 folder_id 的后代
  5213. * @param int $target_id
  5214. * @param int $folder_id
  5215. * @return bool
  5216. */
  5217. private function isDescendant($target_id, $folder_id) {
  5218. if ($target_id == $folder_id) {
  5219. return true;
  5220. }
  5221. $parent = DB::table('mp_products')
  5222. ->where('id', $target_id)
  5223. ->where('is_deleted', 0)
  5224. ->first();
  5225. if (!$parent || $parent->parent_id == 0) {
  5226. return false;
  5227. }
  5228. return $this->isDescendant($parent->parent_id, $folder_id);
  5229. }
  5230. /**
  5231. * 递归更新子项层级
  5232. * @param int $parent_id
  5233. * @param int $parent_level
  5234. */
  5235. private function updateChildrenLevel($parent_id, $parent_level) {
  5236. $children = DB::table('mp_products')
  5237. ->where('parent_id', $parent_id)
  5238. ->where('is_deleted', 0)
  5239. ->get();
  5240. foreach ($children as $child) {
  5241. $new_level = $parent_level + 1;
  5242. DB::table('mp_products')
  5243. ->where('id', $child->id)
  5244. ->update([
  5245. 'level' => $new_level,
  5246. 'updated_at' => date('Y-m-d H:i:s')
  5247. ]);
  5248. // 如果是文件夹,继续递归
  5249. if ($child->type == 2) {
  5250. $this->updateChildrenLevel($child->id, $new_level);
  5251. }
  5252. }
  5253. }
  5254. /**
  5255. * 获取文件夹路径(面包屑导航)
  5256. * @param array $data 包含 folder_id
  5257. * @return array 返回路径数组
  5258. */
  5259. public function getFolderPath($data) {
  5260. $folder_id = getProp($data, 'id', 0);
  5261. if ($folder_id == 0) {
  5262. return [
  5263. ['id' => 0, 'name' => '根目录']
  5264. ];
  5265. }
  5266. $path = [];
  5267. $current_id = $folder_id;
  5268. while ($current_id > 0) {
  5269. $folder = DB::table('mp_products')
  5270. ->where('id', $current_id)
  5271. ->where('type', 2)
  5272. ->where('is_deleted', 0)
  5273. ->first();
  5274. if (!$folder) {
  5275. break;
  5276. }
  5277. array_unshift($path, [
  5278. 'id' => $folder->id,
  5279. 'name' => $folder->product_name
  5280. ]);
  5281. $current_id = $folder->parent_id;
  5282. }
  5283. // 添加根目录
  5284. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5285. return $path;
  5286. }
  5287. public function createProduct($data) {
  5288. $uid = Site::getUid();
  5289. $cpid = Site::getCpid();
  5290. $product_name = trim(getProp($data, 'product_name'));
  5291. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5292. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5293. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5294. $url = trim(getProp($data, 'url'));
  5295. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5296. $versions = getProp($data, 'versions');
  5297. // 检查是否是正确的图片格式
  5298. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5299. $urlPath = parse_url($url, PHP_URL_PATH);
  5300. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5301. if (!in_array($extension, $allowedExtensions)) {
  5302. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5303. }
  5304. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5305. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5306. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5307. $product = getProp($data, 'product');
  5308. if (!in_array($product, [1, 2, 3])) {
  5309. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5310. }
  5311. // 获取父文件夹ID和层级
  5312. $parent_id = getProp($data, 'parent_id', 0);
  5313. $parent_level = 0;
  5314. if ($parent_id > 0) {
  5315. $parent = DB::table('mp_products')
  5316. ->where('id', $parent_id)
  5317. ->where('cpid', $cpid)
  5318. ->where('type', 2)
  5319. ->where('is_deleted', 0)
  5320. ->first();
  5321. if (!$parent) {
  5322. Utils::throwError('20003:父文件夹不存在');
  5323. }
  5324. $parent_level = $parent->level;
  5325. }
  5326. $id = DB::table('mp_products')->insertGetId([
  5327. 'user_id' => $uid,
  5328. 'cpid' => $cpid,
  5329. 'type' => 1, // 1=角色图片
  5330. 'parent_id' => $parent_id,
  5331. 'level' => $parent_level + 1,
  5332. 'product_name' => $product_name,
  5333. 'url' => $url,
  5334. 'pic_prompt' => $pic_prompt,
  5335. 'product' => $product,
  5336. 'versions' => json_encode($versions, 256),
  5337. 'sort_order' => time(), // 使用时间戳作为排序权重
  5338. 'created_at' => date('Y-m-d H:i:s'),
  5339. 'updated_at' => date('Y-m-d H:i:s')
  5340. ]);
  5341. if (!$id) Utils::throwError('20003:创建失败');
  5342. return [
  5343. 'id' => $id,
  5344. 'type' => 1,
  5345. 'parent_id' => $parent_id,
  5346. 'level' => $parent_level + 1,
  5347. 'product_name' => $product_name,
  5348. 'url' => $url,
  5349. 'pic_prompt' => $pic_prompt,
  5350. 'product' => $product,
  5351. 'versions' => $versions
  5352. ];
  5353. }
  5354. public function editProduct($data) {
  5355. $uid = Site::getUid();
  5356. $cpid = Site::getCpid();
  5357. $id = getProp($data, 'id');
  5358. if (!$id) Utils::throwError('20003:ID不能为空');
  5359. $versions = getProp($data, 'versions');
  5360. // 检查是否存在且属于当前用户
  5361. $role = DB::table('mp_products')
  5362. ->where('id', $id)
  5363. ->where('cpid', $cpid)
  5364. ->where('type', 1)->first();
  5365. if (!$role) Utils::throwError('20003:记录不存在');
  5366. $updateData = [];
  5367. // $needVersionRecord = false; // 是否需要记录版本
  5368. // 名称
  5369. $product_name = trim(getProp($data, 'product_name'));
  5370. if ($product_name) {
  5371. $updateData['product_name'] = $product_name;
  5372. }
  5373. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5374. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  5375. // 图片地址
  5376. $url = trim(getProp($data, 'url'));
  5377. if ($url) {
  5378. // 检查是否是正确的图片格式
  5379. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5380. $urlPath = parse_url($url, PHP_URL_PATH);
  5381. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5382. if (!in_array($extension, $allowedExtensions)) {
  5383. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5384. }
  5385. // // 如果 url 有变更,记录版本
  5386. // if ($url !== $role->url) {
  5387. // $needVersionRecord = true;
  5388. // }
  5389. $updateData['url'] = $url;
  5390. }
  5391. // 提示词
  5392. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5393. if ($pic_prompt) {
  5394. // // 如果 pic_prompt 有变更,记录版本
  5395. // if ($pic_prompt !== $role->pic_prompt) {
  5396. // $needVersionRecord = true;
  5397. // }
  5398. $updateData['pic_prompt'] = $pic_prompt;
  5399. }
  5400. if (empty($updateData)) {
  5401. Utils::throwError('20003:没有需要更新的数据');
  5402. }
  5403. // // 如果需要记录版本,将数据添加到 versions 数组
  5404. // if ($needVersionRecord) {
  5405. // // 获取现有的 versions 数据
  5406. // $versions = json_decode($role->versions, true) ?: [];
  5407. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  5408. // // 如果是第一次记录版本,先添加旧版本(变更前)
  5409. // if ($isFirstVersion) {
  5410. // $oldVersion = [
  5411. // 'url' => $role->url,
  5412. // 'description' => $role->pic_prompt,
  5413. // ];
  5414. // // 旧版本添加到数组末尾
  5415. // $versions[] = $oldVersion;
  5416. // }
  5417. // // 构建新版本(变更后)
  5418. // $newVersion = [
  5419. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  5420. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  5421. // ];
  5422. // // 检查新版本是否已存在于历史版本中
  5423. // $existingIndex = -1;
  5424. // foreach ($versions as $index => $version) {
  5425. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  5426. // $existingIndex = $index;
  5427. // break;
  5428. // }
  5429. // }
  5430. // if ($existingIndex !== -1) {
  5431. // // 如果已存在,移除旧的位置
  5432. // array_splice($versions, $existingIndex, 1);
  5433. // }
  5434. // // 新版本添加到数组开头(最新的在前)
  5435. // array_unshift($versions, $newVersion);
  5436. // // // 限制版本数量(可选,例如只保留最近10个版本)
  5437. // // if (count($versions) > 10) {
  5438. // // $versions = array_slice($versions, 0, 10);
  5439. // // }
  5440. // $updateData['versions'] = json_encode($versions, 256);
  5441. // }
  5442. if ($versions) {
  5443. $updateData['versions'] = json_encode($versions, 256);
  5444. }
  5445. $updateData['updated_at'] = date('Y-m-d H:i:s');
  5446. return DB::table('mp_products')
  5447. ->where('cpid', $cpid)
  5448. ->where('id', $id)->update($updateData);
  5449. }
  5450. /**
  5451. * 获取角色版本历史
  5452. * @param array $data 包含 id(角色ID)
  5453. * @return array 返回版本历史列表
  5454. */
  5455. public function getProductVersions($data) {
  5456. $cpid = Site::getCpid();
  5457. $id = getProp($data, 'id');
  5458. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5459. $role = DB::table('mp_products')
  5460. ->where('id', $id)
  5461. ->where('cpid', $cpid)
  5462. ->where('type', 1)
  5463. ->first();
  5464. if (!$role) Utils::throwError('20003:角色不存在');
  5465. // 获取版本历史
  5466. $versions = json_decode($role->versions, true) ?: [];
  5467. // 添加当前版本作为最新版本
  5468. $currentVersion = [
  5469. 'version' => 0, // 0 表示当前版本
  5470. 'url' => $role->url,
  5471. 'pic_prompt' => $role->pic_prompt,
  5472. 'updated_at' => $role->updated_at,
  5473. 'is_current' => true
  5474. ];
  5475. array_unshift($versions, $currentVersion);
  5476. return $versions;
  5477. }
  5478. /**
  5479. * 恢复到指定版本
  5480. * @param array $data 包含 id(角色ID)、version(版本号)
  5481. * @return bool
  5482. */
  5483. public function restoreProductVersion($data) {
  5484. $uid = Site::getUid();
  5485. $cpid = Site::getCpid();
  5486. $id = getProp($data, 'id');
  5487. $version = getProp($data, 'version');
  5488. if (!$id) Utils::throwError('20003:角色ID不能为空');
  5489. if (!$version) Utils::throwError('20003:版本号不能为空');
  5490. $role = DB::table('mp_products')
  5491. ->where('id', $id)
  5492. ->where('cpid', $cpid)
  5493. ->where('type', 1)
  5494. ->first();
  5495. if (!$role) Utils::throwError('20003:角色不存在');
  5496. // 获取版本历史
  5497. $versions = json_decode($role->versions, true) ?: [];
  5498. // 查找指定版本
  5499. $targetVersion = null;
  5500. foreach ($versions as $v) {
  5501. if ($v['version'] == $version) {
  5502. $targetVersion = $v;
  5503. break;
  5504. }
  5505. }
  5506. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  5507. // 先将当前版本保存到历史
  5508. $newVersion = [
  5509. 'version' => count($versions) + 1,
  5510. 'url' => $role->url,
  5511. 'pic_prompt' => $role->pic_prompt,
  5512. 'updated_at' => date('Y-m-d H:i:s'),
  5513. 'updated_by' => $uid
  5514. ];
  5515. array_unshift($versions, $newVersion);
  5516. // 限制版本数量
  5517. if (count($versions) > 10) {
  5518. $versions = array_slice($versions, 0, 10);
  5519. }
  5520. // 恢复到指定版本
  5521. return DB::table('mp_products')
  5522. ->where('id', $id)
  5523. ->where('cpid', $cpid)
  5524. ->update([
  5525. 'url' => $targetVersion['url'],
  5526. 'pic_prompt' => $targetVersion['pic_prompt'],
  5527. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  5528. 'updated_at' => date('Y-m-d H:i:s')
  5529. ]);
  5530. }
  5531. public function deleteProduct($data) {
  5532. $uid = Site::getUid();
  5533. $cpid = Site::getCpid();
  5534. $id = getProp($data, 'id');
  5535. if (!$id) Utils::throwError('20003:ID不能为空');
  5536. $ids = explode(',', $id);
  5537. // 检查是否存在且属于当前用户
  5538. $role = DB::table('mp_products')
  5539. ->whereIn('id', $ids)
  5540. ->where('cpid', $cpid)
  5541. ->get();
  5542. if (!$role) Utils::throwError('20003:记录不存在');
  5543. return DB::table('mp_products')
  5544. ->where('cpid', $cpid)
  5545. ->whereIn('id', $ids)
  5546. ->update([
  5547. 'is_deleted' => 1,
  5548. 'updated_at' => date('Y-m-d H:i:s')
  5549. ]);
  5550. }
  5551. public function generateThreeView($data) {
  5552. $uid = Site::getUid();
  5553. $cpid = Site::getCpid();
  5554. $id = getProp($data, 'id');
  5555. if (!$id) Utils::throwError('20003:ID不能为空');
  5556. // 检查是否存在且属于当前用户
  5557. $role = DB::table('mp_products')
  5558. ->where('id', $id)
  5559. ->where('cpid', $cpid)
  5560. ->where('type', 1)->first();
  5561. if (!$role) Utils::throwError('20003:记录不存在');
  5562. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  5563. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  5564. if (!$ref_img_url) {
  5565. // 如果没有传入参考图,使用角色表中的图片
  5566. $ref_img_url = $role->url ?? '';
  5567. if (!$ref_img_url) {
  5568. Utils::throwError('20003:参考图不能为空');
  5569. }
  5570. }
  5571. // 检查参考图是否是正确的图片格式
  5572. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5573. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  5574. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5575. if (!in_array($extension, $allowedExtensions)) {
  5576. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5577. }
  5578. // 处理图片模型
  5579. $model = getProp($data, 'model');
  5580. if (!$model) {
  5581. // 使用默认模型
  5582. $model = 'doubao-seedream-5-0-lite-260128';
  5583. }
  5584. // 验证模型是否在可用模型表中
  5585. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5586. Utils::throwError('20003:该模型已不可用,请更换!');
  5587. }
  5588. try {
  5589. // 创建图片生成任务
  5590. $params = [
  5591. 'prompt' => $prompt,
  5592. 'model' => $model,
  5593. 'ref_img_urls' => [$ref_img_url],
  5594. 'width' => 1600,
  5595. 'height' => 2848
  5596. ];
  5597. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5598. $task_id = $task->id;
  5599. if (!$task_id) {
  5600. Utils::throwError('20003:创建图片生成任务失败');
  5601. }
  5602. // 检查任务模型类型
  5603. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5604. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5605. $isSyncModel = $isVolcModel || $isGptModel;
  5606. // 轮询获取结果(5分钟超时,每3秒查询一次)
  5607. $start_time = time();
  5608. $timeout = 300; // 5分钟
  5609. $img_url = '';
  5610. while (time() - $start_time < $timeout) {
  5611. sleep(3);
  5612. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5613. if ($isSyncModel) {
  5614. // 刷新任务状态
  5615. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5616. if ($task->status === 'success' && $task->result_url) {
  5617. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  5618. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  5619. break;
  5620. } elseif ($task->status === 'failed') {
  5621. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  5622. }
  5623. } else {
  5624. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5625. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5626. if ($statusInfo['status'] === 'success') {
  5627. $task->updateStatus('success', [
  5628. 'result_url' => $statusInfo['result_url'],
  5629. 'result_json' => $statusInfo['result_json'] ?? []
  5630. ]);
  5631. $img_url = $statusInfo['result_url'][0];
  5632. break;
  5633. } elseif ($statusInfo['status'] === 'failed') {
  5634. $task->updateStatus('failed', [
  5635. 'error_message' => $statusInfo['error_message'],
  5636. 'result_json' => $statusInfo['result_json'] ?? []
  5637. ]);
  5638. dLog('anime')->error('三视图生成失败', [
  5639. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5640. ]);
  5641. Utils::throwError('20003:三视图生成失败,' . ($statusInfo['error_message'] ?? '未知错误'));
  5642. }
  5643. }
  5644. }
  5645. if (empty($img_url)) {
  5646. Utils::throwError('20003:三视图生成超时,请稍后重试');
  5647. }
  5648. // 保存三视图到 mp_products 表
  5649. DB::table('mp_products')
  5650. ->where('id', $id)
  5651. ->where('cpid', $cpid)
  5652. ->update([
  5653. 'three_view_image_url' => $img_url,
  5654. 'updated_at' => date('Y-m-d H:i:s')
  5655. ]);
  5656. return ['three_view_image_url' => $img_url];
  5657. } catch (\Exception $e) {
  5658. dLog('anime')->error('生成三视图失败', [
  5659. 'error' => $e->getMessage()
  5660. ]);
  5661. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  5662. Utils::throwError('20003:' . $e->getMessage());
  5663. }
  5664. }
  5665. /**
  5666. * 保存剧本资产关联关系
  5667. * @param array $data 请求参数
  5668. * @return bool
  5669. */
  5670. public function saveScriptProducts($data) {
  5671. $uid = Site::getUid();
  5672. $cpid = Site::getCpid();
  5673. $script_id = getProp($data, 'script_id');
  5674. $products = getProp($data, 'products', []);
  5675. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  5676. if (!$script_id) {
  5677. Utils::throwError('20003:请提供剧本ID');
  5678. }
  5679. // 验证剧本是否存在
  5680. $script = DB::table('mp_scripts')
  5681. ->where('id', $script_id)
  5682. ->where('is_deleted', 0)
  5683. ->first();
  5684. if (!$script) {
  5685. Utils::throwError('20003:剧本不存在');
  5686. }
  5687. $script_name = $script->script_name ?? 'script_' . $script_id;
  5688. // 检查是否已经有该剧本的资产数据
  5689. $existingMappings = DB::table('mp_script_product_mappings')
  5690. ->where('script_id', $script_id)
  5691. ->get();
  5692. if ($existingMappings->isNotEmpty()) {
  5693. // 已存在资产映射,检查是否所有资产都有图片生成任务
  5694. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  5695. // 查询这些资产的图片生成任务状态
  5696. $productsWithTasks = DB::table('mp_products')
  5697. ->whereIn('id', $productIds)
  5698. ->where('is_deleted', 0)
  5699. ->get();
  5700. $productTaskMap = [];
  5701. $typeFolderIds = [];
  5702. $hasAllTasks = true;
  5703. foreach ($productsWithTasks as $product) {
  5704. // 收集类型文件夹ID
  5705. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  5706. $parentFolder = DB::table('mp_products')
  5707. ->where('id', $product->parent_id)
  5708. ->where('type', 2)
  5709. ->first();
  5710. if ($parentFolder) {
  5711. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  5712. }
  5713. }
  5714. // 检查是否有图片生成任务
  5715. if (!empty($product->pic_task_id)) {
  5716. $productTaskMap[$product->id] = $product->pic_task_id;
  5717. } else if($product->url && $product->pic_task_status == '生成成功') {
  5718. continue;
  5719. }
  5720. else {
  5721. // 有资产没有图片任务
  5722. $hasAllTasks = false;
  5723. }
  5724. }
  5725. // 如果所有资产都有任务ID,直接轮询返回结果
  5726. if ($hasAllTasks && !empty($productTaskMap)) {
  5727. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  5728. 'script_id' => $script_id,
  5729. 'script_name' => $script_name,
  5730. 'product_count' => count($productTaskMap)
  5731. ]);
  5732. // 直接返回 SSE 流轮询结果
  5733. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  5734. }
  5735. // 如果部分资产没有任务ID,只为这些资产创建任务
  5736. if (!$hasAllTasks && $auto_generate_images) {
  5737. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  5738. 'script_id' => $script_id,
  5739. 'script_name' => $script_name
  5740. ]);
  5741. // 开启事务
  5742. DB::beginTransaction();
  5743. try {
  5744. // 默认图片生成参数
  5745. $model = 'doubao-seedream-5-0-lite-260128';
  5746. $width = 1600;
  5747. $height = 2848;
  5748. foreach ($productsWithTasks as $product) {
  5749. // 跳过已有任务的资产
  5750. if (!empty($product->pic_task_id)) {
  5751. continue;
  5752. }
  5753. // 跳过没有提示词的资产
  5754. if (empty($product->pic_prompt)) {
  5755. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  5756. 'product_id' => $product->id,
  5757. 'product_name' => $product->product_name
  5758. ]);
  5759. continue;
  5760. }
  5761. try {
  5762. // 创建图片生成任务
  5763. $params = [
  5764. 'prompt' => $product->pic_prompt,
  5765. 'model' => $model,
  5766. 'ref_img_urls' => [],
  5767. 'width' => $width,
  5768. 'height' => $height
  5769. ];
  5770. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5771. $task_id = $task->id;
  5772. if ($task_id) {
  5773. $productTaskMap[$product->id] = $task_id;
  5774. // 在事务中更新资产表的任务ID和状态
  5775. DB::table('mp_products')
  5776. ->where('id', $product->id)
  5777. ->update([
  5778. 'pic_task_id' => $task_id,
  5779. 'pic_task_status' => '生成中',
  5780. 'updated_at' => now()
  5781. ]);
  5782. dLog('anime')->info('为已存在资产创建图片生成任务', [
  5783. 'product_id' => $product->id,
  5784. 'task_id' => $task_id
  5785. ]);
  5786. }
  5787. } catch (\Exception $e) {
  5788. dLog('anime')->error('创建资产图片生成任务失败', [
  5789. 'product_id' => $product->id,
  5790. 'error' => $e->getMessage()
  5791. ]);
  5792. // 标记为失败(仍在事务中)
  5793. DB::table('mp_products')
  5794. ->where('id', $product->id)
  5795. ->update([
  5796. 'pic_task_status' => '生成失败',
  5797. 'updated_at' => now()
  5798. ]);
  5799. }
  5800. }
  5801. // 提交事务
  5802. DB::commit();
  5803. // 如果有新创建的任务,返回 SSE 流
  5804. if (!empty($productTaskMap)) {
  5805. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  5806. }
  5807. } catch (\Exception $e) {
  5808. // 回滚事务
  5809. DB::rollback();
  5810. dLog('anime')->error('为已存在资产创建图片任务失败', [
  5811. 'script_id' => $script_id,
  5812. 'error' => $e->getMessage()
  5813. ]);
  5814. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  5815. }
  5816. }
  5817. // 如果不需要生成图片,返回已存在的信息
  5818. return [
  5819. 'success' => true,
  5820. 'message' => '剧本资产已存在',
  5821. 'script_id' => $script_id,
  5822. 'script_name' => $script_name,
  5823. 'type_folder_ids' => $typeFolderIds,
  5824. 'existing_products' => count($productIds),
  5825. 'tasks_count' => count($productTaskMap)
  5826. ];
  5827. }
  5828. // 解析 products(可能是 JSON 字符串或数组)
  5829. if (is_string($products)) {
  5830. $products = json_decode($products, true);
  5831. if (json_last_error() !== JSON_ERROR_NONE) {
  5832. Utils::throwError('20003:产品数据格式错误');
  5833. }
  5834. }
  5835. if (!is_array($products) || empty($products)) {
  5836. Utils::throwError('20003:产品数据不能为空');
  5837. }
  5838. // 以下是原有的创建逻辑...
  5839. // 开启事务
  5840. DB::beginTransaction();
  5841. try {
  5842. $now = now();
  5843. $mappingRecords = [];
  5844. $createdProductIds = []; // 记录所有创建的资产ID
  5845. // 获取剧本名称
  5846. $script_name = $script->script_name ?? 'script_' . $script_id;
  5847. // 存储每个类型的根文件夹ID
  5848. $typeFolderIds = [];
  5849. // 默认图片生成参数
  5850. $model = 'doubao-seedream-5-0-lite-260128';
  5851. $width = 1600;
  5852. $height = 2848;
  5853. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  5854. foreach ($products as $productGroup) {
  5855. $type = getProp($productGroup, 'type');
  5856. $title = getProp($productGroup, 'title', '');
  5857. $content = getProp($productGroup, 'content', []);
  5858. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  5859. continue;
  5860. }
  5861. // 为当前类型创建根文件夹(如果还未创建)
  5862. if (!isset($typeFolderIds[$type])) {
  5863. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  5864. 'user_id' => $uid,
  5865. 'cpid' => $cpid,
  5866. 'type' => 2, // 1.资产 2文件夹
  5867. 'product' => $type, // 1.主体 2.场景 3.道具
  5868. 'parent_id' => 0, // 根文件夹,parent_id=0
  5869. 'level' => 1, // 第一层级
  5870. 'product_name' => $script_name,
  5871. 'sort_order' => time() + $type,
  5872. 'is_deleted' => 0,
  5873. 'created_at' => $now,
  5874. 'updated_at' => $now
  5875. ]);
  5876. }
  5877. $folder_id = $typeFolderIds[$type];
  5878. // 获取表头(第一行)并查找关键列的位置
  5879. $headers = $content[0];
  5880. $nameColumnIndex = -1; // 资产名称列索引
  5881. $sequenceColumnIndex = -1; // 使用范围列索引
  5882. $promptColumnIndex = -1; // 参考提示词列索引
  5883. foreach ($headers as $index => $header) {
  5884. // 查找"资产名称"列
  5885. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  5886. $nameColumnIndex = $index;
  5887. }
  5888. // 查找"使用范围"列
  5889. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  5890. $sequenceColumnIndex = $index;
  5891. }
  5892. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  5893. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  5894. $promptColumnIndex = $index;
  5895. }
  5896. }
  5897. // 验证必要的列是否都找到了
  5898. if ($nameColumnIndex === -1) {
  5899. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  5900. continue;
  5901. }
  5902. if ($sequenceColumnIndex === -1) {
  5903. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  5904. continue;
  5905. }
  5906. // 跳过表头,解析每一行数据
  5907. for ($i = 1; $i < count($content); $i++) {
  5908. $row = $content[$i];
  5909. // 确保行数据有效
  5910. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  5911. continue;
  5912. }
  5913. // 根据动态查找的列索引提取数据
  5914. $product_name = isset($row[$nameColumnIndex]) ? trim($row[$nameColumnIndex]) : '';
  5915. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  5916. $pic_prompt = '';
  5917. // 提取参考提示词(如果找到了该列)
  5918. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  5919. $pic_prompt = trim($row[$promptColumnIndex]);
  5920. }
  5921. // 解析使用范围(逗号分隔的序号)
  5922. $sequences = [];
  5923. if (!empty($sequence_str)) {
  5924. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  5925. foreach ($sequenceParts as $part) {
  5926. if (is_numeric($part)) {
  5927. $sequences[] = (int)$part;
  5928. }
  5929. }
  5930. }
  5931. if (empty($product_name)) {
  5932. continue;
  5933. }
  5934. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  5935. $product_id = DB::table('mp_products')->insertGetId([
  5936. 'product_name' => $product_name,
  5937. 'type' => 1, // 1=资产 2.文件夹
  5938. 'product' => $type, // 1=角色, 2=场景, 3=道具
  5939. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  5940. 'level' => 2, // 第二层级
  5941. 'pic_prompt' => $pic_prompt,
  5942. 'user_id' => $uid,
  5943. 'cpid' => $cpid,
  5944. 'sort_order' => time(),
  5945. 'is_deleted' => 0,
  5946. 'created_at' => $now,
  5947. 'updated_at' => $now,
  5948. ]);
  5949. // 记录创建的资产ID
  5950. $createdProductIds[] = $product_id;
  5951. // 为每个序号创建映射记录
  5952. if (!empty($sequences)) {
  5953. foreach ($sequences as $sequence) {
  5954. $mappingRecords[] = [
  5955. 'script_id' => $script_id,
  5956. 'product_id' => $product_id,
  5957. 'episode_number' => $sequence,
  5958. 'created_at' => $now,
  5959. 'updated_at' => $now,
  5960. ];
  5961. }
  5962. } else {
  5963. // 如果没有指定序号,创建一个默认映射(序号为0)
  5964. $mappingRecords[] = [
  5965. 'script_id' => $script_id,
  5966. 'product_id' => $product_id,
  5967. 'episode_number' => 0,
  5968. 'created_at' => $now,
  5969. 'updated_at' => $now,
  5970. ];
  5971. }
  5972. }
  5973. }
  5974. if (empty($mappingRecords)) {
  5975. Utils::throwError('20003:没有有效的产品数据');
  5976. }
  5977. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  5978. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  5979. // 如果需要自动生成图片,在事务中创建图片生成任务
  5980. $productTaskMap = [];
  5981. if ($auto_generate_images && !empty($createdProductIds)) {
  5982. // 查询所有创建的资产
  5983. $productsToGenerate = DB::table('mp_products')
  5984. ->whereIn('id', $createdProductIds)
  5985. ->where('is_deleted', 0)
  5986. ->get();
  5987. foreach ($productsToGenerate as $product) {
  5988. if (empty($product->pic_prompt)) {
  5989. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  5990. 'product_id' => $product->id,
  5991. 'product_name' => $product->product_name
  5992. ]);
  5993. continue;
  5994. }
  5995. try {
  5996. // 创建图片生成任务
  5997. $params = [
  5998. 'prompt' => $product->pic_prompt,
  5999. 'model' => $model,
  6000. 'ref_img_urls' => [],
  6001. 'width' => $width,
  6002. 'height' => $height
  6003. ];
  6004. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6005. $task_id = $task->id;
  6006. if ($task_id) {
  6007. $productTaskMap[$product->id] = $task_id;
  6008. // 在事务中更新资产表的任务ID和状态
  6009. DB::table('mp_products')
  6010. ->where('id', $product->id)
  6011. ->update([
  6012. 'pic_task_id' => $task_id,
  6013. 'pic_task_status' => '生成中',
  6014. 'updated_at' => now()
  6015. ]);
  6016. dLog('anime')->info('创建资产图片生成任务', [
  6017. 'product_id' => $product->id,
  6018. 'task_id' => $task_id
  6019. ]);
  6020. }
  6021. } catch (\Exception $e) {
  6022. dLog('anime')->error('创建资产图片生成任务失败', [
  6023. 'product_id' => $product->id,
  6024. 'error' => $e->getMessage()
  6025. ]);
  6026. // 标记为失败(仍在事务中)
  6027. DB::table('mp_products')
  6028. ->where('id', $product->id)
  6029. ->update([
  6030. 'pic_task_status' => '生成失败',
  6031. 'updated_at' => now()
  6032. ]);
  6033. }
  6034. }
  6035. }
  6036. // 提交事务
  6037. DB::commit();
  6038. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  6039. if ($auto_generate_images && !empty($productTaskMap)) {
  6040. // 返回 SSE 流(事务外轮询)
  6041. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6042. }
  6043. // 如果不需要生成图片,返回普通结果
  6044. return [
  6045. 'success' => true,
  6046. 'type_folder_ids' => $typeFolderIds,
  6047. 'inserted_count' => $insertedCount,
  6048. 'total_records' => count($mappingRecords),
  6049. 'created_products' => count($createdProductIds),
  6050. 'image_tasks_created' => count($productTaskMap)
  6051. ];
  6052. } catch (\Exception $e) {
  6053. // 回滚事务
  6054. DB::rollback();
  6055. // 记录错误日志
  6056. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  6057. 'script_id' => $script_id,
  6058. 'error' => $e->getMessage(),
  6059. 'trace' => $e->getTraceAsString()
  6060. ]);
  6061. // 统一使用 Utils::throwError 抛出错误
  6062. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  6063. }
  6064. }
  6065. /**
  6066. * 批量为剧本资产生成图片
  6067. *
  6068. * @param array $data 请求参数
  6069. * @return \Generator 返回 SSE 流
  6070. */
  6071. public function batchGenerateProductImages($data) {
  6072. $script_id = getProp($data, 'script_id');
  6073. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  6074. if (!$script_id) {
  6075. Utils::throwError('20003:请提供剧本ID');
  6076. }
  6077. // 验证剧本是否存在
  6078. $script = DB::table('mp_scripts')
  6079. ->where('id', $script_id)
  6080. ->where('is_deleted', 0)
  6081. ->first();
  6082. if (!$script) {
  6083. Utils::throwError('20003:剧本不存在');
  6084. }
  6085. $script_name = $script->script_name ?? 'script_' . $script_id;
  6086. // 获取需要生成图片的所有资产
  6087. $products = DB::table('mp_products')
  6088. ->whereIn('parent_id', array_values($type_folder_ids))
  6089. ->where('is_deleted', 0)
  6090. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  6091. ->get();
  6092. if ($products->isEmpty()) {
  6093. Utils::throwError('20003:没有找到需要生成图片的资产');
  6094. }
  6095. // 默认参数
  6096. $model = 'doubao-seedream-5-0-lite-260128';
  6097. $width = 1600;
  6098. $height = 2848;
  6099. // 开始为每个资产创建图片生成任务
  6100. $taskIds = [];
  6101. $productTaskMap = []; // 资产ID到任务ID的映射
  6102. foreach ($products as $product) {
  6103. if (empty($product->pic_prompt)) {
  6104. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  6105. continue;
  6106. }
  6107. try {
  6108. // 创建图片生成任务
  6109. $params = [
  6110. 'prompt' => $product->pic_prompt,
  6111. 'model' => $model,
  6112. 'ref_img_urls' => [],
  6113. 'width' => $width,
  6114. 'height' => $height
  6115. ];
  6116. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6117. $task_id = $task->id;
  6118. if ($task_id) {
  6119. $taskIds[] = $task_id;
  6120. $productTaskMap[$product->id] = $task_id;
  6121. // 更新资产表的任务ID和状态
  6122. DB::table('mp_products')
  6123. ->where('id', $product->id)
  6124. ->update([
  6125. 'pic_task_id' => $task_id,
  6126. 'pic_task_status' => '生成中',
  6127. 'updated_at' => now()
  6128. ]);
  6129. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  6130. }
  6131. } catch (\Exception $e) {
  6132. dLog('anime')->error('创建资产图片生成任务失败', [
  6133. 'product_id' => $product->id,
  6134. 'error' => $e->getMessage()
  6135. ]);
  6136. // 标记为失败
  6137. DB::table('mp_products')
  6138. ->where('id', $product->id)
  6139. ->update([
  6140. 'pic_task_status' => '生成失败',
  6141. 'updated_at' => now()
  6142. ]);
  6143. }
  6144. }
  6145. if (empty($taskIds)) {
  6146. Utils::throwError('20003:没有成功创建任何图片生成任务');
  6147. }
  6148. // 返回 SSE 流
  6149. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  6150. }
  6151. /**
  6152. * 轮询资产图片生成任务状态(SSE流式返回)
  6153. * 只通过查询数据库获取任务状态,不主动调用API
  6154. *
  6155. * @param int $script_id 剧本ID
  6156. * @param string $script_name 剧本名称
  6157. * @param array $productTaskMap 资产ID到任务ID的映射
  6158. * @param array $type_folder_ids 类型文件夹ID映射
  6159. * @return \Generator
  6160. */
  6161. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  6162. $startTime = time();
  6163. $timeout = 1800; // 30分钟超时
  6164. $pollInterval = 10; // 10秒轮询一次
  6165. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  6166. // 定义类型名称映射
  6167. $typeNames = [
  6168. 1 => 'roles', // 角色
  6169. 2 => 'scenes', // 场景
  6170. 3 => 'props' // 道具
  6171. ];
  6172. while (time() - $startTime < $timeout) {
  6173. sleep($pollInterval);
  6174. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  6175. $mappings = DB::table('mp_script_product_mappings')
  6176. ->where('script_id', $script_id)
  6177. ->pluck('product_id')
  6178. ->unique()
  6179. ->toArray();
  6180. if (empty($mappings)) {
  6181. dLog('anime')->warning('该剧本没有关联的资产', [
  6182. 'script_id' => $script_id,
  6183. 'script_name' => $script_name
  6184. ]);
  6185. break;
  6186. }
  6187. // 查询所有资产的当前状态
  6188. $products = DB::table('mp_products')
  6189. ->whereIn('id', $mappings)
  6190. ->where('is_deleted', 0)
  6191. ->get();
  6192. // 统计各类型的状态(使用类型名称作为键名)
  6193. $stats = [
  6194. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  6195. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  6196. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  6197. ];
  6198. $allCompleted = true;
  6199. $hasStatusChange = false;
  6200. foreach ($products as $product) {
  6201. $type = $product->product;
  6202. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  6203. // 如果类型名称不在 stats 中,初始化
  6204. if (!isset($stats[$typeName])) {
  6205. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  6206. }
  6207. $stats[$typeName]['total']++;
  6208. $task_id = $product->pic_task_id;
  6209. $currentStatus = $product->pic_task_status;
  6210. // 检查状态是否有变化
  6211. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  6212. $hasStatusChange = true;
  6213. $lastStatus[$product->id] = $currentStatus;
  6214. }
  6215. // 如果是生成中,查询任务表状态
  6216. if ($currentStatus === '生成中' && $task_id) {
  6217. // 只查询数据库,不调用API
  6218. $task = DB::table('mp_generate_pic_tasks')
  6219. ->where('id', $task_id)
  6220. ->first();
  6221. if ($task) {
  6222. // 检查任务状态
  6223. if ($task->status === 'success' && $task->result_url) {
  6224. // 解析图片URL
  6225. $result_urls = $task->result_url;
  6226. if (is_string($result_urls)) {
  6227. $result_urls = json_decode($result_urls, true);
  6228. }
  6229. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6230. // 更新资产表状态
  6231. DB::table('mp_products')
  6232. ->where('id', $product->id)
  6233. ->update([
  6234. 'pic_task_status' => '生成成功',
  6235. 'url' => $img_url,
  6236. 'updated_at' => now()
  6237. ]);
  6238. $stats[$typeName]['success']++;
  6239. $stats[$typeName]['completed']++;
  6240. $hasStatusChange = true;
  6241. dLog('anime')->info('资产图片生成成功', [
  6242. 'product_id' => $product->id,
  6243. 'task_id' => $task_id,
  6244. 'img_url' => $img_url
  6245. ]);
  6246. } elseif ($task->status === 'failed') {
  6247. // 更新资产表状态
  6248. DB::table('mp_products')
  6249. ->where('id', $product->id)
  6250. ->update([
  6251. 'pic_task_status' => '生成失败',
  6252. 'updated_at' => now()
  6253. ]);
  6254. $stats[$typeName]['completed']++;
  6255. $hasStatusChange = true;
  6256. dLog('anime')->warning('资产图片生成失败', [
  6257. 'product_id' => $product->id,
  6258. 'task_id' => $task_id,
  6259. 'error' => $task->error_message ?? '未知错误'
  6260. ]);
  6261. } else {
  6262. // 任务还在处理中
  6263. $allCompleted = false;
  6264. }
  6265. } else {
  6266. // 任务不存在,标记为失败
  6267. DB::table('mp_products')
  6268. ->where('id', $product->id)
  6269. ->update([
  6270. 'pic_task_status' => '生成失败',
  6271. 'updated_at' => now()
  6272. ]);
  6273. $stats[$type]['completed']++;
  6274. $hasStatusChange = true;
  6275. dLog('anime')->error('图片生成任务不存在', [
  6276. 'product_id' => $product->id,
  6277. 'task_id' => $task_id
  6278. ]);
  6279. }
  6280. } elseif ($currentStatus === '生成成功') {
  6281. $stats[$typeName]['success']++;
  6282. $stats[$typeName]['completed']++;
  6283. } elseif ($currentStatus === '生成失败') {
  6284. $stats[$typeName]['completed']++;
  6285. } else {
  6286. // 其他状态也认为未完成
  6287. $allCompleted = false;
  6288. }
  6289. }
  6290. // 移除没有数据的类型(total=0)
  6291. foreach ($stats as $typeName => $stat) {
  6292. if ($stat['total'] === 0) {
  6293. unset($stats[$typeName]);
  6294. }
  6295. }
  6296. // 如果有状态变化,发送 SSE 更新
  6297. if ($hasStatusChange) {
  6298. $eventType = $allCompleted ? 'complete' : 'update';
  6299. $response = [
  6300. 'type' => $eventType,
  6301. 'script_id' => $script_id,
  6302. 'script_name' => $script_name,
  6303. 'stats' => $stats,
  6304. 'timestamp' => date('Y-m-d H:i:s')
  6305. ];
  6306. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  6307. dLog('anime')->info('SSE更新', [
  6308. 'event_type' => $eventType,
  6309. 'script_id' => $script_id,
  6310. 'script_name' => $script_name,
  6311. 'stats' => $stats
  6312. ]);
  6313. if ($allCompleted) {
  6314. dLog('anime')->info('所有资产图片生成任务已完成', [
  6315. 'script_id' => $script_id,
  6316. 'script_name' => $script_name,
  6317. 'stats' => $stats
  6318. ]);
  6319. break;
  6320. }
  6321. }
  6322. }
  6323. // 超时处理
  6324. if (time() - $startTime >= $timeout && !$allCompleted) {
  6325. $response = [
  6326. 'type' => 'timeout',
  6327. 'message' => '部分任务超时,请稍后查看结果',
  6328. 'script_id' => $script_id,
  6329. 'script_name' => $script_name,
  6330. 'timestamp' => date('Y-m-d H:i:s')
  6331. ];
  6332. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  6333. dLog('anime')->warning('资产图片生成任务超时', [
  6334. 'script_id' => $script_id,
  6335. 'script_name' => $script_name,
  6336. 'timeout' => $timeout
  6337. ]);
  6338. }
  6339. }
  6340. /**
  6341. * 获取剧本关联的资产列表
  6342. * @param array $data 请求参数
  6343. * @return array
  6344. */
  6345. public function getScriptProducts($data) {
  6346. $uid = Site::getUid();
  6347. $cpid = Site::getCpid();
  6348. $script_id = getProp($data, 'script_id');
  6349. $episode_number = getProp($data, 'episode_number');
  6350. if (!$script_id) {
  6351. Utils::throwError('20003:请提供剧本ID');
  6352. }
  6353. // 验证剧本是否存在
  6354. $script = DB::table('mp_scripts')
  6355. ->where('id', $script_id)
  6356. ->where('is_deleted', 0)
  6357. ->first();
  6358. if (!$script) {
  6359. Utils::throwError('20003:剧本不存在');
  6360. }
  6361. // 联表查询资产信息
  6362. $query = DB::table('mp_script_product_mappings as mapping')
  6363. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6364. ->where('mapping.script_id', $script_id)
  6365. ->where('product.cpid', $cpid)
  6366. ->where('product.is_deleted', 0);
  6367. // 如果提供了 episode_number,则过滤指定集数
  6368. if ($episode_number !== null && $episode_number !== '') {
  6369. $query->where('mapping.episode_number', $episode_number);
  6370. }
  6371. $mappings = $query->select(
  6372. 'mapping.script_id',
  6373. 'mapping.product_id',
  6374. 'mapping.episode_number',
  6375. 'product.product_name',
  6376. 'product.type',
  6377. 'product.product',
  6378. 'product.pic_prompt',
  6379. 'product.url',
  6380. 'product.pic_task_id',
  6381. 'product.pic_task_status',
  6382. 'product.three_view_image_url',
  6383. 'mapping.created_at'
  6384. )
  6385. ->orderBy('mapping.product_id', 'asc')
  6386. ->orderBy('mapping.episode_number', 'asc')
  6387. ->get();
  6388. // 按 product_id 分组,合并 episode_number
  6389. $productMap = [];
  6390. foreach ($mappings as $item) {
  6391. $product_id = $item->product_id;
  6392. if (!isset($productMap[$product_id])) {
  6393. $productMap[$product_id] = [
  6394. 'product_id' => $product_id,
  6395. 'product_name' => $item->product_name,
  6396. 'type' => (int)$item->type,
  6397. 'product' => (int)$item->product,
  6398. 'pic_prompt' => $item->pic_prompt,
  6399. 'url' => $item->url,
  6400. 'pic_task_id' => $item->pic_task_id,
  6401. 'pic_task_status' => $item->pic_task_status,
  6402. 'episode_numbers' => [],
  6403. 'created_at' => $item->created_at,
  6404. ];
  6405. }
  6406. // 添加 episode_number(去重)
  6407. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6408. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6409. }
  6410. }
  6411. // 按类型分组
  6412. $roles = []; // type=1 角色/主体
  6413. $scenes = []; // type=2 场景
  6414. $props = []; // type=3 道具
  6415. foreach ($productMap as $product) {
  6416. // 将 episode_numbers 数组转换为逗号分隔的字符串
  6417. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  6418. // 构造返回数据
  6419. $productData = [
  6420. 'product_id' => $product['product_id'],
  6421. 'product_name' => $product['product_name'],
  6422. 'product' => $product['product'],
  6423. 'pic_prompt' => $product['pic_prompt'],
  6424. 'url' => $product['url'],
  6425. 'pic_task_id' => $product['pic_task_id'],
  6426. 'pic_task_status' => $product['pic_task_status'],
  6427. 'episode_numbers' => $episodeNumbersStr,
  6428. 'created_at' => $product['created_at'],
  6429. ];
  6430. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  6431. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  6432. switch ($product['product']) {
  6433. case 1:
  6434. $roles[] = $productData;
  6435. break;
  6436. case 2:
  6437. $scenes[] = $productData;
  6438. break;
  6439. case 3:
  6440. $props[] = $productData;
  6441. break;
  6442. }
  6443. }
  6444. return [
  6445. 'script_id' => $script_id,
  6446. 'script_name' => $script->script_name ?? '',
  6447. 'roles' => $roles, // 主体
  6448. 'scenes' => $scenes, // 场景
  6449. 'props' => $props, // 道具
  6450. ];
  6451. }
  6452. /**
  6453. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  6454. * @param string $actContent 原始内容
  6455. * @param array $products 产品数组(包含product_name和url)
  6456. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  6457. */
  6458. public function processActContentWithProducts($actContent, $products) {
  6459. if (empty($actContent) || empty($products)) {
  6460. return [
  6461. 'content' => $actContent,
  6462. 'reference_images' => []
  6463. ];
  6464. }
  6465. // 构建产品名称到产品信息的映射
  6466. $product_dict = [];
  6467. foreach ($products as $product) {
  6468. $product_name = getProp($product, 'product_name');
  6469. if ($product_name) {
  6470. $product_dict[$product_name] = [
  6471. 'url' => getProp($product, 'url'),
  6472. 'voice_prompt' => getProp($product, 'voice_prompt')
  6473. ];
  6474. }
  6475. }
  6476. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  6477. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  6478. $reference_images = [];
  6479. $product_index_map = []; // 产品名称 => 图片序号的映射
  6480. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  6481. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  6482. $current_index = 1;
  6483. if (!empty($matches[1])) {
  6484. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  6485. $seen_products = []; // 用于去重
  6486. foreach ($matches[1] as $product_name) {
  6487. // 跳过已处理的产品
  6488. if (isset($seen_products[$product_name])) {
  6489. continue;
  6490. }
  6491. $seen_products[$product_name] = true;
  6492. // 检查产品是否在字典中
  6493. if (isset($product_dict[$product_name])) {
  6494. $url = $product_dict[$product_name]['url'];
  6495. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  6496. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  6497. if (!empty($voice_prompt) && $product_name !== '旁白') {
  6498. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  6499. }
  6500. // 只有URL非空才分配序号和添加到参考图片
  6501. if (!empty($url)) {
  6502. // 检查URL是否已经在reference_images中(去重)
  6503. if (!in_array($url, $reference_images)) {
  6504. $reference_images[] = $url;
  6505. $product_index_map[$product_name] = $current_index;
  6506. $current_index++;
  6507. } else {
  6508. // URL重复,找到已有的序号
  6509. $existing_index = array_search($url, $reference_images) + 1;
  6510. $product_index_map[$product_name] = $existing_index;
  6511. }
  6512. } else {
  6513. // URL为空,不分配序号(后续直接去掉{})
  6514. $product_index_map[$product_name] = 0;
  6515. }
  6516. } else {
  6517. // 产品不在字典中,不分配序号
  6518. $product_index_map[$product_name] = 0;
  6519. }
  6520. }
  6521. }
  6522. // 第二步:替换内容中的 {产品名称}
  6523. $processedContent = $actContent;
  6524. foreach ($product_index_map as $product_name => $index) {
  6525. $escaped_name = preg_quote($product_name, '/');
  6526. if ($index > 0) {
  6527. // 有图片,替换为:产品名称(图X)
  6528. $replacement = $product_name . '<图片' . $index . '>';
  6529. } else {
  6530. // 无图片,只保留产品名称
  6531. $replacement = $product_name;
  6532. }
  6533. // 替换所有 {产品名称} 为处理后的格式
  6534. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  6535. }
  6536. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  6537. foreach ($products as $product) {
  6538. $product_name = getProp($product, 'product_name');
  6539. $voice_prompt = getProp($product, 'voice_prompt');
  6540. if ($product_name === '旁白' && !empty($voice_prompt)) {
  6541. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  6542. break; // 找到旁白后退出循环
  6543. }
  6544. }
  6545. // 第四步:将voice_prompt信息添加到内容最前面
  6546. $voice_prompt_prefix = '';
  6547. if (!empty($voice_prompts)) {
  6548. $voice_prompt_prefix .= implode('', $voice_prompts);
  6549. }
  6550. // 旁白的voice_prompt放在最后
  6551. if (!empty($narrator_voice_prompt)) {
  6552. $voice_prompt_prefix .= $narrator_voice_prompt;
  6553. }
  6554. // 如果有voice_prompt信息,添加到内容开头
  6555. if (!empty($voice_prompt_prefix)) {
  6556. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  6557. }
  6558. return [
  6559. 'content' => $processedContent,
  6560. 'reference_images' => $reference_images
  6561. ];
  6562. }
  6563. public function saveActVideoGenerateParams($data) {
  6564. $episode_id = getProp($data, 'episode_id');
  6565. $model = getProp($data, 'video_model');
  6566. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  6567. Utils::throwError('20003:该模型不可用');
  6568. }
  6569. if (!$model) {
  6570. // 使用默认模型
  6571. $model = 'zhizhen-20-mini';
  6572. }
  6573. // 验证模型是否在可用模型表中
  6574. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6575. Utils::throwError('20003:该模型已不可用,请更换!');
  6576. }
  6577. $video_resolution = getProp($data, 'video_resolution', '720p');
  6578. $ratio = getProp($data, 'ratio');
  6579. if (!$ratio) $ratio = '9:16';
  6580. return DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  6581. 'video_model' => $model,
  6582. 'video_resolution' => $video_resolution,
  6583. 'ratio' => $ratio,
  6584. 'updated_at' => date('Y-m-d H:i:s')
  6585. ]);
  6586. }
  6587. public function confirmActs($data) {
  6588. $episode_id = getProp($data, 'episode_id');
  6589. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  6590. if (!$episode) {
  6591. Utils::throwError('20003:分集不存在');
  6592. }
  6593. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  6594. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  6595. // 获取所有片段数据
  6596. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  6597. // 构建角色和场景名称数组
  6598. $role_names = [];
  6599. $scene_names = [];
  6600. foreach ($roles as $role) {
  6601. $role_name = getProp($role, 'role');
  6602. if ($role_name && $role_name != '旁白') {
  6603. $role_names[] = $role_name;
  6604. }
  6605. }
  6606. foreach ($scenes as $scene) {
  6607. $scene_name = getProp($scene, 'scene');
  6608. if ($scene_name) {
  6609. $scene_names[] = $scene_name;
  6610. }
  6611. }
  6612. // 按照字符长度降序排序,确保先匹配长的名称(避免部分匹配问题)
  6613. usort($role_names, function($a, $b) {
  6614. return mb_strlen($b) - mb_strlen($a);
  6615. });
  6616. usort($scene_names, function($a, $b) {
  6617. return mb_strlen($b) - mb_strlen($a);
  6618. });
  6619. try {
  6620. DB::beginTransaction();
  6621. // 处理每个片段
  6622. foreach ($acts as $act) {
  6623. $act_content = getProp($act, 'act_content');
  6624. if (!$act_content) continue;
  6625. $processed_content = $act_content;
  6626. // 标记已处理的位置,避免重复标记
  6627. $marked_positions = [];
  6628. // 先匹配场景(在"场景:"后面)
  6629. foreach ($scene_names as $scene_name) {
  6630. // 转义特殊字符
  6631. $escaped_scene = preg_quote($scene_name, '/');
  6632. // 匹配场景:后面的场景名称(可能换行,也可能不换行)
  6633. $pattern = '/(场景:[\s\r\n]*)(' . $escaped_scene . ')/u';
  6634. $processed_content = preg_replace_callback($pattern, function($matches) use (&$marked_positions) {
  6635. $full_match = $matches[0];
  6636. $prefix = $matches[1];
  6637. $scene_name = $matches[2];
  6638. // 检查是否已经被标记
  6639. if (strpos($scene_name, '{') === false && strpos($scene_name, '}') === false) {
  6640. return $prefix . '{' . $scene_name . '}';
  6641. }
  6642. return $full_match;
  6643. }, $processed_content);
  6644. }
  6645. // 再匹配角色名称(只在"画面:"部分)
  6646. foreach ($role_names as $role_name) {
  6647. // 转义特殊字符
  6648. $escaped_role = preg_quote($role_name, '/');
  6649. // 只匹配"画面:"开始到换行之前的内容
  6650. $pattern = '/(画面:[^\n]*)/u';
  6651. $processed_content = preg_replace_callback($pattern, function($matches) use ($escaped_role) {
  6652. $line = $matches[1]; // 整行"画面:xxxxx"
  6653. // 在这一行中匹配所有角色名(避免重复标记)
  6654. $new_line = preg_replace(
  6655. '/(?<![{])(' . $escaped_role . ')(?![}])/u',
  6656. '{$1}',
  6657. $line
  6658. );
  6659. return $new_line;
  6660. }, $processed_content);
  6661. }
  6662. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  6663. $shot_counter = 0;
  6664. $processed_content = preg_replace_callback(
  6665. '/【(?:镜头|分镜)(\d+)】/u',
  6666. function($matches) use (&$shot_counter) {
  6667. $shot_counter++;
  6668. return '【镜头' . $shot_counter . '】';
  6669. },
  6670. $processed_content
  6671. );
  6672. // 更新数据库
  6673. $boolen = DB::table('mp_episode_segments')
  6674. ->where('id', $act->id)
  6675. ->update([
  6676. 'act_show_content' => $processed_content,
  6677. 'updated_at' => date('Y-m-d H:i:s')
  6678. ]);
  6679. if (!$boolen) {
  6680. Utils::throwError('20003:片段处理失败');
  6681. }
  6682. }
  6683. }catch (\Exception $e) {
  6684. DB::rollBack();
  6685. Utils::throwError('20003:'.$e->getMessage());
  6686. }
  6687. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  6688. 'is_generated' => 1,
  6689. 'updated_at' => date('Y-m-d H:i:s')
  6690. ]);
  6691. if (!$boolen1) {
  6692. DB::rollBack();
  6693. Utils::throwError('20003:分集处理失败!');
  6694. }
  6695. DB::commit();
  6696. // 重新查询更新后的片段数据
  6697. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  6698. // 合并角色、场景和extra_products作为products,统一字段名为product_name
  6699. // extra_products优先级更高,会覆盖同名的roles和scenes
  6700. $products = [];
  6701. // 先处理角色数组
  6702. foreach ($roles as $role) {
  6703. $product = $role;
  6704. // 将role字段重命名为product_name
  6705. if (isset($product['role'])) {
  6706. $product['product_name'] = $product['role'];
  6707. unset($product['role']);
  6708. }
  6709. $product['product'] = 1; // 标记类型为角色
  6710. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  6711. }
  6712. // 处理场景数组
  6713. foreach ($scenes as $scene) {
  6714. $product = $scene;
  6715. // 将scene字段重命名为product_name
  6716. if (isset($product['scene'])) {
  6717. $product['product_name'] = $product['scene'];
  6718. unset($product['scene']);
  6719. }
  6720. $product['product'] = 2; // 标记类型为场景
  6721. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  6722. }
  6723. // extra_products优先级更高,直接覆盖同名的roles和scenes
  6724. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  6725. foreach ($extra_products as $extra_product) {
  6726. $product_name = getProp($extra_product, 'product_name');
  6727. if ($product_name) {
  6728. $products[$product_name] = $extra_product; // 覆盖同名数据
  6729. }
  6730. }
  6731. // 重新索引数组(去除key)
  6732. $products = array_values($products);
  6733. // 构建返回的acts数组
  6734. $return_acts = [];
  6735. foreach ($acts as $act) {
  6736. $return_acts[] = [
  6737. 'act_id' => getProp($act, 'id'),
  6738. 'act_number' => getProp($act, 'act_number'),
  6739. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  6740. 'act_show_content' => getProp($act, 'act_show_content'),
  6741. 'video_url' => getProp($act, 'video_url'),
  6742. 'video_duration' => getProp($act, 'video_duration'),
  6743. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  6744. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  6745. ];
  6746. }
  6747. return [
  6748. 'anime_id' => getProp($episode, 'anime_id'),
  6749. 'episode_id' => $episode_id,
  6750. 'title' => getProp($episode, 'title'),
  6751. 'episode_number' => getProp($episode, 'episode_number'),
  6752. 'is_generated' => getProp($episode, 'is_generated'),
  6753. 'products' => $products,
  6754. 'acts' => $return_acts
  6755. ];
  6756. }
  6757. }