AnimeService.php 385 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902
  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 App\Services\PointsService;
  12. use Dflydev\DotAccessData\Util;
  13. use GuzzleHttp\Client;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Log;
  16. use Illuminate\Support\Facades\Redis;
  17. use OSS\Core\OssException;
  18. use OSS\OssClient;
  19. class AnimeService
  20. {
  21. protected $aiImageGenerationService;
  22. protected $aiVideoGenerationService;
  23. protected $DeepSeekService;
  24. protected $pointsService;
  25. private $url;
  26. private $api_key;
  27. private $headers;
  28. public function __construct(
  29. AIImageGenerationService $aiImageGenerationService,
  30. AIVideoGenerationService $aiVideoGenerationService,
  31. DeepSeekService $DeepSeekService,
  32. PointsService $pointsService
  33. ) {
  34. $this->aiImageGenerationService = $aiImageGenerationService;
  35. $this->aiVideoGenerationService = $aiVideoGenerationService;
  36. $this->DeepSeekService = $DeepSeekService;
  37. $this->pointsService = $pointsService;
  38. $this->url = 'https://api.deepseek.com/chat/completions';
  39. $this->api_key = env('DEEPSEEK_API_KEY');
  40. $this->headers = [
  41. 'Authorization' => 'Bearer '.$this->api_key,
  42. 'Content-Type' => 'application/json; charset=UTF-8'
  43. ];
  44. }
  45. /**
  46. * 构建统一的分镜数据结构(episodeInfo格式)
  47. * @param array $segments 分镜数据数组
  48. * @return array 返回包含acts和total_duration的数组
  49. */
  50. public function buildEpisodeSegmentsStructure($segments) {
  51. $acts = [];
  52. $totalDuration = 0; // 初始化总时长
  53. foreach($segments as $segment) {
  54. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  55. $videoDuration = getProp($segment, 'video_duration');
  56. $audioDuration = getProp($segment, 'audio_duration');
  57. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  58. $totalDuration += floatval($videoDuration);
  59. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  60. $totalDuration += floatval($audioDuration);
  61. } else {
  62. $totalDuration += 5; // 默认5秒
  63. }
  64. $segment_content = getProp($segment, 'segment_content');
  65. // 判断是否有尾帧描述,如果有则去掉这部分内容
  66. if (strpos($segment_content, '尾帧') !== false) {
  67. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  68. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  69. }
  70. // 构建分镜信息
  71. $segmentInfo = [
  72. 'segment_id' => getProp($segment, 'segment_id'),
  73. 'segment_number' => getProp($segment, 'segment_number'),
  74. 'segment_content' => $segment_content,
  75. 'description' => getProp($segment, 'description'),
  76. 'composition' => getProp($segment, 'composition'),
  77. 'camera_movement' => getProp($segment, 'camera_movement'),
  78. 'voice_actor' => getProp($segment, 'voice_actor'),
  79. 'dialogue' => getProp($segment, 'dialogue'),
  80. 'frame_type' => getProp($segment, 'frame_type'),
  81. 'scene' => getProp($segment, 'scene'),
  82. 'characters' => getProp($segment, 'characters'),
  83. 'tail_frame' => getProp($segment, 'tail_frame'),
  84. 'emotion' => getProp($segment, 'emotion'),
  85. 'emotion_type' => getProp($segment, 'emotion_type'),
  86. 'gender' => getProp($segment, 'gender'),
  87. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  88. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  89. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  90. 'pitch' => getProp($segment, 'pitch'),
  91. 'voice_name' => getProp($segment, 'voice_name'),
  92. 'voice_type' => getProp($segment, 'voice_type'),
  93. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  94. 'img_url' => getProp($segment, 'img_url'),
  95. 'audio_url' => getProp($segment, 'audio_url'),
  96. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  97. 'video_url' => getProp($segment, 'video_url'),
  98. 'video_duration' => getProp($segment, 'video_duration', 0),
  99. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  100. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  101. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  102. 'current_type' => getProp($segment, 'current_type'),
  103. ];
  104. $actNumber = getProp($segment, 'act_number');
  105. if (isset($acts[$actNumber])) {
  106. $acts[$actNumber]['segments'][] = $segmentInfo;
  107. } else {
  108. $acts[$actNumber] = [
  109. 'act_number' => $actNumber,
  110. 'act_title' => getProp($segment, 'act_title'),
  111. 'act_duration' => getProp($segment, 'act_duration'),
  112. 'segments' => [$segmentInfo]
  113. ];
  114. }
  115. }
  116. return [
  117. 'acts' => array_values($acts),
  118. 'total_duration' => intval(round($totalDuration))
  119. ];
  120. }
  121. /**
  122. * 构建统一的分段数据结构(episodeInfoForAce格式)
  123. * @param array $segments 分段数据数组
  124. * @return array 返回包含acts和total_duration的数组
  125. */
  126. public function buildEpisodeActsStructureForAce($segments) {
  127. $acts = [];
  128. $totalDuration = 0; // 初始化总时长
  129. foreach($segments as $segment) {
  130. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  131. $videoDuration = getProp($segment, 'video_duration');
  132. $actDuration = getProp($segment, 'act_duration');
  133. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  134. $totalDuration += floatval($videoDuration);
  135. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  136. $totalDuration += floatval($actDuration);
  137. } else {
  138. $totalDuration += 5; // 默认5秒
  139. }
  140. // 构建分镜信息
  141. $segmentInfo = [
  142. 'act_id' => getProp($segment, 'id'),
  143. 'act_number' => getProp($segment, 'act_number'),
  144. 'act_title' => getProp($segment, 'act_title'),
  145. 'act_duration' => getProp($segment, 'act_duration'),
  146. 'act_content' => getProp($segment, 'act_content'),
  147. 'video_url' => getProp($segment, 'video_url'),
  148. 'video_duration' => getProp($segment, 'video_duration', 0),
  149. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  150. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  151. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  152. 'current_type' => getProp($segment, 'current_type'),
  153. ];
  154. $acts[] = $segmentInfo;
  155. }
  156. return [
  157. 'acts' => array_values($acts),
  158. 'total_duration' => intval(round($totalDuration))
  159. ];
  160. }
  161. /**
  162. * 验证画面比例是否有效
  163. * @param string $ratio 画面比例
  164. * @return bool
  165. */
  166. public function validateRatio($ratio) {
  167. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  168. }
  169. /**
  170. * 获取画面比例对应的宽高
  171. * @param string $ratio 画面比例
  172. * @return array ['width' => int, 'height' => int]
  173. * @throws \Exception
  174. */
  175. private function getRatioDimensions($ratio) {
  176. if ($ratio && !$this->validateRatio($ratio)) {
  177. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  178. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  179. }
  180. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  181. }
  182. public function createAnime($data) {
  183. $uid = Site::getUid();
  184. $cpid = Site::getCpid();
  185. $input_art_style = getProp($data, 'art_style');
  186. $file = getProp($data, 'file');
  187. $content = getProp($data, 'content', '');
  188. $bid = getProp($data, 'bid', 0);
  189. $script_id = getProp($data, 'script_id', 0);
  190. $ace_mode = getProp($data, 'ace_mode', 0);
  191. $extra_products = getProp($data, 'products', []);
  192. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  193. if (!is_array($extra_products)) {
  194. Utils::throwError('20003:传入的资产格式不正确');
  195. }
  196. // 替换美术风格
  197. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  198. // 提取文件内容
  199. if ($file) {
  200. $content = $this->DeepSeekService->extractFileContent($file);
  201. if (!$content) {
  202. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  203. }
  204. } elseif ($script_id) {
  205. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  206. if (!$content) {
  207. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  208. }
  209. } elseif ($bid) {
  210. $content = $this->DeepSeekService->getContentByBid($bid);
  211. if (!$content) {
  212. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  213. }
  214. } elseif ($content) {
  215. $content = filterContent($content);
  216. }else {
  217. $content = '';
  218. }
  219. $anime_data = [
  220. 'user_id' => $uid,
  221. 'cpid' => $cpid,
  222. 'anime_name' => '新剧本策划',
  223. 'is_multi' => getProp($data, 'is_multi', 1),
  224. 'content' => $content,
  225. 'art_style_type' => $input_art_style,
  226. 'ace_mode' => $ace_mode,
  227. 'script_id' => $script_id,
  228. 'extra_products' => json_encode($extra_products, 256),
  229. 'created_at' => date('Y-m-d H:i:s'),
  230. 'updated_at' => date('Y-m-d H:i:s'),
  231. ];
  232. // 处理文本模型
  233. $model = getProp($data, 'model');
  234. if (!$model) {
  235. // 用户没有输入,使用默认值
  236. $model = 'deepseek-v4-pro';
  237. }
  238. // 验证模型是否在可用模型表中
  239. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  240. $model = 'deepseek-v4-pro';
  241. }
  242. $anime_data['model'] = $model;
  243. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  244. return DB::table('mp_animes')->insertGetId($anime_data);
  245. }
  246. public function chatList($data) {
  247. $uid = Site::getUid();
  248. $anime_name = getProp($data, 'anime_name');
  249. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  250. if ($anime_name) {
  251. $query->where('anime_name', 'like', "%$anime_name%");
  252. }
  253. return $query->orderBy('id', 'desc')->paginate();
  254. }
  255. public function chatHistory($data) {
  256. $anime_id = getProp($data, 'anime_id');
  257. $sequence = getProp($data, 'sequence', 0);
  258. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  259. $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)
  260. ->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');
  261. return $query->orderBy('ar.id')->get()->map(function ($value) {
  262. $value = (array)$value;
  263. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  264. $value['created_at'] = transDate($value['created_at']);
  265. $value['episode_created_at'] = transDate($value['episode_created_at']);
  266. return $value;
  267. })->toArray();
  268. }
  269. public function batchSetRoleImg($data) {
  270. $episode_id = getProp($data, 'episode_id');
  271. if (!$episode_id) Utils::throwError('1002:请选择分集');
  272. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  273. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  274. $art_style = getProp($episode, 'art_style');
  275. $anime_id = getProp($episode, 'anime_id');
  276. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  277. $art_style_type = getProp($anime, 'art_style_type');
  278. $character_prefix = '';
  279. $scene_prefix = '';
  280. if ($art_style_type) {
  281. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  282. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  283. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  284. }
  285. foreach ($roles as &$role) {
  286. $role_name = getProp($role, 'role');
  287. if ($role_name == '旁白') continue;
  288. // 优先使用 pic_prompt,如果没有则使用 description
  289. $pic_prompt = getProp($role, 'pic_prompt');
  290. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  291. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  292. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  293. // 参考图地址
  294. $ref_img_url = getProp($role, 'url');
  295. if ($ref_img_url) continue; // 已有图片则跳过
  296. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  297. try {
  298. $params = [
  299. 'prompt' => $description,
  300. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  301. ];
  302. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  303. $task_id = $task->id;
  304. if (!$task_id) {
  305. Utils::throwError("20003:角色({$role_name})生成图片失败");
  306. }
  307. $role['task_id'] = $task_id;
  308. $role['task_status'] = 'processing';
  309. } catch (\Exception $e) {
  310. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  311. Utils::throwError("20003:" . $e->getMessage());
  312. }
  313. }
  314. // 保存角色信息
  315. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  316. 'roles' => json_encode($roles, 256),
  317. 'generate_status' => '执行中',
  318. 'generate_at' => date('Y-m-d H:i:s'),
  319. 'updated_at' => date('Y-m-d H:i:s')
  320. ]);
  321. if (!$boolen) {
  322. Utils::throwError('20003:保存角色信息失败');
  323. }
  324. return $boolen;
  325. }
  326. public function batchSetSceneImg($data) {
  327. $episode_id = getProp($data, 'episode_id');
  328. if (!$episode_id) Utils::throwError('1002:请选择分集');
  329. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  330. $scenes = json_decode(getProp($episode, 'scenes'), true);
  331. $art_style = getProp($episode, 'art_style');
  332. $target_scene = getProp($data, 'target_scene');
  333. $anime_id = getProp($episode, 'anime_id');
  334. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  335. $art_style_type = getProp($anime, 'art_style_type');
  336. $character_prefix = '';
  337. $scene_prefix = '';
  338. if ($art_style_type) {
  339. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  340. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  341. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  342. }
  343. foreach ($scenes as &$scene) {
  344. $scene_name = getProp($scene, 'scene');
  345. if ($scene_name != $target_scene) continue;
  346. // 优先使用 pic_prompt,如果没有则使用 description
  347. $pic_prompt = getProp($scene, 'pic_prompt');
  348. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  349. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  350. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  351. // 参考图地址
  352. $ref_img_url = getProp($scene, 'url');
  353. if ($ref_img_url) continue; // 已有图片则跳过
  354. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  355. try {
  356. $params = [
  357. 'prompt' => $description,
  358. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  359. ];
  360. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  361. $task_id = $task->id;
  362. if (!$task_id) {
  363. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  364. }
  365. $scene['task_id'] = $task_id;
  366. $scene['task_status'] = 'processing';
  367. } catch (\Exception $e) {
  368. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  369. Utils::throwError("20003:" . $e->getMessage());
  370. }
  371. }
  372. // 保存场景信息
  373. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  374. 'scenes' => json_encode($scenes, 256),
  375. 'generate_status' => '执行中',
  376. 'generate_at' => date('Y-m-d H:i:s'),
  377. 'updated_at' => date('Y-m-d H:i:s')
  378. ]);
  379. if (!$boolen) {
  380. Utils::throwError('20003:保存角色信息失败');
  381. }
  382. return $boolen;
  383. }
  384. public function editAnime($data) {
  385. $anime_id = getProp($data, 'anime_id');
  386. $anime_name = trim(getProp($data, 'anime_name'));
  387. // 确认对话名称唯一性
  388. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  389. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  390. }
  391. if (!$anime_id || !$anime_name) {
  392. Utils::throwError('20003:参数异常');
  393. }
  394. return DB::table('mp_animes')->where('id', $anime_id)->update([
  395. 'anime_name' => $anime_name,
  396. 'updated_at' => date('Y-m-d H:i:s')
  397. ]);
  398. // $script_arr =getProp($data, 'script', []);
  399. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  400. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  401. // $anime_id = getProp($data, 'anime_id');
  402. // try {
  403. // DB::beginTransaction();
  404. // $table_data = [
  405. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  406. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  407. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  408. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  409. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  410. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  411. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  412. // 'status' => 3,
  413. // 'start_episode_sequence' => $start_episode_sequence,
  414. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  415. // 'episode_num' => count($script_arr['episodes']),
  416. // 'updated_at' => date('Y-m-d H:i:s')
  417. // ];
  418. // // 保存剧本内容
  419. // if (!empty($anime_id)) {
  420. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  421. // if (!$boolen) {
  422. // dLog('anime')->info('对话保存失败', $table_data);
  423. // Utils::throwError('20003:对话保存失败');
  424. // }
  425. // }else {
  426. // $table['created_at'] = $table_data['updated_at'];
  427. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  428. // if (!$anime_id) {
  429. // dLog('anime')->info('对话保存失败', $table_data);
  430. // Utils::throwError('20003:对话保存失败');
  431. // }
  432. // }
  433. // // 保存分集内容
  434. // // 删除历史分集内容
  435. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  436. // $episodes = [];
  437. // $sequence = 1;
  438. // foreach ($script_arr['episodes'] as $episode) {
  439. // $segment_number = 1;
  440. // foreach($episode['segments'] as $segment) {
  441. // $episodes[] = [
  442. // 'anime_id' => $anime_id,
  443. // 'episode_number' => $episode['episode_number'],
  444. // 'title' => $episode['title'],
  445. // // 'content' => $episode['content'],
  446. // 'content' => '',
  447. // 'segment_number' => $segment_number,
  448. // 'segment_content' => $segment['segment_content'],
  449. // 'sequence' => $sequence,
  450. // 'created_at' => date('Y-m-d H:i:s'),
  451. // 'updated_at' => date('Y-m-d H:i:s')
  452. // ];
  453. // $sequence++;
  454. // $segment_number++;
  455. // }
  456. // }
  457. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  458. // if (!$boolen2) {
  459. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  460. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  461. // Utils::throwError('20003:分集内容保存失败');
  462. // }
  463. // } catch (\Exception $e) {
  464. // DB::rollBack();
  465. // Utils::throwError('20003:'.$e->getMessage());
  466. // }
  467. // DB::commit();
  468. // return true;
  469. }
  470. public function delAnime($data) {
  471. $anime_id = getProp($data, 'anime_id');
  472. if (!$anime_id) {
  473. Utils::throwError('20003:请选择剧本');
  474. }
  475. return DB::table('mp_animes')->where('id', $anime_id)->update([
  476. 'is_deleted' => 1,
  477. 'updated_at' => date('Y-m-d H:i:s')
  478. ]);
  479. }
  480. public function animeDetail($data) {
  481. $uid = Site::getUid();
  482. $anime_id = getProp($data, 'anime_id');
  483. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  484. ->selectRaw('id as anime_id, anime_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, remark, generate_status, created_at, ace_mode, end_episode_sequence')->first();
  485. if (!$anime) Utils::throwError('20003:权限不足');
  486. $anime = (array)$anime;
  487. $anime['roles'] = json_decode($anime['roles']);
  488. $anime['scenes'] = json_decode($anime['scenes']);
  489. // 获取分集信息
  490. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  491. ->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"))
  492. ->orderBy('episode_number')->get()->map(function ($value) {
  493. return (array)$value;
  494. })->toArray();
  495. $anime['episodes'] = $episodes;
  496. return $anime;
  497. }
  498. public function episodeInfo($data) {
  499. $uid = Site::getUid();
  500. $anime_id = getProp($data, 'anime_id');
  501. $episode_id = getProp($data, 'episode_id');
  502. if (!$anime_id || !$episode_id) {
  503. Utils::throwError('1002:请选择剧集');
  504. }
  505. // 验证用户权限
  506. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  507. if (!$anime) Utils::throwError('20003:权限不足');
  508. $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();
  509. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  510. $episode = (array)$episode;
  511. $episode['roles'] = json_decode($episode['roles'], true);
  512. // foreach($episode['roles'] as &$item) {
  513. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  514. // }
  515. $episode['scenes'] = json_decode($episode['scenes'], true);
  516. // foreach($episode['scenes'] as &$item) {
  517. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  518. // }
  519. // 获取分镜信息
  520. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  521. ->select('*')->get()->map(function ($value) {
  522. return (array)$value;
  523. })->toArray();
  524. // 使用公共方法构建分镜结构
  525. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  526. $episode['acts'] = $segmentsStructure['acts'];
  527. $episode['total_duration'] = $segmentsStructure['total_duration'];
  528. return $episode;
  529. }
  530. public function episodeInfoForAce($data) {
  531. $anime_id = getProp($data, 'anime_id');
  532. $episode_id = getProp($data, 'episode_id');
  533. if (!$anime_id || !$episode_id) {
  534. Utils::throwError('1002:请选择剧集');
  535. }
  536. $episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes', 'props', 'is_generated')->first();
  537. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  538. $episode = (array)$episode;
  539. $episode['roles'] = json_decode($episode['roles'], true);
  540. // foreach($episode['roles'] as &$item) {
  541. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  542. // }
  543. $episode['scenes'] = json_decode($episode['scenes'], true);
  544. // foreach($episode['scenes'] as &$item) {
  545. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  546. // }
  547. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  548. // 获取分镜信息
  549. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  550. ->select('*')->get()->map(function ($value) {
  551. return (array)$value;
  552. })->toArray();
  553. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  554. $episode['acts'] = $segmentsStructure['acts'];
  555. $episode['total_duration'] = $segmentsStructure['total_duration'];
  556. return $episode;
  557. }
  558. public function segmentInfo($data) {
  559. $uid = Site::getUid();
  560. $segment_id = getProp($data, 'segment_id');
  561. if (!$segment_id) {
  562. Utils::throwError('1002:请选择分镜');
  563. }
  564. // 获取分镜信息
  565. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  566. // 验证用户权限
  567. if ($segment) {
  568. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  569. if (!$anime) Utils::throwError('20003:权限不足');
  570. }
  571. $result = [
  572. 'segment_id' => getProp($segment, 'segment_id'),
  573. 'segment_number' => getProp($segment, 'segment_number'),
  574. 'segment_content' => getProp($segment, 'segment_content'),
  575. 'description' => getProp($segment, 'description'),
  576. 'composition' => getProp($segment, 'composition'),
  577. 'camera_movement' => getProp($segment, 'camera_movement'),
  578. 'voice_actor' => getProp($segment, 'voice_actor'),
  579. 'dialogue' => getProp($segment, 'dialogue'),
  580. 'frame_type' => getProp($segment, 'frame_type'),
  581. 'scene' => getProp($segment, 'scene'),
  582. 'characters' => getProp($segment, 'characters'),
  583. 'tail_frame' => getProp($segment, 'tail_frame'),
  584. 'emotion' => getProp($segment, 'emotion'),
  585. 'emotion_type' => getProp($segment, 'emotion_type'),
  586. 'gender' => getProp($segment, 'gender'),
  587. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  588. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  589. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  590. 'pitch' => getProp($segment, 'pitch'),
  591. 'voice_name' => getProp($segment, 'voice_name'),
  592. 'voice_type' => getProp($segment, 'voice_type'),
  593. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  594. 'img_url' => getProp($segment, 'img_url'),
  595. 'video_url' => getProp($segment, 'video_url'),
  596. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  597. ];
  598. return $result;
  599. }
  600. public function copyEpisodeVersion($data) {
  601. $episode_id = getProp($data, 'episode_id');
  602. $uid = Site::getUid();
  603. $cpid = Site::getCpid();
  604. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  605. if (!$episode) Utils::throwError('20003:该剧集不存在');
  606. $episode = (array)$episode;
  607. $anime_id = $episode['anime_id'];
  608. $episode_number = $episode['episode_number'];
  609. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  610. $sequence = $count + 1;
  611. unset($episode['id']);
  612. $now = date('Y-m-d H:i:s');
  613. $episode['created_at'] = $now;
  614. $episode['updated_at'] = $now;
  615. $episode['is_default'] = 1;
  616. // 获取版本中含有"(副本"字样的个数
  617. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  618. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  619. $episode['sequence'] = $sequence;
  620. $episode['is_generated'] = 0;
  621. $episode['cpid'] = $cpid;
  622. // 获取ace_mode
  623. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  624. try {
  625. DB::beginTransaction();
  626. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  627. // 新增副本
  628. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  629. if (!$new_episode_id) {
  630. Utils::throwError('20003:创建副本失败!');
  631. }
  632. // 获取分镜数据并准备插入
  633. $segments_for_insert = DB::table('mp_episode_segments')
  634. ->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')
  635. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  636. $item = (array)$item;
  637. $item['episode_id'] = $new_episode_id;
  638. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  639. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  640. return $item;
  641. })->toArray();
  642. // 写入分镜数据
  643. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  644. if (!$boolen2) {
  645. Utils::throwError('20003:写入分镜数据失败!');
  646. }
  647. // 写入对话历史
  648. $records = [
  649. [
  650. 'uid' => $uid,
  651. 'anime_id' => $anime_id,
  652. 'role' => 'user',
  653. 'content' => '创建副本',
  654. 'sequence' => $episode_number,
  655. 'episode_id' => $new_episode_id,
  656. 'created_at' => $now,
  657. 'updated_at' => $now
  658. ],
  659. [
  660. 'uid' => $uid,
  661. 'anime_id' => $anime_id,
  662. 'role' => 'assistant',
  663. 'content' => '好的,已为您创建副本',
  664. 'sequence' => $episode_number,
  665. 'episode_id' => $new_episode_id,
  666. 'created_at' => $now,
  667. 'updated_at' => $now
  668. ]
  669. ];
  670. $boolen3 = DB::table('mp_anime_records')->insert($records);
  671. if (!$boolen3) {
  672. Utils::throwError('20003:对话记录保存失败');
  673. }
  674. }catch (\Exception $e) {
  675. DB::rollBack();
  676. Utils::throwError('20003:'.$e->getMessage());
  677. }
  678. DB::commit();
  679. // 构建与 episodeInfo 方法一致的返回数据结构
  680. $result = [
  681. 'episode_id' => $new_episode_id,
  682. 'anime_id' => $anime_id,
  683. 'episode_number' => $episode_number,
  684. 'title' => $episode['title'],
  685. 'intro' => $episode['intro'],
  686. 'art_style' => $episode['art_style'],
  687. 'roles' => json_decode($episode['roles'], true),
  688. 'scenes' => json_decode($episode['scenes'], true),
  689. 'is_generated' => (int)$episode['is_generated']
  690. ];
  691. if ((int)$ace_mode === 1) {
  692. // 获取分镜信息
  693. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  694. ->select('*')->get()->map(function ($value) {
  695. return (array)$value;
  696. })->toArray();
  697. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  698. }else {
  699. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  700. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  701. }
  702. $result['acts'] = $segmentsStructure['acts'];
  703. $result['total_duration'] = $segmentsStructure['total_duration'];
  704. return $result;
  705. }
  706. public function episodeVersions($data) {
  707. $anime_id = getProp($data, 'anime_id');
  708. $episode_id = getProp($data, 'episode_id');
  709. if (!$anime_id || !$episode_id) {
  710. Utils::throwError('1002:请选择剧集');
  711. }
  712. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  713. $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) {
  714. return (array)$value;
  715. })->toArray();
  716. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  717. foreach($episodes as &$episode) {
  718. $episode['version'] = 'V'.$episode['sequence'];
  719. $episode['roles'] = json_decode($episode['roles'], true);
  720. $episode['scenes'] = json_decode($episode['scenes'], true);
  721. // 获取分镜信息
  722. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  723. ->select('*')->get()->map(function ($value) {
  724. return (array)$value;
  725. })->toArray();
  726. // 使用公共方法构建分镜结构
  727. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  728. $episode['acts'] = $segmentsStructure['acts'];
  729. $episode['total_duration'] = $segmentsStructure['total_duration'];
  730. }
  731. return $episodes;
  732. }
  733. public function bindEpisodeVersion($data) {
  734. $episode_id = getProp($data, 'episode_id');
  735. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  736. if (!$episode) Utils::throwError('20003:该剧集不存在');
  737. $episode = (array)$episode;
  738. if ((int)$episode['is_default'] === 1) return true;
  739. try {
  740. DB::beginTransaction();
  741. // 移除is_default标志
  742. $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')]);
  743. if (!$boolen) {
  744. Utils::throwError('20003:更新失败!');
  745. }
  746. // 绑定副本
  747. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  748. if (!$boolen2) {
  749. Utils::throwError('20003:绑定失败!');
  750. }
  751. }catch (\Exception $e) {
  752. DB::rollBack();
  753. Utils::throwError('20003:'.$e->getMessage());
  754. }
  755. DB::commit();
  756. return true;
  757. }
  758. public function chatChangeImg($data) {
  759. $segment_id = getProp($data, 'segment_id');
  760. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  761. $prompt = getProp($data, 'prompt');
  762. if (!$prompt || !$segment_id) {
  763. Utils::throwError('1002:请输入提示词,并且选择分镜');
  764. }
  765. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  766. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  767. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  768. else $ref_img_url = '';
  769. // $ref_img_url = '';
  770. if (empty($prompt)) {
  771. if (empty($ref_img_url)) {
  772. $prompt = getProp($segment, 'segment_content');
  773. }else {
  774. $prompt = '请根据图片生成';
  775. }
  776. }
  777. $anime_id = getProp($segment, 'anime_id');
  778. $episode_id = getProp($segment, 'episode_id');
  779. $episode_number = getProp($segment, 'episode_number');
  780. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  781. $ratio = getProp($data, 'ratio');
  782. if (!$ratio) {
  783. $ratio = getProp($episode, 'ratio');
  784. if (!$ratio) $ratio = '9:16';
  785. }
  786. $art_style = getProp($episode, 'art_style');
  787. if ($art_style) {
  788. $prompt = "美术风格:{$art_style}\n{$prompt}";
  789. }
  790. $dimensions = $this->getRatioDimensions($ratio);
  791. $width = $dimensions['width'];
  792. $height = $dimensions['height'];
  793. try {
  794. $params = [
  795. 'alias_segment_id' => $segment_id,
  796. 'prompt' => $prompt,
  797. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  798. 'width' => $width,
  799. 'height' => $height
  800. ];
  801. // 优化提示词(不要生成字幕)
  802. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  803. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  804. $task_id = $task->id;
  805. if (!$task_id) {
  806. Utils::throwError("20003:生成图片失败");
  807. }
  808. // 更新任务ID
  809. $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')]);
  810. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  811. } catch (\Exception $e) {
  812. Utils::throwError("20003:" . $e->getMessage());
  813. }
  814. // 创建任务之后先暂停10s等待异步任务完成
  815. sleep(10);
  816. $img_url = $this->loopGetPicTaskResult($task_id);
  817. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  818. // 图片生成后新增对话记录
  819. try {
  820. $uid = Site::getUid();
  821. $now = date('Y-m-d H:i:s');
  822. // 使用AI反推图片提示词
  823. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  824. // 保存对话记录
  825. $records = [
  826. [
  827. 'uid' => $uid,
  828. 'anime_id' => $anime_id,
  829. 'sequence' => $episode_number,
  830. 'role' => 'user',
  831. 'content' => $prompt,
  832. 'segment_id' => $segment_id,
  833. 'image_url' => '',
  834. 'created_at' => $now,
  835. 'updated_at' => $now
  836. ],
  837. [
  838. 'uid' => $uid,
  839. 'anime_id' => $anime_id,
  840. 'sequence' => $episode_number,
  841. 'role' => 'assistant',
  842. 'content' => $pic_prompt,
  843. 'segment_id' => $segment_id,
  844. 'image_url' => $img_url,
  845. 'created_at' => $now,
  846. 'updated_at' => $now
  847. ]
  848. ];
  849. DB::table('mp_anime_records')->insert($records);
  850. } catch (\Exception $e) {
  851. // 记录日志但不影响主流程
  852. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  853. 'segment_id' => $segment_id,
  854. 'img_url' => $img_url
  855. ]);
  856. logDB('anime', 'error', '保存对话记录失败', [
  857. 'segment_id' => $segment_id,
  858. 'img_url' => $img_url,
  859. 'error' => $e->getMessage()
  860. ]);
  861. }
  862. return $img_url;
  863. }
  864. public function segmentChatHistory($data) {
  865. $segment_id = getProp($data, 'segment_id');
  866. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  867. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'created_at');
  868. $chat = $query->orderBy('id')->get()->map(function ($value) {
  869. $value = (array)$value;
  870. $value['created_at'] = transDate($value['created_at']);
  871. return $value;
  872. })->toArray();
  873. // 获取历史图片
  874. $url = [];
  875. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  876. foreach($pic_history as $task) {
  877. $result_url = getProp($task, 'result_url');
  878. if (is_json($result_url)) {
  879. $url = array_merge($url, json_decode($result_url, true));
  880. }else {
  881. $url[] = $result_url;
  882. }
  883. }
  884. // 获取历史视频
  885. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  886. foreach($video_history as $task) {
  887. $result_url = getProp($task, 'compressed_url');
  888. if (is_json($result_url)) {
  889. $url = array_merge($url, json_decode($result_url, true));
  890. }else {
  891. $url[] = $result_url;
  892. }
  893. }
  894. return compact('chat', 'url');
  895. }
  896. public function changeEpisodeRoles($data) {
  897. $anime_id = getProp($data, 'anime_id');
  898. $episode_id = getProp($data, 'episode_id');
  899. $target_roles = getProp($data, 'roles');
  900. $is_deleted = getProp($data, 'is_deleted', 0);
  901. // 参数验证
  902. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  903. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  904. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  905. // 验证剧集是否存在
  906. $episode = DB::table('mp_anime_episodes')
  907. ->where('anime_id', $anime_id)
  908. ->where('id', $episode_id)
  909. ->first();
  910. if (!$episode) Utils::throwError('20003:该剧集不存在');
  911. $roles = json_decode(getProp($episode, 'roles'), true);
  912. // 获取anime信息,检查是否有关联的script_id
  913. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  914. if (!$anime) Utils::throwError('20003:动漫不存在');
  915. $script_id = getProp($anime, 'script_id');
  916. $episode_number = getProp($episode, 'episode_number', 1);
  917. $uid = Site::getUid();
  918. $cpid = Site::getCpid();
  919. try {
  920. $target_role_name = getProp($target_roles, 'role');
  921. // 如果是删除操作
  922. if ($is_deleted == 1) {
  923. // 从角色列表中移除该角色
  924. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  925. return getProp($role, 'role') !== $target_role_name;
  926. }));
  927. // 更新角色列表
  928. $result = DB::table('mp_anime_episodes')
  929. ->where('anime_id', $anime_id)
  930. ->where('id', $episode_id)
  931. ->update([
  932. 'roles' => json_encode($roles, 256),
  933. 'updated_at' => date('Y-m-d H:i:s')
  934. ]);
  935. if ($result === false) {
  936. Utils::throwError('20003:删除角色失败');
  937. }
  938. } else {
  939. // 新增或更新操作
  940. $role_found = false;
  941. $is_new_role = false;
  942. // 查找并更新已存在的角色
  943. foreach($roles as &$role) {
  944. if (getProp($role, 'role') === $target_role_name) {
  945. $role = $target_roles;
  946. $role_found = true;
  947. break;
  948. }
  949. }
  950. // 如果角色不存在,则新增
  951. if (!$role_found) {
  952. $roles[] = $target_roles;
  953. $is_new_role = true;
  954. }
  955. // 更新角色列表
  956. $result = DB::table('mp_anime_episodes')
  957. ->where('anime_id', $anime_id)
  958. ->where('id', $episode_id)
  959. ->update([
  960. 'roles' => json_encode($roles, 256),
  961. 'updated_at' => date('Y-m-d H:i:s')
  962. ]);
  963. if ($result === false) {
  964. Utils::throwError('20003:更新角色列表失败');
  965. }
  966. // 同步更新分镜表中对应主体的音色信息
  967. $voice_name = getProp($target_roles, 'voice_name');
  968. $voice_type = getProp($target_roles, 'voice_type');
  969. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  970. DB::table('mp_episode_segments')
  971. ->where('anime_id', $anime_id)
  972. ->where('episode_id', $episode_id)
  973. ->where('voice_actor', $target_role_name)
  974. ->update([
  975. 'voice_name' => $voice_name,
  976. 'voice_type' => $voice_type,
  977. 'voice_audio_url' => $voice_audio_url,
  978. 'updated_at' => date('Y-m-d H:i:s')
  979. ]);
  980. // 如果有关联的script_id,则同步到mp_products表
  981. if ($script_id) {
  982. // 查询剧本信息
  983. $script = DB::table('mp_scripts')
  984. ->where('id', $script_id)
  985. ->where('is_deleted', 0)
  986. ->first();
  987. if ($script) {
  988. $script_name = $script->script_name ?? 'script_' . $script_id;
  989. $product_name = getProp($target_roles, 'role');
  990. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  991. $url = getProp($target_roles, 'url', '');
  992. $product_type = 1; // 1=角色
  993. // 查找或创建以script_name命名的文件夹
  994. $folder = DB::table('mp_products')
  995. ->where('cpid', $cpid)
  996. ->where('type', 2) // 文件夹类型
  997. ->where('product', $product_type) // 角色类型
  998. ->where('product_name', $script_name)
  999. ->where('parent_id', 0)
  1000. ->where('is_deleted', 0)
  1001. ->first();
  1002. if (!$folder) {
  1003. // 创建文件夹
  1004. $folder_id = DB::table('mp_products')->insertGetId([
  1005. 'user_id' => $uid,
  1006. 'cpid' => $cpid,
  1007. 'type' => 2, // 文件夹
  1008. 'product' => $product_type, // 角色类型
  1009. 'parent_id' => 0,
  1010. 'level' => 1,
  1011. 'product_name' => $script_name,
  1012. 'sort_order' => time(),
  1013. 'is_deleted' => 0,
  1014. 'created_at' => date('Y-m-d H:i:s'),
  1015. 'updated_at' => date('Y-m-d H:i:s')
  1016. ]);
  1017. } else {
  1018. $folder_id = $folder->id;
  1019. }
  1020. // 查找该文件夹下是否已存在同名资产
  1021. $existing_product = DB::table('mp_products')
  1022. ->where('cpid', $cpid)
  1023. ->where('type', 1) // 资产类型
  1024. ->where('product', $product_type)
  1025. ->where('parent_id', $folder_id)
  1026. ->where('product_name', $product_name)
  1027. ->where('is_deleted', 0)
  1028. ->first();
  1029. if ($existing_product) {
  1030. // 更新已存在的资产
  1031. $updateData = [
  1032. 'pic_task_status' => '生成成功',
  1033. ];
  1034. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1035. if ($url) $updateData['url'] = $url;
  1036. // 处理versions字段
  1037. $versions = getProp($target_roles, 'versions', []);
  1038. if ($versions && is_array($versions)) {
  1039. $updateData['versions'] = json_encode($versions, 256);
  1040. }
  1041. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1042. DB::table('mp_products')
  1043. ->where('id', $existing_product->id)
  1044. ->update($updateData);
  1045. $product_id = $existing_product->id;
  1046. } else {
  1047. // 创建新资产
  1048. $versions = getProp($target_roles, 'versions', []);
  1049. $product_id = DB::table('mp_products')->insertGetId([
  1050. 'user_id' => $uid,
  1051. 'cpid' => $cpid,
  1052. 'type' => 1, // 资产
  1053. 'product' => $product_type, // 角色
  1054. 'parent_id' => $folder_id,
  1055. 'level' => 2,
  1056. 'product_name' => $product_name,
  1057. 'url' => $url,
  1058. 'pic_prompt' => $pic_prompt,
  1059. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1060. 'sort_order' => time(),
  1061. 'is_deleted' => 0,
  1062. 'pic_task_status' => '生成成功',
  1063. 'created_at' => date('Y-m-d H:i:s'),
  1064. 'updated_at' => date('Y-m-d H:i:s')
  1065. ]);
  1066. }
  1067. // 建立或更新绑定关系
  1068. $existing_mapping = DB::table('mp_script_product_mappings')
  1069. ->where('script_id', $script_id)
  1070. ->where('product_id', $product_id)
  1071. ->where('episode_number', $episode_number)
  1072. ->first();
  1073. if (!$existing_mapping) {
  1074. // 创建绑定关系
  1075. DB::table('mp_script_product_mappings')->insert([
  1076. 'script_id' => $script_id,
  1077. 'product_id' => $product_id,
  1078. 'episode_number' => $episode_number,
  1079. 'created_at' => date('Y-m-d H:i:s'),
  1080. 'updated_at' => date('Y-m-d H:i:s')
  1081. ]);
  1082. }
  1083. }
  1084. }
  1085. }
  1086. } catch (\Exception $e) {
  1087. dLog('anime')->error('更新剧集角色失败', [
  1088. 'anime_id' => $anime_id,
  1089. 'episode_id' => $episode_id,
  1090. 'error' => $e->getMessage()
  1091. ]);
  1092. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1093. }
  1094. return true;
  1095. }
  1096. public function changeEpisodeScenes($data) {
  1097. $anime_id = getProp($data, 'anime_id');
  1098. $episode_id = getProp($data, 'episode_id');
  1099. $target_scenes = getProp($data, 'scenes');
  1100. $is_deleted = getProp($data, 'is_deleted', 0);
  1101. // 参数验证
  1102. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1103. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1104. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1105. // 验证剧集是否存在
  1106. $episode = DB::table('mp_anime_episodes')
  1107. ->where('anime_id', $anime_id)
  1108. ->where('id', $episode_id)
  1109. ->first();
  1110. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1111. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1112. // 获取anime信息,检查是否有关联的script_id
  1113. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1114. if (!$anime) Utils::throwError('20003:动漫不存在');
  1115. $script_id = getProp($anime, 'script_id');
  1116. $episode_number = getProp($episode, 'episode_number', 1);
  1117. $uid = Site::getUid();
  1118. $cpid = Site::getCpid();
  1119. try {
  1120. $target_scene_name = getProp($target_scenes, 'scene');
  1121. // 如果是删除操作
  1122. if ($is_deleted == 1) {
  1123. // 从场景列表中移除该场景
  1124. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1125. return getProp($scene, 'scene') !== $target_scene_name;
  1126. }));
  1127. // 更新场景列表
  1128. $result = DB::table('mp_anime_episodes')
  1129. ->where('anime_id', $anime_id)
  1130. ->where('id', $episode_id)
  1131. ->update([
  1132. 'scenes' => json_encode($scenes, 256),
  1133. 'updated_at' => date('Y-m-d H:i:s')
  1134. ]);
  1135. if ($result === false) {
  1136. Utils::throwError('20003:删除场景失败');
  1137. }
  1138. } else {
  1139. // 新增或更新操作
  1140. $scene_found = false;
  1141. $is_new_scene = false;
  1142. // 查找并更新已存在的场景
  1143. foreach($scenes as &$scene) {
  1144. if (getProp($scene, 'scene') === $target_scene_name) {
  1145. $scene = $target_scenes;
  1146. $scene_found = true;
  1147. break;
  1148. }
  1149. }
  1150. // 如果场景不存在,则新增
  1151. if (!$scene_found) {
  1152. $scenes[] = $target_scenes;
  1153. $is_new_scene = true;
  1154. }
  1155. // 更新场景列表
  1156. $result = DB::table('mp_anime_episodes')
  1157. ->where('anime_id', $anime_id)
  1158. ->where('id', $episode_id)
  1159. ->update([
  1160. 'scenes' => json_encode($scenes, 256),
  1161. 'updated_at' => date('Y-m-d H:i:s')
  1162. ]);
  1163. if ($result === false) {
  1164. Utils::throwError('20003:更新场景列表失败');
  1165. }
  1166. // 如果有关联的script_id,则同步到mp_products表
  1167. if ($script_id) {
  1168. // 查询剧本信息
  1169. $script = DB::table('mp_scripts')
  1170. ->where('id', $script_id)
  1171. ->where('is_deleted', 0)
  1172. ->first();
  1173. if ($script) {
  1174. $script_name = $script->script_name ?? 'script_' . $script_id;
  1175. $product_name = getProp($target_scenes, 'scene');
  1176. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1177. $url = getProp($target_scenes, 'url', '');
  1178. $product_type = 2; // 2=场景
  1179. // 查找或创建以script_name命名的文件夹
  1180. $folder = DB::table('mp_products')
  1181. ->where('cpid', $cpid)
  1182. ->where('type', 2) // 文件夹类型
  1183. ->where('product', $product_type) // 场景类型
  1184. ->where('product_name', $script_name)
  1185. ->where('parent_id', 0)
  1186. ->where('is_deleted', 0)
  1187. ->first();
  1188. if (!$folder) {
  1189. // 创建文件夹
  1190. $folder_id = DB::table('mp_products')->insertGetId([
  1191. 'user_id' => $uid,
  1192. 'cpid' => $cpid,
  1193. 'type' => 2, // 文件夹
  1194. 'product' => $product_type, // 场景类型
  1195. 'parent_id' => 0,
  1196. 'level' => 1,
  1197. 'product_name' => $script_name,
  1198. 'sort_order' => time(),
  1199. 'is_deleted' => 0,
  1200. 'created_at' => date('Y-m-d H:i:s'),
  1201. 'updated_at' => date('Y-m-d H:i:s')
  1202. ]);
  1203. } else {
  1204. $folder_id = $folder->id;
  1205. }
  1206. // 查找该文件夹下是否已存在同名资产
  1207. $existing_product = DB::table('mp_products')
  1208. ->where('cpid', $cpid)
  1209. ->where('type', 1) // 资产类型
  1210. ->where('product', $product_type)
  1211. ->where('parent_id', $folder_id)
  1212. ->where('product_name', $product_name)
  1213. ->where('is_deleted', 0)
  1214. ->first();
  1215. if ($existing_product) {
  1216. // 更新已存在的资产
  1217. $updateData = [
  1218. 'pic_task_status' => '生成成功'
  1219. ];
  1220. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1221. if ($url) $updateData['url'] = $url;
  1222. // 处理versions字段
  1223. $versions = getProp($target_scenes, 'versions', []);
  1224. if ($versions && is_array($versions)) {
  1225. $updateData['versions'] = json_encode($versions, 256);
  1226. }
  1227. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1228. DB::table('mp_products')
  1229. ->where('id', $existing_product->id)
  1230. ->update($updateData);
  1231. $product_id = $existing_product->id;
  1232. } else {
  1233. // 创建新资产
  1234. $versions = getProp($target_scenes, 'versions', []);
  1235. $product_id = DB::table('mp_products')->insertGetId([
  1236. 'user_id' => $uid,
  1237. 'cpid' => $cpid,
  1238. 'type' => 1, // 资产
  1239. 'product' => $product_type, // 场景
  1240. 'parent_id' => $folder_id,
  1241. 'level' => 2,
  1242. 'product_name' => $product_name,
  1243. 'url' => $url,
  1244. 'pic_prompt' => $pic_prompt,
  1245. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1246. 'sort_order' => time(),
  1247. 'is_deleted' => 0,
  1248. 'pic_task_status' => '生成成功',
  1249. 'created_at' => date('Y-m-d H:i:s'),
  1250. 'updated_at' => date('Y-m-d H:i:s')
  1251. ]);
  1252. }
  1253. // 建立或更新绑定关系
  1254. $existing_mapping = DB::table('mp_script_product_mappings')
  1255. ->where('script_id', $script_id)
  1256. ->where('product_id', $product_id)
  1257. ->where('episode_number', $episode_number)
  1258. ->first();
  1259. if (!$existing_mapping) {
  1260. // 创建绑定关系
  1261. DB::table('mp_script_product_mappings')->insert([
  1262. 'script_id' => $script_id,
  1263. 'product_id' => $product_id,
  1264. 'episode_number' => $episode_number,
  1265. 'created_at' => date('Y-m-d H:i:s'),
  1266. 'updated_at' => date('Y-m-d H:i:s')
  1267. ]);
  1268. }
  1269. }
  1270. }
  1271. }
  1272. } catch (\Exception $e) {
  1273. dLog('anime')->error('更新剧集场景失败', [
  1274. 'anime_id' => $anime_id,
  1275. 'episode_id' => $episode_id,
  1276. 'error' => $e->getMessage()
  1277. ]);
  1278. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1279. }
  1280. return true;
  1281. }
  1282. public function changeEpisodeProps($data) {
  1283. $anime_id = getProp($data, 'anime_id');
  1284. $episode_id = getProp($data, 'episode_id');
  1285. $target_props = getProp($data, 'props');
  1286. $is_deleted = getProp($data, 'is_deleted', 0);
  1287. // 参数验证
  1288. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1289. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1290. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1291. // 验证剧集是否存在
  1292. $episode = DB::table('mp_anime_episodes')
  1293. ->where('anime_id', $anime_id)
  1294. ->where('id', $episode_id)
  1295. ->first();
  1296. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1297. $props = json_decode(getProp($episode, 'props'), true);
  1298. // 获取anime信息,检查是否有关联的script_id
  1299. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1300. if (!$anime) Utils::throwError('20003:动漫不存在');
  1301. $script_id = getProp($anime, 'script_id');
  1302. $episode_number = getProp($episode, 'episode_number', 1);
  1303. $uid = Site::getUid();
  1304. $cpid = Site::getCpid();
  1305. try {
  1306. $target_prop_name = getProp($target_props, 'prop');
  1307. // 如果是删除操作
  1308. if ($is_deleted == 1) {
  1309. // 从道具列表中移除该道具
  1310. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1311. return getProp($prop, 'prop') !== $target_prop_name;
  1312. }));
  1313. // 更新道具列表
  1314. $result = DB::table('mp_anime_episodes')
  1315. ->where('anime_id', $anime_id)
  1316. ->where('id', $episode_id)
  1317. ->update([
  1318. 'props' => json_encode($props, 256),
  1319. 'updated_at' => date('Y-m-d H:i:s')
  1320. ]);
  1321. if ($result === false) {
  1322. Utils::throwError('20003:删除道具失败');
  1323. }
  1324. } else {
  1325. // 新增或更新操作
  1326. $prop_found = false;
  1327. $is_new_prop = false;
  1328. // 查找并更新已存在的道具
  1329. foreach($props as &$prop) {
  1330. if (getProp($prop, 'prop') === $target_prop_name) {
  1331. $prop = $target_props;
  1332. $prop_found = true;
  1333. break;
  1334. }
  1335. }
  1336. // 如果道具不存在,则新增
  1337. if (!$prop_found) {
  1338. $props[] = $target_props;
  1339. $is_new_prop = true;
  1340. }
  1341. // 更新道具列表
  1342. $result = DB::table('mp_anime_episodes')
  1343. ->where('anime_id', $anime_id)
  1344. ->where('id', $episode_id)
  1345. ->update([
  1346. 'props' => json_encode($props, 256),
  1347. 'updated_at' => date('Y-m-d H:i:s')
  1348. ]);
  1349. if ($result === false) {
  1350. Utils::throwError('20003:更新道具列表失败');
  1351. }
  1352. // 如果有关联的script_id,则同步到mp_products表
  1353. if ($script_id) {
  1354. // 查询剧本信息
  1355. $script = DB::table('mp_scripts')
  1356. ->where('id', $script_id)
  1357. ->where('is_deleted', 0)
  1358. ->first();
  1359. if ($script) {
  1360. $script_name = $script->script_name ?? 'script_' . $script_id;
  1361. $product_name = getProp($target_props, 'prop');
  1362. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1363. $url = getProp($target_props, 'url', '');
  1364. $product_type = 3; // 3=道具
  1365. // 查找或创建以script_name命名的文件夹
  1366. $folder = DB::table('mp_products')
  1367. ->where('cpid', $cpid)
  1368. ->where('type', 2) // 文件夹类型
  1369. ->where('product', $product_type) // 道具类型
  1370. ->where('product_name', $script_name)
  1371. ->where('parent_id', 0)
  1372. ->where('is_deleted', 0)
  1373. ->first();
  1374. if (!$folder) {
  1375. // 创建文件夹
  1376. $folder_id = DB::table('mp_products')->insertGetId([
  1377. 'user_id' => $uid,
  1378. 'cpid' => $cpid,
  1379. 'type' => 2, // 文件夹
  1380. 'product' => $product_type, // 道具类型
  1381. 'parent_id' => 0,
  1382. 'level' => 1,
  1383. 'product_name' => $script_name,
  1384. 'sort_order' => time(),
  1385. 'is_deleted' => 0,
  1386. 'created_at' => date('Y-m-d H:i:s'),
  1387. 'updated_at' => date('Y-m-d H:i:s')
  1388. ]);
  1389. } else {
  1390. $folder_id = $folder->id;
  1391. }
  1392. // 查找该文件夹下是否已存在同名资产
  1393. $existing_product = DB::table('mp_products')
  1394. ->where('cpid', $cpid)
  1395. ->where('type', 1) // 资产类型
  1396. ->where('product', $product_type)
  1397. ->where('parent_id', $folder_id)
  1398. ->where('product_name', $product_name)
  1399. ->where('is_deleted', 0)
  1400. ->first();
  1401. if ($existing_product) {
  1402. // 更新已存在的资产
  1403. $updateData = [
  1404. 'pic_task_status' => '生成成功'
  1405. ];
  1406. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1407. if ($url) $updateData['url'] = $url;
  1408. // 处理versions字段
  1409. $versions = getProp($target_props, 'versions', []);
  1410. if ($versions && is_array($versions)) {
  1411. $updateData['versions'] = json_encode($versions, 256);
  1412. }
  1413. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1414. DB::table('mp_products')
  1415. ->where('id', $existing_product->id)
  1416. ->update($updateData);
  1417. $product_id = $existing_product->id;
  1418. } else {
  1419. // 创建新资产
  1420. $versions = getProp($target_props, 'versions', []);
  1421. $product_id = DB::table('mp_products')->insertGetId([
  1422. 'user_id' => $uid,
  1423. 'cpid' => $cpid,
  1424. 'type' => 1, // 资产
  1425. 'product' => $product_type, // 道具
  1426. 'parent_id' => $folder_id,
  1427. 'level' => 2,
  1428. 'product_name' => $product_name,
  1429. 'url' => $url,
  1430. 'pic_prompt' => $pic_prompt,
  1431. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1432. 'sort_order' => time(),
  1433. 'is_deleted' => 0,
  1434. 'pic_task_status' => '生成成功',
  1435. 'created_at' => date('Y-m-d H:i:s'),
  1436. 'updated_at' => date('Y-m-d H:i:s')
  1437. ]);
  1438. }
  1439. // 建立或更新绑定关系
  1440. $existing_mapping = DB::table('mp_script_product_mappings')
  1441. ->where('script_id', $script_id)
  1442. ->where('product_id', $product_id)
  1443. ->where('episode_number', $episode_number)
  1444. ->first();
  1445. if (!$existing_mapping) {
  1446. // 创建绑定关系
  1447. DB::table('mp_script_product_mappings')->insert([
  1448. 'script_id' => $script_id,
  1449. 'product_id' => $product_id,
  1450. 'episode_number' => $episode_number,
  1451. 'created_at' => date('Y-m-d H:i:s'),
  1452. 'updated_at' => date('Y-m-d H:i:s')
  1453. ]);
  1454. }
  1455. }
  1456. }
  1457. }
  1458. } catch (\Exception $e) {
  1459. dLog('anime')->error('更新剧集道具失败', [
  1460. 'anime_id' => $anime_id,
  1461. 'episode_id' => $episode_id,
  1462. 'error' => $e->getMessage()
  1463. ]);
  1464. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1465. }
  1466. return true;
  1467. }
  1468. public function editSegment($data) {
  1469. $segment_id = getProp($data, 'segment_id');
  1470. $segment_content = getProp($data, 'segment_content');
  1471. $image_url = getProp($data, 'image_url');
  1472. $video_url = getProp($data, 'video_url');
  1473. // 参数验证
  1474. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1475. // 验证分镜是否存在
  1476. $segment = DB::table('mp_episode_segments')
  1477. ->where('segment_id', $segment_id)
  1478. ->first();
  1479. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1480. $dubTaskId = 0;
  1481. try {
  1482. DB::beginTransaction();
  1483. // 准备更新数据
  1484. $update_data = [
  1485. 'updated_at' => date('Y-m-d H:i:s')
  1486. ];
  1487. if ($segment_content) {
  1488. // 先将segment_content赋值到update_data
  1489. $update_data['segment_content'] = $segment_content;
  1490. // 使用现有方法分析segment_content,提取各个字段
  1491. $this->handleSegmentContent($update_data);
  1492. // 如果有对话内容,创建视频配音合成任务
  1493. $dialogue = getProp($update_data, 'dialogue');
  1494. if (!empty($dialogue)) {
  1495. $now = date('Y-m-d H:i:s');
  1496. $generate_json = [
  1497. 'text' => $dialogue,
  1498. 'role' => getProp($update_data, 'voice_actor'),
  1499. 'voice_type' => getProp($update_data, 'voice_type'),
  1500. 'voice_name' => getProp($update_data, 'voice_name'),
  1501. 'emotion' => getProp($update_data, 'emotion'),
  1502. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1503. 'gender' => getProp($update_data, 'gender'),
  1504. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1505. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1506. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1507. 'pitch' => getProp($update_data, 'pitch', 0),
  1508. ];
  1509. // 插入视频配音合成任务
  1510. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1511. 'alias_segment_id' => $segment_id,
  1512. 'generate_status' => '执行中',
  1513. 'audio_url' => '',
  1514. 'generate_json' => json_encode($generate_json, 256),
  1515. 'created_at' => $now,
  1516. 'updated_at' => $now,
  1517. ]);
  1518. if (!$dubTaskId) {
  1519. Utils::throwError('20003:创建配音任务失败!');
  1520. }
  1521. $update_data['audio_url'] = '';
  1522. } else {
  1523. // dialogue为空时,直接写入默认音频信息
  1524. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1525. $update_data['audio_duration'] = 2.0;
  1526. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1527. }
  1528. }
  1529. if ($image_url) {
  1530. $update_data['img_url'] = $image_url;
  1531. // 同时写入一个简单的图片生成任务
  1532. $pic_task = [
  1533. 'alias_segment_id' => $segment_id,
  1534. 'ref_img_url' => json_encode([]),
  1535. 'status' => 'success',
  1536. 'result_url' => json_encode([$image_url], 256),
  1537. 'model' => '',
  1538. 'created_at' => date('Y-m-d H:i:s'),
  1539. 'updated_at' => date('Y-m-d H:i:s'),
  1540. ];
  1541. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1542. }
  1543. if ($video_url) {
  1544. $update_data['origin_video_url'] = $video_url;
  1545. $compressed_video_url = compressVideo($video_url);
  1546. $update_data['current_type'] = 2;
  1547. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1548. // 同时写入一个简单的视频生成任务
  1549. $video_task = [
  1550. 'alias_segment_id' => $segment_id,
  1551. 'status' => 'success',
  1552. 'result_url' => $update_data['origin_video_url'],
  1553. 'compressed_url' => $update_data['video_url'],
  1554. 'created_at' => date('Y-m-d H:i:s'),
  1555. 'updated_at' => date('Y-m-d H:i:s'),
  1556. ];
  1557. DB::table('mp_generate_video_tasks')->insert($video_task);
  1558. }
  1559. // 更新分镜信息
  1560. $result = DB::table('mp_episode_segments')
  1561. ->where('segment_id', $segment_id)
  1562. ->update($update_data);
  1563. if ($result === false) {
  1564. Utils::throwError('20003:更新分镜剧本失败');
  1565. }
  1566. DB::commit();
  1567. // 如果有创建音频生成任务则调用API
  1568. if ($dubTaskId) {
  1569. // 请求远程服务器执行生成
  1570. $client = new Client(['timeout' => 300, 'verify' => false]);
  1571. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1572. $response = $result->getBody()->getContents();
  1573. $response_arr = json_decode($response, true);
  1574. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1575. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1576. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1577. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1578. Utils::throwError('20003:火山生成音频失败');
  1579. }
  1580. }
  1581. return true;
  1582. } catch (\Exception $e) {
  1583. DB::rollBack();
  1584. dLog('anime')->error('更新分镜剧本失败', [
  1585. 'segment_id' => $segment_id,
  1586. 'error' => $e->getMessage()
  1587. ]);
  1588. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1589. }
  1590. }
  1591. public function batchSetSegmentPics($data) {
  1592. $anime_id = getProp($data, 'anime_id');
  1593. $episode_id = getProp($data, 'episode_id');
  1594. $ratio = getProp($data, 'ratio');
  1595. $dimensions = $this->getRatioDimensions($ratio);
  1596. $width = $dimensions['width'];
  1597. $height = $dimensions['height'];
  1598. if (!$anime_id || !$episode_id) {
  1599. Utils::throwError('1002:请选择剧集');
  1600. }
  1601. // 获取剧集信息
  1602. $episode = DB::table('mp_anime_episodes')
  1603. ->where('anime_id', $anime_id)
  1604. ->where('id', $episode_id)
  1605. ->where('is_default', 1)
  1606. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1607. ->first();
  1608. if (!$episode) {
  1609. Utils::throwError('20003:该剧集不存在');
  1610. }
  1611. $model = getProp($data, 'model');
  1612. if (!$model) {
  1613. $model = getProp($episode, 'image_model');
  1614. if (!$model) {
  1615. // episode表也没有,使用默认值
  1616. $model = 'doubao-seedream-5-0-lite-260128';
  1617. }
  1618. }
  1619. // 验证模型是否在可用模型表中
  1620. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1621. $model = 'doubao-seedream-5-0-lite-260128';
  1622. }
  1623. $roles = json_decode(getProp($episode, 'roles'), true);
  1624. if (!$roles) {
  1625. Utils::throwError('20003:角色信息格式错误');
  1626. }
  1627. // 构建角色名称到参考图的映射
  1628. $role_map = [];
  1629. foreach ($roles as $role) {
  1630. $role_name = getProp($role, 'role');
  1631. $role_url = getProp($role, 'url');
  1632. if (!empty($role_name) && !empty($role_url)) {
  1633. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1634. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1635. // $role_map[$base_name] = $role_url;
  1636. // 同时保存完整名称的映射
  1637. $role_map[$role_name] = $role_url;
  1638. }
  1639. }
  1640. $scenes = json_decode(getProp($episode, 'roles'), true);
  1641. if (!$scenes) {
  1642. Utils::throwError('20003:场景信息格式错误');
  1643. }
  1644. // 构建角色名称到参考图的映射
  1645. $scene_map = [];
  1646. foreach ($scenes as $scene) {
  1647. $scene_name = getProp($scene, 'scene');
  1648. $scene_url = getProp($scene, 'url');
  1649. if (!empty($scene_name) && !empty($scene_url)) {
  1650. $scene_map[$scene_name] = $scene_url;
  1651. }
  1652. }
  1653. // 获取所有分镜信息
  1654. $segments = DB::table('mp_episode_segments')
  1655. ->where('anime_id', $anime_id)
  1656. ->where('episode_id', $episode_id)
  1657. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1658. ->orderBy('segment_number')
  1659. ->get()
  1660. ->toArray();
  1661. if (empty($segments)) {
  1662. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1663. }
  1664. // 保存图片比例
  1665. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1666. $updated_segments = [];
  1667. $failed_segments = [];
  1668. // 批量为每个分镜生成图片任务
  1669. foreach ($segments as $segment) {
  1670. $segment_id = $segment->segment_id;
  1671. $segment_content = $segment->segment_content;
  1672. if (empty($segment_content)) {
  1673. $failed_segments[] = [
  1674. 'segment_id' => $segment_id,
  1675. 'error' => '分镜内容为空'
  1676. ];
  1677. continue;
  1678. }
  1679. try {
  1680. $dubTaskId = 0;
  1681. // 解析分镜内容,提取画面描述作为主要提示词
  1682. $prompt = $segment_content;
  1683. $ref_img_urls = [];
  1684. // 分镜场景
  1685. $scene = getProp($segment, 'scene');
  1686. $matched_scene = '';
  1687. if (isset($scene_map[$scene])) {
  1688. $img_index = count($ref_img_urls) + 1;
  1689. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1690. $ref_img_urls[] = $scene_map[$scene];
  1691. $matched_scene = $scene;
  1692. }
  1693. // 分镜角色
  1694. $characters = getProp($segment, 'characters');
  1695. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1696. $roles = explode(',', $characters);
  1697. // 从分镜内容中提取涉及的角色
  1698. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1699. // 获取匹配角色的参考图
  1700. foreach ($segment_characters as $character) {
  1701. if (isset($role_map[$character])) {
  1702. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1703. $img_index = count($ref_img_urls) + 1;
  1704. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1705. $ref_img_urls[] = $role_map[$character];
  1706. }
  1707. }
  1708. // 如果没有找到匹配的角色参考图,不使用参考图
  1709. if (empty($ref_img_urls)) {
  1710. $ref_img_urls = [];
  1711. }
  1712. // 准备生成任务参数
  1713. $params = [
  1714. 'model' => $model,
  1715. 'alias_segment_id' => $segment_id,
  1716. 'prompt' => $prompt,
  1717. 'ref_img_urls' => $ref_img_urls,
  1718. 'width' => $width,
  1719. 'height' => $height,
  1720. ];
  1721. // 优化提示词(不要生成字幕)
  1722. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1723. // $task_id = mt_rand(100000, 999999);
  1724. // 调用AI图片生成服务
  1725. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1726. $task_id = $task->id;
  1727. if (!$task_id) {
  1728. $failed_segments[] = [
  1729. 'segment_id' => $segment_id,
  1730. 'error' => '创建生成任务失败'
  1731. ];
  1732. continue;
  1733. }
  1734. $update_data = [
  1735. 'pic_task_id' => $task_id,
  1736. 'pic_task_status' => '生成中',
  1737. 'audio_url' => '',
  1738. 'updated_at' => date('Y-m-d H:i:s')
  1739. ];
  1740. // 如果有对话内容,创建视频配音合成任务
  1741. $dialogue = getProp($segment, 'dialogue');
  1742. if (!empty($dialogue)) {
  1743. $now = date('Y-m-d H:i:s');
  1744. $generate_json = [
  1745. 'text' => $dialogue,
  1746. 'role' => getProp($segment, 'voice_actor'),
  1747. 'voice_type' => getProp($segment, 'voice_type'),
  1748. 'voice_name' => getProp($segment, 'voice_name'),
  1749. 'emotion' => getProp($segment, 'emotion'),
  1750. 'emotion_type' => getProp($segment, 'emotion_type'),
  1751. 'gender' => getProp($segment, 'gender'),
  1752. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1753. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1754. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1755. 'pitch' => getProp($segment, 'pitch', 0),
  1756. ];
  1757. // 插入视频配音合成任务
  1758. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1759. 'alias_segment_id' => $segment_id,
  1760. 'generate_status' => '执行中',
  1761. 'audio_url' => '',
  1762. 'generate_json' => json_encode($generate_json, 256),
  1763. 'created_at' => $now,
  1764. 'updated_at' => $now,
  1765. ]);
  1766. if (!$dubTaskId) {
  1767. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1768. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1769. // Utils::throwError('20003:创建配音任务失败!');
  1770. }
  1771. } else {
  1772. // dialogue为空时,直接写入默认音频信息到分镜表
  1773. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1774. $update_data['audio_duration'] = 2.0;
  1775. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1776. }
  1777. // 更新分镜的任务信息
  1778. $update_result = DB::table('mp_episode_segments')
  1779. ->where('segment_id', $segment_id)
  1780. ->update($update_data);
  1781. // 如果是第一集的首帧图片,则存入待更新数组
  1782. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1783. Redis::sadd('anime_first_frame_urls', $segment_id);
  1784. }
  1785. if ($update_result) {
  1786. $updated_segments[] = [
  1787. 'segment_id' => $segment_id,
  1788. 'task_id' => $task_id,
  1789. 'status' => '生成中',
  1790. 'matched_scenes' => $matched_scene,
  1791. 'matched_roles' => $segment_characters,
  1792. 'ref_urls_count' => count($ref_img_urls)
  1793. ];
  1794. } else {
  1795. $failed_segments[] = [
  1796. 'segment_id' => $segment_id,
  1797. 'error' => '更新分镜任务状态失败'
  1798. ];
  1799. }
  1800. if ($dubTaskId) {
  1801. sleep(1);
  1802. // 请求远程服务器执行生成
  1803. $client = new Client(['timeout' => 300, 'verify' => false]);
  1804. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1805. $response = $result->getBody()->getContents();
  1806. $response_arr = json_decode($response, true);
  1807. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1808. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1809. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1810. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1811. }
  1812. }
  1813. } catch (\Exception $e) {
  1814. $failed_segments[] = [
  1815. 'segment_id' => $segment_id,
  1816. 'error' => $e->getMessage()
  1817. ];
  1818. }
  1819. }
  1820. // 更新剧集生成状态
  1821. if (!empty($updated_segments)) {
  1822. DB::table('mp_anime_episodes')
  1823. ->where('id', $episode_id)
  1824. ->update([
  1825. 'is_generated' => 1,
  1826. 'updated_at' => date('Y-m-d H:i:s')
  1827. ]);
  1828. }
  1829. return [
  1830. 'success_count' => count($updated_segments),
  1831. 'failed_count' => count($failed_segments),
  1832. 'success_segments' => $updated_segments,
  1833. 'failed_segments' => $failed_segments,
  1834. 'total_segments' => count($segments)
  1835. ];
  1836. }
  1837. public function reGenerateSegment($data) {
  1838. $segment_id = getProp($data, 'segment_id');
  1839. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1840. $anime_id = getProp($segment, 'anime_id');
  1841. $episode_id = getProp($segment, 'episode_id');
  1842. $episode_number = getProp($segment, 'episode_number');
  1843. $segment_content = getProp($data, 'segment_content');
  1844. $ratio = getProp($data, 'ratio');
  1845. if (!$ratio) {
  1846. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1847. if (!$ratio) $ratio = '9:16';
  1848. }
  1849. $dimensions = $this->getRatioDimensions($ratio);
  1850. $width = $dimensions['width'];
  1851. $height = $dimensions['height'];
  1852. if (!$anime_id || !$episode_id) {
  1853. Utils::throwError('1002:请选择分镜');
  1854. }
  1855. // 使用文生文模型重新解析segment_content
  1856. if (!empty($segment_content)) {
  1857. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1858. }
  1859. // 获取动漫的角色信息(包含参考图)
  1860. $anime = DB::table('mp_animes')
  1861. ->where('id', $anime_id)
  1862. ->select('roles', 'scenes')
  1863. ->first();
  1864. if (!$anime || !$anime->roles) {
  1865. Utils::throwError('20003:未找到角色信息');
  1866. }
  1867. $roles = json_decode($anime->roles, true);
  1868. if (!$roles) {
  1869. Utils::throwError('20003:角色信息格式错误');
  1870. }
  1871. // 构建角色名称到参考图的映射
  1872. $role_map = [];
  1873. foreach ($roles as $role) {
  1874. $role_name = getProp($role, 'role');
  1875. $role_url = getProp($role, 'url');
  1876. if (!empty($role_name) && !empty($role_url)) {
  1877. $role_map[$role_name] = $role_url;
  1878. }
  1879. }
  1880. $scenes = json_decode($anime->scenes, true);
  1881. if (!$scenes) {
  1882. Utils::throwError('20003:角色信息格式错误');
  1883. }
  1884. // 构建角色名称到参考图的映射
  1885. $scene_map = [];
  1886. foreach ($scenes as $scene) {
  1887. $scene_name = getProp($scene, 'scene');
  1888. $scene_url = getProp($scene, 'url');
  1889. if (!empty($scene_name) && !empty($scene_url)) {
  1890. $scene_map[$scene_name] = $scene_url;
  1891. }
  1892. }
  1893. $segment_id = $segment->segment_id;
  1894. $original_segment_content = $segment->segment_content;
  1895. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1896. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1897. if (empty($final_segment_content)) {
  1898. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1899. }
  1900. try {
  1901. $dubTaskId = 0;
  1902. // 分镜剧本数组
  1903. $update_data = [
  1904. 'segment_content' => $final_segment_content,
  1905. 'pic_task_status' => '生成中',
  1906. 'updated_at' => date('Y-m-d H:i:s')
  1907. ];
  1908. // 解析分镜内容,提取画面描述作为主要提示词
  1909. $prompt = $final_segment_content;
  1910. $ref_img_urls = [];
  1911. // 分镜场景
  1912. $scene = getProp($data, 'scene');
  1913. if ($scene) {
  1914. $matched_scene = '';
  1915. if (isset($scene_map[$scene])) {
  1916. $img_index = count($ref_img_urls) + 1;
  1917. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1918. $ref_img_urls[] = $scene_map[$scene];
  1919. $matched_scene = $scene;
  1920. }
  1921. $update_data['scene'] = $scene;
  1922. }
  1923. // 分镜角色
  1924. $characters = getProp($data, 'characters');
  1925. if ($characters) {
  1926. $update_data['characters'] = $characters;
  1927. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1928. $characters = explode(',', $characters);
  1929. // 从分镜内容中提取涉及的角色
  1930. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1931. // 获取匹配角色的参考图
  1932. foreach ($segment_characters as $character) {
  1933. if (isset($role_map[$character])) {
  1934. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1935. $img_index = count($ref_img_urls) + 1;
  1936. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1937. $ref_img_urls[] = $role_map[$character];
  1938. }
  1939. }
  1940. }
  1941. // 如果没有找到匹配的角色参考图,不使用参考图
  1942. if (empty($ref_img_urls)) {
  1943. $ref_img_urls = [];
  1944. }
  1945. // 准备生成任务参数
  1946. $params = [
  1947. 'alias_segment_id' => $segment_id,
  1948. 'prompt' => $prompt,
  1949. 'ref_img_urls' => $ref_img_urls,
  1950. 'width' => $width,
  1951. 'height' => $height,
  1952. ];
  1953. // 优化提示词(不要生成字幕)
  1954. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1955. // 调用AI图片生成服务
  1956. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1957. $task_id = $task->id;
  1958. if (!$task_id) {
  1959. Utils::throwError('20003:创建生成任务失败!');
  1960. }
  1961. $update_data['pic_task_id'] = $task_id;
  1962. // 更新分镜剧本信息
  1963. $this->handleSegmentContent($update_data);
  1964. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1965. if ($segment_content) {
  1966. $dialogue = getProp($update_data, 'dialogue');
  1967. if (!empty($dialogue)) {
  1968. $now = date('Y-m-d H:i:s');
  1969. $generate_json = [
  1970. 'text' => $dialogue,
  1971. 'role' => getProp($update_data, 'voice_actor'),
  1972. 'voice_type' => getProp($update_data, 'voice_type'),
  1973. 'voice_name' => getProp($update_data, 'voice_name'),
  1974. 'emotion' => getProp($update_data, 'emotion'),
  1975. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1976. 'gender' => getProp($update_data, 'gender'),
  1977. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1978. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1979. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1980. 'pitch' => getProp($update_data, 'pitch', 0),
  1981. ];
  1982. // 插入视频配音合成任务
  1983. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1984. 'alias_segment_id' => $segment_id,
  1985. 'generate_status' => '执行中',
  1986. 'audio_url' => '',
  1987. 'generate_json' => json_encode($generate_json, 256),
  1988. 'created_at' => date('Y-m-d H:i:s'),
  1989. 'updated_at' => date('Y-m-d H:i:s'),
  1990. ]);
  1991. if (!$dubTaskId) {
  1992. Utils::throwError('20003:创建配音任务失败!');
  1993. }
  1994. $update_data['audio_url'] = '';
  1995. } else {
  1996. // dialogue为空时,直接写入默认音频信息
  1997. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1998. $update_data['audio_duration'] = 2.0;
  1999. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2000. }
  2001. }
  2002. $boolen = DB::table('mp_episode_segments')
  2003. ->where('segment_id', $segment_id)
  2004. ->update($update_data);
  2005. // 如果是第一集的首帧图片,则存入待更新数组
  2006. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2007. Redis::sadd('anime_first_frame_urls', $segment_id);
  2008. }
  2009. if ($dubTaskId) {
  2010. // 请求远程服务器执行生成
  2011. $client = new Client(['timeout' => 300, 'verify' => false]);
  2012. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2013. $response = $result->getBody()->getContents();
  2014. $response_arr = json_decode($response, true);
  2015. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2016. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2017. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2018. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2019. Utils::throwError('20003:火山生成音频失败');
  2020. }
  2021. }
  2022. } catch (\Exception $e) {
  2023. $failed_segments[] = [
  2024. 'segment_id' => $segment_id,
  2025. 'error' => $e->getMessage()
  2026. ];
  2027. }
  2028. // 创建任务之后先暂停10s等待异步任务完成
  2029. sleep(10);
  2030. $img_url = $this->loopGetPicTaskResult($task_id);
  2031. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2032. // 图片生成后新增对话记录
  2033. try {
  2034. $uid = Site::getUid();
  2035. $now = date('Y-m-d H:i:s');
  2036. // 使用AI反推图片提示词
  2037. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2038. // 保存对话记录
  2039. $records = [
  2040. [
  2041. 'uid' => $uid,
  2042. 'anime_id' => $anime_id,
  2043. 'sequence' => $episode_number,
  2044. 'role' => 'user',
  2045. 'content' => '重新生成',
  2046. 'segment_id' => $segment_id,
  2047. 'image_url' => '',
  2048. 'created_at' => $now,
  2049. 'updated_at' => $now
  2050. ],
  2051. [
  2052. 'uid' => $uid,
  2053. 'anime_id' => $anime_id,
  2054. 'sequence' => $episode_number,
  2055. 'role' => 'assistant',
  2056. 'content' => $pic_prompt,
  2057. 'segment_id' => $segment_id,
  2058. 'image_url' => $img_url,
  2059. 'created_at' => $now,
  2060. 'updated_at' => $now
  2061. ]
  2062. ];
  2063. DB::table('mp_anime_records')->insert($records);
  2064. } catch (\Exception $e) {
  2065. // 记录日志但不影响主流程
  2066. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2067. 'segment_id' => $segment_id,
  2068. 'img_url' => $img_url
  2069. ]);
  2070. }
  2071. return $img_url;
  2072. }
  2073. public function addSegment($data) {
  2074. $prev_segment_id = getProp($data, 'prev_segment_id');
  2075. $img_url = getProp($data, 'img_url');
  2076. $video_url = getProp($data, 'video_url');
  2077. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2078. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2079. $anime_id = getProp($segment, 'anime_id');
  2080. $episode_id = getProp($segment, 'episode_id');
  2081. $episode_number = getProp($segment, 'episode_number');
  2082. $segment_number = getProp($segment, 'segment_number');
  2083. $new_segment_number = $segment_number + 1;
  2084. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2085. // 分镜剧本数组
  2086. $insert_data = [
  2087. 'anime_id' => $anime_id,
  2088. 'episode_id' => $episode_id,
  2089. 'episode_number' => $episode_number,
  2090. 'act_number' => getProp($segment, 'act_number'),
  2091. 'act_title' => getProp($segment, 'act_title'),
  2092. 'segment_id' => $segment_id,
  2093. 'segment_number' => $new_segment_number,
  2094. 'segment_content' => '',
  2095. 'img_url' => '',
  2096. 'video_url' => '',
  2097. 'created_at' => date('Y-m-d H:i:s'),
  2098. 'updated_at' => date('Y-m-d H:i:s')
  2099. ];
  2100. if ($img_url) $insert_data['img_url'] = $img_url;
  2101. if ($video_url) {
  2102. $insert_data['origin_video_url'] = $video_url;
  2103. $insert_data['current_type'] = 2;
  2104. $compressed_video_url = compressVideo($video_url);
  2105. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2106. }
  2107. try {
  2108. DB::beginTransaction();
  2109. // 先更新序号
  2110. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2111. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2112. if (!$id) {
  2113. Utils::throwError('20003:新增分镜失败!');
  2114. }
  2115. }catch (\Exception $e) {
  2116. DB::rollBack();
  2117. Utils::throwError('20003:'.$e->getMessage());
  2118. }
  2119. DB::commit();
  2120. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2121. $segment = $segment ? (array)$segment : [];
  2122. return $segment;
  2123. // 以下代码暂弃用
  2124. $anime_id = getProp($segment, 'anime_id');
  2125. $episode_id = getProp($segment, 'episode_id');
  2126. $episode_number = getProp($segment, 'episode_number');
  2127. $segment_number = getProp($segment, 'segment_number');
  2128. $segment_content = getProp($data, 'segment_content');
  2129. $img_url = getProp($data, 'img_url');
  2130. $video_url = getProp($data, 'video_url');
  2131. $ratio = getProp($data, 'ratio');
  2132. $dimensions = $this->getRatioDimensions($ratio);
  2133. $width = $dimensions['width'];
  2134. $height = $dimensions['height'];
  2135. if (!$anime_id || !$episode_id) {
  2136. Utils::throwError('1002:请选择分镜');
  2137. }
  2138. // 使用文生文模型重新解析segment_content
  2139. if (!empty($segment_content)) {
  2140. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2141. }
  2142. // 获取动漫的角色信息(包含参考图)
  2143. $anime = DB::table('mp_animes')
  2144. ->where('id', $anime_id)
  2145. ->select('roles', 'scenes')
  2146. ->first();
  2147. if (!$anime || !$anime->roles) {
  2148. Utils::throwError('20003:未找到角色信息');
  2149. }
  2150. $roles = json_decode($anime->roles, true);
  2151. if (!$roles) {
  2152. Utils::throwError('20003:角色信息格式错误');
  2153. }
  2154. // 构建角色名称到参考图的映射
  2155. $role_map = [];
  2156. foreach ($roles as $role) {
  2157. $role_name = getProp($role, 'role');
  2158. $role_url = getProp($role, 'url');
  2159. if (!empty($role_name) && !empty($role_url)) {
  2160. $role_map[$role_name] = $role_url;
  2161. }
  2162. }
  2163. $scenes = json_decode($anime->scenes, true);
  2164. if (!$scenes) {
  2165. Utils::throwError('20003:角色信息格式错误');
  2166. }
  2167. // 构建角色名称到参考图的映射
  2168. $scene_map = [];
  2169. foreach ($scenes as $scene) {
  2170. $scene_name = getProp($scene, 'scene');
  2171. $scene_url = getProp($scene, 'url');
  2172. if (!empty($scene_name) && !empty($scene_url)) {
  2173. $scene_map[$scene_name] = $scene_url;
  2174. }
  2175. }
  2176. $segment_id = $segment->segment_id;
  2177. $original_segment_content = $segment->segment_content;
  2178. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2179. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2180. if (empty($final_segment_content)) {
  2181. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2182. }
  2183. try {
  2184. $dubTaskId = 0;
  2185. DB::beginTransaction();
  2186. $new_segment_number = $segment_number + 1;
  2187. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2188. // 分镜剧本数组
  2189. $insert_data = [
  2190. 'anime_id' => $anime_id,
  2191. 'episode_id' => $episode_id,
  2192. 'episode_number' => $episode_number,
  2193. 'act_number' => getProp($segment, 'act_number'),
  2194. 'act_title' => getProp($segment, 'act_title'),
  2195. 'segment_id' => $segment_id,
  2196. 'segment_number' => $new_segment_number,
  2197. 'segment_content' => $final_segment_content,
  2198. 'img_url' => $img_url,
  2199. 'video_url' => $video_url,
  2200. 'created_at' => date('Y-m-d H:i:s'),
  2201. 'updated_at' => date('Y-m-d H:i:s')
  2202. ];
  2203. // 更新分镜剧本信息
  2204. $this->handleSegmentContent($insert_data);
  2205. // 如果有对话内容,创建视频配音合成任务
  2206. $dialogue = getProp($insert_data, 'dialogue');
  2207. if (!empty($dialogue)) {
  2208. $now = date('Y-m-d H:i:s');
  2209. $generate_json = [
  2210. 'text' => $dialogue,
  2211. 'role' => getProp($insert_data, 'voice_actor'),
  2212. 'voice_type' => getProp($insert_data, 'voice_type'),
  2213. 'voice_name' => getProp($insert_data, 'voice_name'),
  2214. 'emotion' => getProp($insert_data, 'emotion'),
  2215. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2216. 'gender' => getProp($insert_data, 'gender'),
  2217. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2218. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2219. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2220. 'pitch' => getProp($insert_data, 'pitch', 0),
  2221. ];
  2222. // 插入视频配音合成任务
  2223. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2224. 'alias_segment_id' => $segment_id,
  2225. 'generate_status' => '执行中',
  2226. 'audio_url' => '',
  2227. 'generate_json' => json_encode($generate_json, 256),
  2228. 'created_at' => $now,
  2229. 'updated_at' => $now,
  2230. ]);
  2231. if (!$dubTaskId) {
  2232. Utils::throwError('20003:创建配音任务失败!');
  2233. }
  2234. $insert_data['audio_url'] = '';
  2235. } else {
  2236. // dialogue为空时,直接写入默认音频信息
  2237. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2238. $insert_data['audio_duration'] = 2.0;
  2239. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2240. }
  2241. // 如果没有上传图片则使用当前描述进行生成
  2242. if (!$img_url) {
  2243. // 解析分镜内容,提取画面描述作为主要提示词
  2244. $prompt = $final_segment_content;
  2245. $ref_img_urls = [];
  2246. // 分镜场景
  2247. $scene = getProp($insert_data, 'scene');
  2248. if ($scene) {
  2249. $matched_scene = '';
  2250. if (isset($scene_map[$scene])) {
  2251. $img_index = count($ref_img_urls) + 1;
  2252. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2253. $ref_img_urls[] = $scene_map[$scene];
  2254. $matched_scene = $scene;
  2255. }
  2256. $update_data['scene'] = $scene;
  2257. }
  2258. // 分镜角色
  2259. $characters = getProp($insert_data, 'characters');
  2260. if ($characters) {
  2261. $update_data['characters'] = $characters;
  2262. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2263. $characters = explode(',', $characters);
  2264. // 从分镜内容中提取涉及的角色
  2265. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2266. // 获取匹配角色的参考图
  2267. foreach ($segment_characters as $character) {
  2268. if (isset($role_map[$character])) {
  2269. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2270. $img_index = count($ref_img_urls) + 1;
  2271. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2272. $ref_img_urls[] = $role_map[$character];
  2273. }
  2274. }
  2275. }
  2276. // 如果没有找到匹配的角色参考图,不使用参考图
  2277. if (empty($ref_img_urls)) {
  2278. $ref_img_urls = [];
  2279. }
  2280. // 准备生成任务参数
  2281. $params = [
  2282. 'alias_segment_id' => $segment_id,
  2283. 'prompt' => $prompt,
  2284. 'ref_img_urls' => $ref_img_urls,
  2285. 'width' => $width,
  2286. 'height' => $height,
  2287. ];
  2288. // 调用AI图片生成服务
  2289. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2290. $task_id = $task->id;
  2291. // $task_id = 'whatever';
  2292. if (!$task_id) {
  2293. Utils::throwError('20003:创建生成任务失败!');
  2294. }
  2295. $insert_data['pic_task_status'] = '生成中';
  2296. $insert_data['pic_task_id'] = $task_id;
  2297. }
  2298. // 先更新序号
  2299. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2300. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2301. if (!$boolen) {
  2302. Utils::throwError('20003:新增分镜失败!');
  2303. }
  2304. // 如果是第一集的首帧图片,则存入待更新数组
  2305. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2306. Redis::sadd('anime_first_frame_urls', $segment_id);
  2307. }
  2308. if ($dubTaskId) {
  2309. // 请求远程服务器执行生成
  2310. $client = new Client(['timeout' => 300, 'verify' => false]);
  2311. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2312. $response = $result->getBody()->getContents();
  2313. $response_arr = json_decode($response, true);
  2314. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2315. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2316. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2317. Utils::throwError('20003:火山生成音频失败');
  2318. }
  2319. }
  2320. } catch (\Exception $e) {
  2321. DB::rollBack();
  2322. Utils::throwError('20003:'.$e->getMessage());
  2323. }
  2324. DB::commit();
  2325. // 创建任务之后先暂停10s等待异步任务完成
  2326. sleep(10);
  2327. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2328. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2329. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2330. $segment = $segment ? (array)$segment : [];
  2331. return $segment;
  2332. }
  2333. public function copySegment($data) {
  2334. $segment_id = getProp($data, 'segment_id');
  2335. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2336. if (!$segment) Utils::throwError('20003:请选择分镜');
  2337. $anime_id = getProp($segment, 'anime_id');
  2338. $episode_id = getProp($segment, 'episode_id');
  2339. $episode_number = getProp($segment, 'episode_number');
  2340. $segment_number = getProp($segment, 'segment_number');
  2341. $new_segment_id = 0;
  2342. try {
  2343. DB::beginTransaction();
  2344. $segment = (array)$segment;
  2345. unset($segment['id']);
  2346. $segment['segment_number'] += 1;
  2347. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2348. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2349. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2350. // 更新其他分镜序号
  2351. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2352. // 复制分镜
  2353. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2354. if (!$id) {
  2355. Utils::throwError('20003:复制分镜失败');
  2356. }
  2357. }catch (\Exception $e) {
  2358. DB::rollBack();
  2359. Utils::throwError('20003:'.$e->getMessage());
  2360. }
  2361. DB::commit();
  2362. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2363. $segment = $segment ? (array)$segment : [];
  2364. return $segment;
  2365. }
  2366. public function moveSegment($data) {
  2367. $segment_id = getProp($data, 'segment_id');
  2368. $target_segment_id = getProp($data, 'target_segment_id');
  2369. // 获取源分镜信息
  2370. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2371. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2372. // 获取目标分镜信息
  2373. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2374. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2375. $anime_id = getProp($source_segment, 'anime_id');
  2376. $episode_id = getProp($source_segment, 'episode_id');
  2377. $episode_number = getProp($source_segment, 'episode_number');
  2378. $source_segment_number = getProp($source_segment, 'segment_number');
  2379. $target_segment_number = getProp($target_segment, 'segment_number');
  2380. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2381. $target_anime_id = getProp($target_segment, 'anime_id');
  2382. $target_episode_number = getProp($target_segment, 'episode_number');
  2383. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2384. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2385. }
  2386. // 如果源分镜和目标分镜相同,无需移动
  2387. if ($source_segment_number == $target_segment_number) {
  2388. return true;
  2389. }
  2390. try {
  2391. DB::beginTransaction();
  2392. if ($source_segment_number < $target_segment_number) {
  2393. // 向后移动:源分镜移动到目标分镜之后
  2394. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2395. DB::table('mp_episode_segments')
  2396. ->where('anime_id', $anime_id)
  2397. ->where('episode_id', $episode_id)
  2398. ->where('segment_number', '>', $source_segment_number)
  2399. ->where('segment_number', '<=', $target_segment_number)
  2400. ->decrement('segment_number');
  2401. // 2. 将源分镜移动到目标分镜之后
  2402. $new_segment_number = $target_segment_number;
  2403. } else {
  2404. // 向前移动:源分镜移动到目标分镜之后
  2405. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2406. DB::table('mp_episode_segments')
  2407. ->where('anime_id', $anime_id)
  2408. ->where('episode_id', $episode_id)
  2409. ->where('segment_number', '>', $target_segment_number)
  2410. ->where('segment_number', '<', $source_segment_number)
  2411. ->increment('segment_number');
  2412. // 2. 将源分镜移动到目标分镜之后
  2413. $new_segment_number = $target_segment_number + 1;
  2414. }
  2415. // 3. 更新源分镜的序号
  2416. $update_result = DB::table('mp_episode_segments')
  2417. ->where('segment_id', $segment_id)
  2418. ->update([
  2419. 'segment_number' => $new_segment_number,
  2420. 'updated_at' => date('Y-m-d H:i:s')
  2421. ]);
  2422. if (!$update_result) {
  2423. Utils::throwError('20003:更新分镜序号失败');
  2424. }
  2425. DB::commit();
  2426. return true;
  2427. } catch (\Exception $e) {
  2428. DB::rollBack();
  2429. Utils::throwError('20003:' . $e->getMessage());
  2430. }
  2431. }
  2432. public function delSegment($data) {
  2433. $segment_id = getProp($data, 'segment_id');
  2434. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2435. if (!$segment) Utils::throwError('20003:请选择分镜');
  2436. $anime_id = getProp($segment, 'anime_id');
  2437. $episode_id = getProp($segment, 'episode_id');
  2438. $episode_number = getProp($segment, 'episode_number');
  2439. $segment_number = getProp($segment, 'segment_number');
  2440. try {
  2441. DB::beginTransaction();
  2442. // 删除分镜
  2443. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2444. if (!$boolen) {
  2445. Utils::throwError('20003:删除分镜失败');
  2446. }
  2447. // 更新其他分镜序号
  2448. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2449. }catch (\Exception $e) {
  2450. DB::rollBack();
  2451. Utils::throwError('20003:'.$e->getMessage());
  2452. }
  2453. DB::commit();
  2454. return true;
  2455. }
  2456. public function applySegment($data) {
  2457. $segment_id = getProp($data, 'segment_id');
  2458. $url = getProp($data, 'url');
  2459. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2460. if (!$url) Utils::throwError('20003:URL不能为空');
  2461. // 获取URL的文件扩展名
  2462. $urlPath = parse_url($url, PHP_URL_PATH);
  2463. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2464. // 定义图片和视频的扩展名
  2465. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2466. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2467. // 判断是图片还是视频
  2468. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2469. if (in_array($extension, $imageExtensions)) {
  2470. // 图片类型
  2471. $updateData['img_url'] = $url;
  2472. $updateData['current_type'] = 1;
  2473. } elseif (in_array($extension, $videoExtensions)) {
  2474. // 视频类型
  2475. $updateData['video_url'] = $url;
  2476. $updateData['current_type'] = 2;
  2477. } else {
  2478. Utils::throwError('20003:不支持的文件类型');
  2479. }
  2480. // 更新分镜表
  2481. $result = DB::table('mp_episode_segments')
  2482. ->where('segment_id', $segment_id)
  2483. ->update($updateData);
  2484. if (!$result) {
  2485. Utils::throwError('20003:更新分镜失败');
  2486. }
  2487. return true;
  2488. }
  2489. public function segmentHistory($data) {
  2490. $segment_id = getProp($data, 'segment_id');
  2491. // 获取历史图片
  2492. $pics = [];
  2493. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2494. foreach($pic_history as $task) {
  2495. $result_url = getProp($task, 'result_url');
  2496. if (is_json($result_url)) {
  2497. $pics = array_merge($pics, json_decode($result_url, true));
  2498. }else {
  2499. $pics[] = $result_url;
  2500. }
  2501. }
  2502. // 获取历史视频
  2503. $videos = [];
  2504. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2505. foreach($video_history as $task) {
  2506. $result_url = getProp($task, 'result_url');
  2507. if (is_json($result_url)) {
  2508. $videos = array_merge($videos, json_decode($result_url, true));
  2509. }else {
  2510. $videos[] = $result_url;
  2511. }
  2512. }
  2513. return compact('pics', 'videos');
  2514. }
  2515. public function addAct($data) {
  2516. $prev_act_id = getProp($data, 'prev_act_id');
  2517. $act_title = getProp($data, 'act_title', '');
  2518. $act_content = getProp($data, 'act_content', '');
  2519. $act_duration = getProp($data, 'act_duration', 5);
  2520. $video_url = getProp($data, 'video_url');
  2521. // 根据prev_act_id获取记录
  2522. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2523. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2524. $anime_id = getProp($prev_segment, 'anime_id');
  2525. $episode_id = getProp($prev_segment, 'episode_id');
  2526. $episode_number = getProp($prev_segment, 'episode_number');
  2527. $prev_act_number = getProp($prev_segment, 'act_number');
  2528. // 获取新的act_number
  2529. $new_act_number = $prev_act_number + 1;
  2530. try {
  2531. DB::beginTransaction();
  2532. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2533. DB::table('mp_episode_segments')
  2534. ->where('anime_id', $anime_id)
  2535. ->where('episode_id', $episode_id)
  2536. ->where('act_number', '>', $prev_act_number)
  2537. ->increment('act_number');
  2538. // 插入新片段记录
  2539. $insert_data = [
  2540. 'anime_id' => $anime_id,
  2541. 'episode_id' => $episode_id,
  2542. 'episode_number' => $episode_number,
  2543. 'act_number' => $new_act_number,
  2544. 'created_at' => date('Y-m-d H:i:s'),
  2545. 'updated_at' => date('Y-m-d H:i:s')
  2546. ];
  2547. if ($act_title) {
  2548. $insert_data['act_title'] = $act_title;
  2549. }
  2550. if ($act_content) {
  2551. $insert_data['act_content'] = $act_content;
  2552. }
  2553. if ($act_duration) {
  2554. $insert_data['act_duration'] = $act_duration;
  2555. }
  2556. if ($video_url) {
  2557. $insert_data['origin_video_url'] = $video_url;
  2558. $insert_data['current_type'] = 2;
  2559. $compressed_video_url = compressVideo($video_url);
  2560. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2561. }
  2562. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2563. if (!$id) {
  2564. Utils::throwError('20003:新增片段失败!');
  2565. }
  2566. DB::commit();
  2567. }catch (\Exception $e) {
  2568. DB::rollBack();
  2569. Utils::throwError('20003:'.$e->getMessage());
  2570. }
  2571. $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();
  2572. $segment = $segment ? (array)$segment : [];
  2573. return $segment;
  2574. }
  2575. public function editAct($data) {
  2576. $act_id = getProp($data, 'act_id');
  2577. $act_content = getProp($data, 'act_content');
  2578. $act_duration = getProp($data, 'act_duration');
  2579. $act_title = getProp($data, 'act_title');
  2580. $image_url = getProp($data, 'image_url');
  2581. $video_url = getProp($data, 'video_url');
  2582. // 参数验证
  2583. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2584. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2585. $segment = DB::table('mp_episode_segments')
  2586. ->where('id', $act_id)
  2587. ->first();
  2588. if (!$segment) Utils::throwError('20003:该片段不存在');
  2589. try {
  2590. DB::beginTransaction();
  2591. // 准备更新数据
  2592. $update_data = [
  2593. 'updated_at' => date('Y-m-d H:i:s')
  2594. ];
  2595. // 更新act相关字段
  2596. if (!empty($act_content)) {
  2597. $update_data['act_show_content'] = $act_content;
  2598. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2599. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2600. $shot_counter = 0;
  2601. $update_data['act_show_content'] = preg_replace_callback(
  2602. '/【(?:镜头|分镜)(\d+)】/u',
  2603. function($matches) use (&$shot_counter) {
  2604. $shot_counter++;
  2605. return '【镜头' . $shot_counter . '】';
  2606. },
  2607. $update_data['act_show_content']
  2608. );
  2609. }
  2610. if (!empty($act_duration)) {
  2611. $update_data['act_duration'] = $act_duration;
  2612. }
  2613. if (!empty($act_title)) {
  2614. $update_data['act_title'] = $act_title;
  2615. }
  2616. // 处理图片上传
  2617. if ($image_url) {
  2618. $update_data['img_url'] = $image_url;
  2619. $update_data['current_type'] = 1;
  2620. // 同时写入一个图片生成任务记录
  2621. if ($act_id) {
  2622. $pic_task = [
  2623. 'alias_act_id' => $act_id,
  2624. 'ref_img_url' => json_encode([]),
  2625. 'status' => 'success',
  2626. 'result_url' => json_encode([$image_url], 256),
  2627. 'model' => '',
  2628. 'created_at' => date('Y-m-d H:i:s'),
  2629. 'updated_at' => date('Y-m-d H:i:s'),
  2630. ];
  2631. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2632. }
  2633. }
  2634. // 处理视频上传
  2635. if ($video_url) {
  2636. $update_data['origin_video_url'] = $video_url;
  2637. $compressed_video_url = compressVideo($video_url);
  2638. $update_data['current_type'] = 2;
  2639. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2640. // 同时写入一个视频生成任务记录
  2641. if ($act_id) {
  2642. $video_task = [
  2643. 'alias_act_id' => $act_id,
  2644. 'status' => 'success',
  2645. 'result_url' => $update_data['origin_video_url'],
  2646. 'compressed_url' => $update_data['video_url'],
  2647. 'created_at' => date('Y-m-d H:i:s'),
  2648. 'updated_at' => date('Y-m-d H:i:s'),
  2649. ];
  2650. DB::table('mp_generate_video_tasks')->insert($video_task);
  2651. }
  2652. }
  2653. // 更新片段信息
  2654. $result = DB::table('mp_episode_segments')
  2655. ->where('id', $act_id)
  2656. ->update($update_data);
  2657. if ($result === false) {
  2658. Utils::throwError('20003:更新片段失败');
  2659. }
  2660. DB::commit();
  2661. // 返回新复制的记录
  2662. $new_segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,act_show_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $act_id)->first();
  2663. $new_segment = (array)$new_segment;
  2664. return $new_segment;
  2665. } catch (\Exception $e) {
  2666. DB::rollBack();
  2667. dLog('anime')->error('更新片段失败', [
  2668. 'act_id' => $act_id,
  2669. 'error' => $e->getMessage()
  2670. ]);
  2671. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2672. }
  2673. }
  2674. public function copyAct($data) {
  2675. $act_id = getProp($data, 'act_id');
  2676. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2677. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2678. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2679. $anime_id = getProp($source_segment, 'anime_id');
  2680. $episode_id = getProp($source_segment, 'episode_id');
  2681. $episode_number = getProp($source_segment, 'episode_number');
  2682. $act_number = getProp($source_segment, 'act_number');
  2683. try {
  2684. DB::beginTransaction();
  2685. // 新act的编号
  2686. $new_act_number = $act_number + 1;
  2687. // 更新后续所有act的act_number
  2688. DB::table('mp_episode_segments')
  2689. ->where('anime_id', $anime_id)
  2690. ->where('episode_id', $episode_id)
  2691. ->where('act_number', '>', $act_number)
  2692. ->increment('act_number');
  2693. // 复制该片段记录
  2694. $segment_data = (array)$source_segment;
  2695. unset($segment_data['id']);
  2696. $segment_data['video_url'] = '';
  2697. $segment_data['video_task_id'] = '';
  2698. $segment_data['video_task_status'] = '';
  2699. $segment_data['act_number'] = $new_act_number;
  2700. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2701. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2702. if (!$id) {
  2703. Utils::throwError('20003:复制片段失败');
  2704. }
  2705. DB::commit();
  2706. }catch (\Exception $e) {
  2707. DB::rollBack();
  2708. Utils::throwError('20003:'.$e->getMessage());
  2709. }
  2710. // 返回新复制的记录
  2711. $new_segment = DB::table('mp_episode_segments')->selectRaw("id as act_id,anime_id,episode_id,episode_number,act_number,act_title,act_duration,act_content,act_show_content,video_url,video_duration,video_time_point_start,video_time_point_end")->where('id', $id)->first();
  2712. $new_segment = $new_segment ? (array)$new_segment : [];
  2713. $new_segment['act_id'] = $id;
  2714. return $new_segment;
  2715. }
  2716. public function moveAct($data) {
  2717. $act_id = getProp($data, 'act_id');
  2718. $target_act_id = getProp($data, 'target_act_id');
  2719. // 获取源片段信息
  2720. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2721. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2722. // 获取目标片段信息
  2723. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2724. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2725. $anime_id = getProp($source_segment, 'anime_id');
  2726. $episode_id = getProp($source_segment, 'episode_id');
  2727. $source_act_number = getProp($source_segment, 'act_number');
  2728. $target_act_number = getProp($target_segment, 'act_number');
  2729. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2730. $target_anime_id = getProp($target_segment, 'anime_id');
  2731. $target_episode_id = getProp($target_segment, 'episode_id');
  2732. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2733. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2734. }
  2735. // 如果源片段和目标片段相同,无需移动
  2736. if ($source_act_number == $target_act_number) {
  2737. return true;
  2738. }
  2739. try {
  2740. DB::beginTransaction();
  2741. if ($source_act_number < $target_act_number) {
  2742. // 向后移动:源片段移动到目标片段之后
  2743. // 1. 将源片段和目标片段之间的所有片段编号减1
  2744. DB::table('mp_episode_segments')
  2745. ->where('anime_id', $anime_id)
  2746. ->where('episode_id', $episode_id)
  2747. ->where('act_number', '>', $source_act_number)
  2748. ->where('act_number', '<=', $target_act_number)
  2749. ->decrement('act_number');
  2750. // 2. 将源片段移动到目标片段之后
  2751. $new_act_number = $target_act_number;
  2752. } else {
  2753. // 向前移动:源片段移动到目标片段之后
  2754. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2755. DB::table('mp_episode_segments')
  2756. ->where('anime_id', $anime_id)
  2757. ->where('episode_id', $episode_id)
  2758. ->where('act_number', '>', $target_act_number)
  2759. ->where('act_number', '<', $source_act_number)
  2760. ->increment('act_number');
  2761. // 2. 将源片段移动到目标片段之后
  2762. $new_act_number = $target_act_number + 1;
  2763. }
  2764. // 3. 更新源片段的编号
  2765. $update_result = DB::table('mp_episode_segments')
  2766. ->where('id', $act_id)
  2767. ->update([
  2768. 'act_number' => $new_act_number,
  2769. 'updated_at' => date('Y-m-d H:i:s')
  2770. ]);
  2771. if (!$update_result) {
  2772. Utils::throwError('20003:更新片段编号失败');
  2773. }
  2774. DB::commit();
  2775. return true;
  2776. } catch (\Exception $e) {
  2777. DB::rollBack();
  2778. Utils::throwError('20003:' . $e->getMessage());
  2779. }
  2780. }
  2781. public function delAct($data) {
  2782. $act_id = getProp($data, 'act_id');
  2783. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2784. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2785. if (!$segment) Utils::throwError('20003:请选择片段');
  2786. $anime_id = getProp($segment, 'anime_id');
  2787. $episode_id = getProp($segment, 'episode_id');
  2788. $act_number = getProp($segment, 'act_number');
  2789. try {
  2790. DB::beginTransaction();
  2791. // 删除该片段记录
  2792. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2793. if (!$deleted) {
  2794. Utils::throwError('20003:删除片段失败');
  2795. }
  2796. // 更新后续act的编号
  2797. DB::table('mp_episode_segments')
  2798. ->where('anime_id', $anime_id)
  2799. ->where('episode_id', $episode_id)
  2800. ->where('act_number', '>', $act_number)
  2801. ->decrement('act_number');
  2802. DB::commit();
  2803. }catch (\Exception $e) {
  2804. DB::rollBack();
  2805. Utils::throwError('20003:'.$e->getMessage());
  2806. }
  2807. return true;
  2808. }
  2809. public function applyAct($data) {
  2810. $act_id = getProp($data, 'act_id');
  2811. $url = getProp($data, 'url');
  2812. if (!$act_id) Utils::throwError('20003:请选择片段');
  2813. if (!$url) Utils::throwError('20003:URL不能为空');
  2814. // 获取URL的文件扩展名
  2815. $urlPath = parse_url($url, PHP_URL_PATH);
  2816. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2817. // 定义图片和视频的扩展名
  2818. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2819. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2820. // 判断是图片还是视频
  2821. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2822. if (in_array($extension, $imageExtensions)) {
  2823. // 图片类型
  2824. $updateData['img_url'] = $url;
  2825. $updateData['current_type'] = 1;
  2826. } elseif (in_array($extension, $videoExtensions)) {
  2827. // 视频类型
  2828. $updateData['video_url'] = $url;
  2829. $updateData['current_type'] = 2;
  2830. } else {
  2831. Utils::throwError('20003:不支持的文件类型');
  2832. }
  2833. // 更新片段记录(全能模式下每个act只有一条记录)
  2834. $result = DB::table('mp_episode_segments')
  2835. ->where('id', $act_id)
  2836. ->update($updateData);
  2837. if (!$result) {
  2838. Utils::throwError('20003:更新片段失败');
  2839. }
  2840. return true;
  2841. }
  2842. public function actChatHistory($data) {
  2843. $act_id = getProp($data, 'act_id');
  2844. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2845. $query = DB::table('mp_anime_records')->where('act_id', $act_id)->select('role', 'content', 'act_id', 'image_url', 'video_url', 'reference_images', 'created_at');
  2846. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2847. $value = (array)$value;
  2848. $value['created_at'] = transDate($value['created_at']);
  2849. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2850. else $value['reference_images'] = [];
  2851. return $value;
  2852. })->toArray();
  2853. // 获取历史图片
  2854. $url = [];
  2855. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2856. foreach($pic_history as $task) {
  2857. $result_url = getProp($task, 'result_url');
  2858. if (is_json($result_url)) {
  2859. $url = array_merge($url, json_decode($result_url, true));
  2860. }else {
  2861. $url[] = $result_url;
  2862. }
  2863. }
  2864. // 获取历史视频
  2865. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2866. foreach($video_history as $task) {
  2867. $result_url = getProp($task, 'result_url');
  2868. if (is_json($result_url)) {
  2869. $url = array_merge($url, json_decode($result_url, true));
  2870. }else {
  2871. $url[] = $result_url;
  2872. }
  2873. }
  2874. // 获取资产库
  2875. $products = [];
  2876. // 通过act_id查询片段信息获取episode_id
  2877. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2878. if ($segment) {
  2879. $episode_id = getProp($segment, 'episode_id');
  2880. // 查询剧集信息获取roles、scenes和extra_products
  2881. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2882. if ($episode) {
  2883. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2884. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2885. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2886. // 先合并roles和scenes
  2887. // 处理角色数组
  2888. foreach ($roles as $role) {
  2889. $product = $role;
  2890. // 将role字段重命名为product_name
  2891. if (isset($product['role'])) {
  2892. $product['product_name'] = $product['role'];
  2893. unset($product['role']);
  2894. }
  2895. $product['product'] = 1; // 标记类型为角色
  2896. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2897. }
  2898. // 处理场景数组
  2899. foreach ($scenes as $scene) {
  2900. $product = $scene;
  2901. // 将scene字段重命名为product_name
  2902. if (isset($product['scene'])) {
  2903. $product['product_name'] = $product['scene'];
  2904. unset($product['scene']);
  2905. }
  2906. $product['product'] = 2; // 标记类型为场景
  2907. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2908. }
  2909. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2910. foreach ($extra_products as $extra_product) {
  2911. $product_name = getProp($extra_product, 'product_name');
  2912. if ($product_name) {
  2913. $products[$product_name] = $extra_product; // 覆盖同名数据
  2914. }
  2915. }
  2916. // 重新索引数组(去除key)
  2917. $products = array_values($products);
  2918. }
  2919. }
  2920. // 获取执行中的任务
  2921. $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) {
  2922. $value = (array)$value;
  2923. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2924. else $value['ref_image_url'] = [];
  2925. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2926. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2927. if (!empty($value['prompt'])) {
  2928. $prompt = $value['prompt'];
  2929. // 查找第一个【镜头】的位置
  2930. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2931. // 从【镜头】开始截取
  2932. $prompt = substr($prompt, $matches[0][1]);
  2933. }
  2934. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2935. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2936. $value['prompt'] = $prompt;
  2937. }
  2938. return $value;
  2939. })->toArray();
  2940. return compact('chat', 'url', 'products', 'tasks');
  2941. }
  2942. public function applyAudioData($data) {
  2943. $segment_id = getProp($data, 'segment_id');
  2944. $global_data = getProp($data, 'global_data');
  2945. $segment_data = getProp($data, 'segment_data');
  2946. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2947. $global_data = is_array($global_data) ? $global_data : [];
  2948. $segment_data = is_array($segment_data) ? $segment_data : [];
  2949. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  2950. $dialogue_item = null;
  2951. foreach ($global_data as $key => $item) {
  2952. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  2953. $dialogue_item = $item;
  2954. unset($global_data[$key]);
  2955. break;
  2956. }
  2957. }
  2958. if ($dialogue_item) {
  2959. $segment_data[] = $dialogue_item;
  2960. }
  2961. // 特殊参数: audio_url,audio_duration,subtitle_info
  2962. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  2963. // 如果不是全部存在,则仍需创建音频任务
  2964. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  2965. $special_update_data = [];
  2966. $has_all_special_params = false;
  2967. // 从segment_data中提取特殊参数
  2968. $filtered_segment_data = [];
  2969. foreach ($segment_data as $item) {
  2970. $field_name = trim((string)getProp($item, 'name'));
  2971. if (in_array($field_name, $special_fields)) {
  2972. $special_update_data[$field_name] = getProp($item, 'value');
  2973. } else {
  2974. // 非特殊参数保留,继续后续处理
  2975. $filtered_segment_data[] = $item;
  2976. }
  2977. }
  2978. // 检查是否三个特殊参数都存在
  2979. if (count($special_update_data) === 3 &&
  2980. isset($special_update_data['audio_url']) &&
  2981. isset($special_update_data['audio_duration']) &&
  2982. isset($special_update_data['subtitle_info'])) {
  2983. $has_all_special_params = true;
  2984. // 立即更新到当前分镜
  2985. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  2986. DB::table('mp_episode_segments')
  2987. ->where('segment_id', $segment_id)
  2988. ->update($special_update_data);
  2989. }
  2990. // 使用过滤后的segment_data继续处理其他参数
  2991. $segment_data = $filtered_segment_data;
  2992. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  2993. $global_update_data = [];
  2994. $segment_update_data = [];
  2995. $global_voice_type = '';
  2996. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2997. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  2998. $episode_id = getProp($target_segment, 'episode_id');
  2999. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3000. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3001. if (!$episode) Utils::throwError('20003:分集不存在');
  3002. foreach ($global_data as $item) {
  3003. $field_name = trim((string)getProp($item, 'name'));
  3004. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3005. continue;
  3006. }
  3007. $global_update_data[$field_name] = getProp($item, 'value');
  3008. if ($field_name === 'voice_type') {
  3009. $global_voice_type = trim((string)getProp($item, 'value'));
  3010. }
  3011. }
  3012. foreach ($segment_data as $item) {
  3013. $field_name = trim((string)getProp($item, 'name'));
  3014. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3015. continue;
  3016. }
  3017. $segment_update_data[$field_name] = getProp($item, 'value');
  3018. }
  3019. if ($global_voice_type) {
  3020. $timbre_info = DB::table('mp_timbres')
  3021. ->where('timbre_type', $global_voice_type)
  3022. ->select('audio_url', 'timbre_name')
  3023. ->first();
  3024. if ($timbre_info) {
  3025. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3026. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3027. }
  3028. }
  3029. try {
  3030. DB::beginTransaction();
  3031. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3032. $segment_ids_to_create_task = [];
  3033. $segments_data = [];
  3034. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3035. if (!empty($global_update_data)) {
  3036. // 如果角色不存在,则只更新当前分镜
  3037. if (!$target_voice_actor) {
  3038. // 只处理当前分镜
  3039. $affected_segments = DB::table('mp_episode_segments')
  3040. ->where('segment_id', $segment_id)
  3041. ->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')
  3042. ->get();
  3043. } else {
  3044. // 获取该角色的所有分镜
  3045. $affected_segments = DB::table('mp_episode_segments')
  3046. ->where('episode_id', $episode_id)
  3047. ->where('voice_actor', $target_voice_actor)
  3048. ->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')
  3049. ->get();
  3050. }
  3051. foreach ($affected_segments as $seg) {
  3052. $seg = (array)$seg;
  3053. $sid = getProp($seg, 'segment_id');
  3054. // 检查参数是否发生变化
  3055. $has_changed = false;
  3056. foreach ($global_update_data as $field => $new_value) {
  3057. $old_value = getProp($seg, $field);
  3058. if ($old_value != $new_value) {
  3059. $has_changed = true;
  3060. break;
  3061. }
  3062. }
  3063. if ($has_changed) {
  3064. $segment_ids_to_create_task[] = $sid;
  3065. $segments_data[$sid] = $seg;
  3066. }
  3067. }
  3068. // 只有在有变化的分镜时才更新
  3069. if (!empty($segment_ids_to_create_task)) {
  3070. $global_segment_update_data = $global_update_data;
  3071. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3072. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3073. DB::table('mp_episode_segments')
  3074. ->where('episode_id', $episode_id)
  3075. ->where('voice_actor', $target_voice_actor)
  3076. ->whereIn('segment_id', $segment_ids_to_create_task)
  3077. ->update($global_segment_update_data);
  3078. }
  3079. if ($global_voice_type) {
  3080. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3081. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3082. $roles_updated = false;
  3083. foreach ($episode_roles as &$role) {
  3084. // 通过 role 字段匹配角色名,而不是 voice_name
  3085. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3086. continue;
  3087. }
  3088. $role['voice_type'] = $global_voice_type;
  3089. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3090. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3091. $roles_updated = true;
  3092. }
  3093. unset($role);
  3094. if ($roles_updated) {
  3095. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3096. 'roles' => json_encode($episode_roles, 256),
  3097. 'updated_at' => date('Y-m-d H:i:s'),
  3098. ]);
  3099. }
  3100. }
  3101. }
  3102. // 如果有单个分镜更新,检查是否有变化
  3103. if (!empty($segment_update_data)) {
  3104. // 获取当前分镜数据
  3105. $current_segment = DB::table('mp_episode_segments')
  3106. ->where('segment_id', $segment_id)
  3107. ->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')
  3108. ->first();
  3109. if ($current_segment) {
  3110. $current_segment = (array)$current_segment;
  3111. // 检查参数是否发生变化
  3112. $has_changed = false;
  3113. foreach ($segment_update_data as $field => $new_value) {
  3114. $old_value = getProp($current_segment, $field);
  3115. if ($old_value != $new_value) {
  3116. $has_changed = true;
  3117. break;
  3118. }
  3119. }
  3120. if ($has_changed) {
  3121. // 如果该分镜还未在列表中,添加进去
  3122. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3123. $segment_ids_to_create_task[] = $segment_id;
  3124. $segments_data[$segment_id] = $current_segment;
  3125. }
  3126. // 更新分镜数据并清空音频URL
  3127. $segment_update_data['audio_url'] = '';
  3128. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3129. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3130. }
  3131. }
  3132. }
  3133. // 为所有有变化的分镜创建音频合成任务
  3134. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3135. if (!empty($segment_ids_to_create_task)) {
  3136. foreach ($segment_ids_to_create_task as $sid) {
  3137. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3138. if ($sid === $segment_id && $has_all_special_params) {
  3139. continue;
  3140. }
  3141. // 重新获取更新后的分镜数据
  3142. $updated_segment = DB::table('mp_episode_segments')
  3143. ->where('segment_id', $sid)
  3144. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3145. ->first();
  3146. if (!$updated_segment) continue;
  3147. $updated_segment = (array)$updated_segment;
  3148. // 检查dialogue是否为空
  3149. $dialogue = getProp($updated_segment, 'dialogue');
  3150. if (empty($dialogue)) {
  3151. // dialogue为空时,直接写入默认音频信息
  3152. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3153. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3154. 'audio_duration' => 2.0,
  3155. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3156. 'updated_at' => date('Y-m-d H:i:s')
  3157. ]);
  3158. continue;
  3159. }
  3160. $generate_json = [
  3161. 'text' => $dialogue,
  3162. 'role' => getProp($updated_segment, 'voice_actor'),
  3163. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3164. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3165. 'emotion' => getProp($updated_segment, 'emotion'),
  3166. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3167. 'gender' => getProp($updated_segment, 'gender'),
  3168. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3169. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3170. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3171. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3172. ];
  3173. // 插入视频配音合成任务
  3174. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3175. 'alias_segment_id' => $sid,
  3176. 'generate_status' => '执行中',
  3177. 'audio_url' => '',
  3178. 'generate_json' => json_encode($generate_json, 256),
  3179. 'created_at' => date('Y-m-d H:i:s'),
  3180. 'updated_at' => date('Y-m-d H:i:s'),
  3181. ]);
  3182. if (!$dubTaskId) {
  3183. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3184. continue;
  3185. }
  3186. // 将任务ID添加到Redis列表中
  3187. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3188. // 请求远程服务器执行生成
  3189. try {
  3190. sleep(1);
  3191. $client = new Client(['timeout' => 300, 'verify' => false]);
  3192. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3193. $response = $result->getBody()->getContents();
  3194. $response_arr = json_decode($response, true);
  3195. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3196. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3197. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3198. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3199. }
  3200. } catch (\Exception $e) {
  3201. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3202. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3203. }
  3204. }
  3205. }
  3206. DB::commit();
  3207. } catch (\Exception $e) {
  3208. DB::rollBack();
  3209. Utils::throwError('20003:'.$e->getMessage());
  3210. }
  3211. return true;
  3212. }
  3213. public function episodePicsInfo($data) {
  3214. $anime_id = getProp($data, 'anime_id');
  3215. $episode_id = getProp($data, 'episode_id');
  3216. // 参数验证
  3217. if (!$anime_id && !$episode_id) {
  3218. Utils::throwError('20003:请提供动漫ID或分集ID');
  3219. }
  3220. // 根据参数获取数据源
  3221. if ($episode_id) {
  3222. // 从剧集表获取
  3223. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3224. if (!$source) Utils::throwError('20003:该剧集不存在');
  3225. $table_name = 'mp_anime_episodes';
  3226. $id_field = 'id';
  3227. $id_value = $episode_id;
  3228. // 获取剧集的anime_id用于继承全局数据
  3229. $anime_id = getProp($source, 'anime_id');
  3230. } else {
  3231. // 从动漫表获取
  3232. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3233. if (!$source) Utils::throwError('20003:该动漫不存在');
  3234. $table_name = 'mp_animes';
  3235. $id_field = 'id';
  3236. $id_value = $anime_id;
  3237. }
  3238. $source = (array)$source;
  3239. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3240. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3241. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3242. // 如果是分集数据,需要处理继承和任务创建逻辑
  3243. if ($episode_id) {
  3244. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3245. }
  3246. // 返回生成器函数,用于 SSE 流式输出
  3247. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3248. $startTime = time();
  3249. $maxDuration = 600; // 10分钟超时
  3250. $checkInterval = 3; // 每3秒检查一次
  3251. // Redis 缓存键
  3252. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3253. // 生成当前数据的哈希值用于比较
  3254. $generateHash = function($roles, $scenes, $props) {
  3255. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3256. };
  3257. // 发送初始数据
  3258. $currentHash = $generateHash($roles, $scenes, $props);
  3259. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3260. echo "data: " . json_encode([
  3261. 'type' => 'init',
  3262. 'data' => [
  3263. 'roles' => $roles,
  3264. 'scenes' => $scenes,
  3265. 'props' => $props,
  3266. 'start_time' => $startTime
  3267. ]
  3268. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3269. if (ob_get_level() > 0) {
  3270. ob_flush();
  3271. }
  3272. flush();
  3273. // 持续轮询任务状态
  3274. while (time() - $startTime < $maxDuration) {
  3275. $hasProcessing = false;
  3276. $updated = false;
  3277. // 检查角色任务状态
  3278. foreach ($roles as $index => &$role) {
  3279. $task_id = getProp($role, 'task_id');
  3280. $task_status = getProp($role, 'task_status');
  3281. $existing_url = getProp($role, 'url');
  3282. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3283. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3284. $hasProcessing = ($task_status === 'processing');
  3285. // 查询任务状态
  3286. $task = DB::table('mp_generate_pic_tasks')
  3287. ->where('id', $task_id)
  3288. ->select('id', 'status', 'result_url', 'error_message')
  3289. ->first();
  3290. if ($task) {
  3291. $task = (array)$task;
  3292. $status = getProp($task, 'status');
  3293. // 如果任务完成或失败
  3294. if (in_array($status, ['success', 'failed'])) {
  3295. $role['task_status'] = $status;
  3296. if ($status === 'success') {
  3297. $result_url = getProp($task, 'result_url');
  3298. if ($result_url) {
  3299. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3300. if (is_array($result_urls) && !empty($result_urls[0])) {
  3301. $role['url'] = $result_urls[0];
  3302. }
  3303. }
  3304. }
  3305. $updated = true;
  3306. } else if ($status === 'processing') {
  3307. $hasProcessing = true;
  3308. }
  3309. }
  3310. }
  3311. }
  3312. // 检查场景任务状态
  3313. foreach ($scenes as $index => &$scene) {
  3314. $task_id = getProp($scene, 'task_id');
  3315. $task_status = getProp($scene, 'task_status');
  3316. $existing_url = getProp($scene, 'url');
  3317. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3318. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3319. $hasProcessing = ($task_status === 'processing');
  3320. // 查询任务状态
  3321. $task = DB::table('mp_generate_pic_tasks')
  3322. ->where('id', $task_id)
  3323. ->select('id', 'status', 'result_url', 'error_message')
  3324. ->first();
  3325. if ($task) {
  3326. $task = (array)$task;
  3327. $status = getProp($task, 'status');
  3328. // 如果任务完成或失败
  3329. if (in_array($status, ['success', 'failed'])) {
  3330. $scene['task_status'] = $status;
  3331. if ($status === 'success') {
  3332. $result_url = getProp($task, 'result_url');
  3333. if ($result_url) {
  3334. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3335. if (is_array($result_urls) && !empty($result_urls[0])) {
  3336. $scene['url'] = $result_urls[0];
  3337. }
  3338. }
  3339. }
  3340. $updated = true;
  3341. } else if ($status === 'processing') {
  3342. $hasProcessing = true;
  3343. }
  3344. }
  3345. }
  3346. }
  3347. // 检查道具任务状态
  3348. foreach ($props as $index => &$prop) {
  3349. $task_id = getProp($prop, 'task_id');
  3350. $task_status = getProp($prop, 'task_status');
  3351. $existing_url = getProp($prop, 'url');
  3352. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3353. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3354. $hasProcessing = ($task_status === 'processing');
  3355. // 查询任务状态
  3356. $task = DB::table('mp_generate_pic_tasks')
  3357. ->where('id', $task_id)
  3358. ->select('id', 'status', 'result_url', 'error_message')
  3359. ->first();
  3360. if ($task) {
  3361. $task = (array)$task;
  3362. $status = getProp($task, 'status');
  3363. // 如果任务完成或失败
  3364. if (in_array($status, ['success', 'failed'])) {
  3365. $prop['task_status'] = $status;
  3366. if ($status === 'success') {
  3367. $result_url = getProp($task, 'result_url');
  3368. if ($result_url) {
  3369. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3370. if (is_array($result_urls) && !empty($result_urls[0])) {
  3371. $prop['url'] = $result_urls[0];
  3372. }
  3373. }
  3374. }
  3375. $updated = true;
  3376. } else if ($status === 'processing') {
  3377. $hasProcessing = true;
  3378. }
  3379. }
  3380. }
  3381. }
  3382. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3383. if ($updated) {
  3384. $newHash = $generateHash($roles, $scenes, $props);
  3385. $cachedHash = Redis::get($cacheKey);
  3386. // 只有当数据真正变化时才更新数据库和发送事件
  3387. if ($newHash !== $cachedHash) {
  3388. try {
  3389. // 更新数据库
  3390. DB::table($table_name)->where($id_field, $id_value)->update([
  3391. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3392. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3393. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3394. 'updated_at' => date('Y-m-d H:i:s')
  3395. ]);
  3396. // 更新缓存
  3397. Redis::setex($cacheKey, 600, $newHash);
  3398. // 发送更新事件
  3399. echo "data: " . json_encode([
  3400. 'type' => 'update',
  3401. 'data' => [
  3402. 'roles' => $roles,
  3403. 'scenes' => $scenes,
  3404. 'props' => $props,
  3405. 'elapsed_time' => time() - $startTime
  3406. ]
  3407. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3408. if (ob_get_level() > 0) {
  3409. ob_flush();
  3410. }
  3411. flush();
  3412. } catch (\Exception $e) {
  3413. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3414. }
  3415. } else {
  3416. // 即使哈希相同,如果有URL更新也要发送事件
  3417. $hasUrlUpdate = false;
  3418. foreach ($roles as $role) {
  3419. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3420. $hasUrlUpdate = true;
  3421. break;
  3422. }
  3423. }
  3424. if (!$hasUrlUpdate) {
  3425. foreach ($scenes as $scene) {
  3426. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3427. $hasUrlUpdate = true;
  3428. break;
  3429. }
  3430. }
  3431. }
  3432. if (!$hasUrlUpdate) {
  3433. foreach ($props as $prop) {
  3434. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3435. $hasUrlUpdate = true;
  3436. break;
  3437. }
  3438. }
  3439. }
  3440. if ($hasUrlUpdate) {
  3441. // 强制更新数据库和发送事件
  3442. try {
  3443. DB::table($table_name)->where($id_field, $id_value)->update([
  3444. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3445. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3446. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3447. 'updated_at' => date('Y-m-d H:i:s')
  3448. ]);
  3449. // 更新缓存
  3450. Redis::setex($cacheKey, 600, $newHash);
  3451. // 发送更新事件
  3452. echo "data: " . json_encode([
  3453. 'type' => 'update',
  3454. 'data' => [
  3455. 'roles' => $roles,
  3456. 'scenes' => $scenes,
  3457. 'props' => $props,
  3458. 'elapsed_time' => time() - $startTime
  3459. ]
  3460. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3461. if (ob_get_level() > 0) {
  3462. ob_flush();
  3463. }
  3464. flush();
  3465. } catch (\Exception $e) {
  3466. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3467. }
  3468. }
  3469. }
  3470. }
  3471. // 如果所有任务都已完成,发送完成事件并退出
  3472. if (!$hasProcessing) {
  3473. // 查询数据库中的最终数据,确保返回最新的完整数据
  3474. try {
  3475. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3476. if ($finalSource) {
  3477. $finalSource = (array)$finalSource;
  3478. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3479. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3480. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3481. // 使用数据库中的最终数据
  3482. $roles = $finalRoles;
  3483. $scenes = $finalScenes;
  3484. $props = $finalProps;
  3485. }
  3486. } catch (\Exception $e) {
  3487. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3488. // 如果查询失败,继续使用内存中的数据
  3489. }
  3490. // 清理缓存
  3491. Redis::del($cacheKey);
  3492. echo "data: " . json_encode([
  3493. 'type' => 'completed',
  3494. 'data' => [
  3495. 'roles' => $roles,
  3496. 'scenes' => $scenes,
  3497. 'props' => $props,
  3498. 'total_time' => time() - $startTime
  3499. ]
  3500. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3501. if (ob_get_level() > 0) {
  3502. ob_flush();
  3503. }
  3504. flush();
  3505. break;
  3506. }
  3507. // 等待下次检查
  3508. sleep($checkInterval);
  3509. }
  3510. // 超时处理
  3511. if (time() - $startTime >= $maxDuration) {
  3512. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3513. try {
  3514. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3515. if ($finalSource) {
  3516. $finalSource = (array)$finalSource;
  3517. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3518. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3519. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3520. // 使用数据库中的最终数据
  3521. $roles = $finalRoles;
  3522. $scenes = $finalScenes;
  3523. $props = $finalProps;
  3524. }
  3525. } catch (\Exception $e) {
  3526. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3527. // 如果查询失败,继续使用内存中的数据
  3528. }
  3529. // 清理缓存
  3530. Redis::del($cacheKey);
  3531. echo "data: " . json_encode([
  3532. 'type' => 'timeout',
  3533. 'message' => '轮询超时,请刷新页面查看最新状态',
  3534. 'data' => [
  3535. 'roles' => $roles,
  3536. 'scenes' => $scenes,
  3537. 'props' => $props
  3538. ]
  3539. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3540. if (ob_get_level() > 0) {
  3541. ob_flush();
  3542. }
  3543. flush();
  3544. }
  3545. };
  3546. }
  3547. public function clipSegmentVideo($data) {
  3548. $segment_id = getProp($data, 'segment_id');
  3549. $video_time_point_start = getProp($data, 'video_time_point_start');
  3550. $video_time_point_end = getProp($data, 'video_time_point_end');
  3551. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3552. Utils::throwError('20003:参数异常');
  3553. }
  3554. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3555. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3556. }
  3557. $video_duration = $video_time_point_end - $video_time_point_start;
  3558. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3559. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3560. 'video_duration' => $video_duration,
  3561. 'video_time_point_start' => $video_time_point_start,
  3562. 'video_time_point_end' => $video_time_point_end,
  3563. 'updated_at' => date('Y-m-d H:i:s')
  3564. ]);
  3565. }
  3566. // 轮训获取图片任务结果
  3567. private function loopGetPicTaskResult($task_id) {
  3568. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3569. if (!$task) {
  3570. return '';
  3571. }
  3572. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3573. $model = getProp($task, 'model');
  3574. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3575. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3576. $isSyncModel = $isVolcModel || $isGptModel;
  3577. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3578. $start_count = 0;
  3579. $img_url = '';
  3580. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3581. sleep(3);
  3582. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3583. // 如果任务已经完成,直接返回结果
  3584. if ($task->status === 'success' && $task->result_url) {
  3585. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3586. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3587. }
  3588. // 如果任务已失败,返回空
  3589. if ($task->status === 'failed') {
  3590. return '';
  3591. }
  3592. if ($isSyncModel) continue;
  3593. // 查询任务状态
  3594. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3595. if ($statusInfo['status'] === 'success') {
  3596. $task->updateStatus('success', [
  3597. 'result_url' => $statusInfo['result_url'],
  3598. 'result_json' => $statusInfo['result_json'] ?? []
  3599. ]);
  3600. // 同步调整分镜图片状态和结果
  3601. if (getProp($task, 'alias_segment_id')) {
  3602. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3603. 'img_url' => $statusInfo['result_url'][0],
  3604. 'pic_task_status' => '已完成',
  3605. ]);
  3606. }
  3607. $img_url = $statusInfo['result_url'][0];
  3608. break;
  3609. } elseif ($statusInfo['status'] === 'failed') {
  3610. $task->updateStatus('failed', [
  3611. 'error_message' => $statusInfo['error_message'],
  3612. 'result_json' => $statusInfo['result_json'] ?? []
  3613. ]);
  3614. if (getProp($task, 'alias_segment_id')) {
  3615. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3616. 'pic_task_status' => '失败',
  3617. ]);
  3618. }
  3619. break;
  3620. }
  3621. $start_count++;
  3622. }
  3623. return $img_url;
  3624. }
  3625. /**
  3626. * 从分镜内容中提取涉及的角色
  3627. */
  3628. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3629. $found_characters = [];
  3630. foreach ($available_characters as $character) {
  3631. // 检查角色名称是否在分镜内容中出现
  3632. if (strpos($segment_content, $character) !== false) {
  3633. $found_characters[] = $character;
  3634. }
  3635. }
  3636. if (!$found_characters) {
  3637. foreach ($roles as $character) {
  3638. // 检查角色名称是否在分镜内容中出现
  3639. if (strpos($segment_content, $character) !== false) {
  3640. $found_characters[] = $character;
  3641. }
  3642. }
  3643. }
  3644. return array_unique($found_characters);
  3645. }
  3646. // 从分镜剧本中提取关键字段
  3647. private function handleSegmentContent(&$data) {
  3648. $segmentContent = getProp($data, 'segment_content');
  3649. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3650. $segmentData = [
  3651. 'description' => '',
  3652. 'composition' => '',
  3653. 'camera_movement' => '',
  3654. 'voice_actor' => '',
  3655. 'dialogue' => '',
  3656. 'frame_type' => '',
  3657. 'scene' => '', // 场景
  3658. 'characters' => '', // 出镜角色
  3659. 'tail_frame' => '', // 尾帧描述
  3660. 'emotion' => '中性', // 情感
  3661. 'gender' => '0', // 性别(0未知,1男,2女)
  3662. 'speed_ratio' => 0, // 语速
  3663. 'loudness_ratio' => 0, // 音量
  3664. 'emotion_scale' => 4, // 情感强度
  3665. 'pitch' => 0, // 音调
  3666. ];
  3667. // 用于存储需要从 segment_content 中移除的匹配项
  3668. $replaceEmptyArr = [];
  3669. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3670. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3671. $segmentData['description'] = trim($descMatch[1]);
  3672. $data['description'] = trim($descMatch[1]);
  3673. }
  3674. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3675. $segmentData['composition'] = trim($compMatch[1]);
  3676. $data['composition'] = trim($compMatch[1]);
  3677. }
  3678. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3679. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3680. $data['camera_movement'] = trim($cameraMatch[1]);
  3681. }
  3682. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3683. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3684. $data['voice_actor'] = trim($voiceMatch[1]);
  3685. }
  3686. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3687. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3688. $data['dialogue'] = trim($dialogueMatch[1]);
  3689. }
  3690. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3691. $segmentData['frame_type'] = trim($frameMatch[1]);
  3692. $data['frame_type'] = trim($frameMatch[1]);
  3693. }
  3694. // 场景字段
  3695. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3696. $segmentData['scene'] = trim($sceneMatch[1]);
  3697. $data['scene'] = trim($sceneMatch[1]);
  3698. }
  3699. // 出镜角色字段
  3700. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3701. $segmentData['characters'] = trim($charactersMatch[1]);
  3702. $data['characters'] = trim($charactersMatch[1]);
  3703. }
  3704. // 尾帧描述字段
  3705. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3706. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3707. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3708. }
  3709. // 情感字段
  3710. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3711. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3712. $segmentData['emotion'] = trim($emotionMatch[1]);
  3713. $data['emotion'] = trim($emotionMatch[1]);
  3714. }
  3715. // 性别字段
  3716. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3717. $replaceEmptyArr[] = trim($genderMatch[0]);
  3718. $genderStr = trim($genderMatch[1]);
  3719. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3720. $segmentData['gender'] = '1';
  3721. $data['gender'] = '1';
  3722. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3723. $segmentData['gender'] = '2';
  3724. $data['gender'] = '2';
  3725. } else {
  3726. $segmentData['gender'] = '0';
  3727. $data['gender'] = '0';
  3728. }
  3729. }
  3730. // 语速字段
  3731. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3732. $replaceEmptyArr[] = trim($speedMatch[0]);
  3733. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3734. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3735. }
  3736. // 音量字段
  3737. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3738. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3739. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3740. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3741. }
  3742. // 情感强度字段
  3743. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3744. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3745. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3746. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3747. }
  3748. // 音调字段
  3749. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3750. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3751. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3752. $data['pitch'] = (int)trim($pitchMatch[1]);
  3753. }
  3754. // 从 segment_content 中移除已提取的配音参数字段
  3755. if (!empty($replaceEmptyArr)) {
  3756. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3757. }
  3758. // 如果有配音角色,查询音色信息并验证情感
  3759. $voice_actor = $segmentData['voice_actor'];
  3760. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3761. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3762. $anime_id = getProp($data, 'anime_id');
  3763. $episode_id = getProp($data, 'episode_id');
  3764. // 优先从剧集的角色列表中查找
  3765. $roles = [];
  3766. if ($episode_id) {
  3767. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3768. if ($episode && getProp($episode, 'roles')) {
  3769. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3770. }
  3771. }
  3772. // 如果剧集中没有,从动漫的角色列表中查找
  3773. if (empty($roles) && $anime_id) {
  3774. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3775. if ($anime && getProp($anime, 'roles')) {
  3776. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3777. }
  3778. }
  3779. // 查找匹配的角色音色信息
  3780. $timbre_info = null;
  3781. foreach ($roles as $role) {
  3782. if (getProp($role, 'role') === $voice_actor) {
  3783. $timbre_info = $role;
  3784. break;
  3785. }
  3786. }
  3787. // 如果找到音色信息,添加到数据中
  3788. if ($timbre_info) {
  3789. $voice_type = getProp($timbre_info, 'voice_type');
  3790. $voice_name = getProp($timbre_info, 'voice_name');
  3791. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3792. if ($voice_type) {
  3793. $data['voice_type'] = $voice_type;
  3794. $segmentData['voice_type'] = $voice_type;
  3795. }
  3796. if ($voice_name) {
  3797. $data['voice_name'] = $voice_name;
  3798. $segmentData['voice_name'] = $voice_name;
  3799. }
  3800. if ($voice_audio_url) {
  3801. $data['voice_audio_url'] = $voice_audio_url;
  3802. $segmentData['voice_audio_url'] = $voice_audio_url;
  3803. }
  3804. // 验证情感是否在音色支持的情感列表中
  3805. if ($voice_type) {
  3806. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3807. if ($timbre_emotion) {
  3808. $timbre_emotion = explode(',', $timbre_emotion);
  3809. } else {
  3810. $timbre_emotion = [];
  3811. }
  3812. $emotion = getProp($segmentData, 'emotion', '中性');
  3813. if (!in_array($emotion, $timbre_emotion)) {
  3814. $emotion = '中性';
  3815. }
  3816. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3817. $emotion_list = array_flip($emotion_list);
  3818. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3819. $data['emotion_type'] = $emotion_type;
  3820. $segmentData['emotion_type'] = $emotion_type;
  3821. }
  3822. }
  3823. }
  3824. return $segmentData;
  3825. }
  3826. public function createSegmentVideoTask($data) {
  3827. $segment_id = getProp($data, 'segment_id');
  3828. $tail_frame = getProp($data, 'tail_frame');
  3829. $first_frame_url = getProp($data, 'first_frame_url');
  3830. $tail_frame_url = getProp($data, 'tail_frame_url');
  3831. $generate_audio = getProp($data, 'generate_audio', 0);
  3832. if (!$segment_id) {
  3833. Utils::throwError('1002:分镜ID不能为空');
  3834. }
  3835. // 获取分镜信息
  3836. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3837. if (!$segment) {
  3838. Utils::throwError('20003:分镜不存在');
  3839. }
  3840. $segment = (array)$segment;
  3841. $episode_id = getProp($segment, 'episode_id');
  3842. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3843. if (!$ratio) $ratio = '9:16';
  3844. // 获取分镜内容
  3845. $segmentContent = getProp($segment, 'segment_content', '');
  3846. // 检查 $segmentContent 中是否已有尾帧描述
  3847. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3848. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3849. $finalTailFrame = '';
  3850. if ($tail_frame) {
  3851. // 用户输入了尾帧描述,优先使用
  3852. $finalTailFrame = $tail_frame;
  3853. // 如果 segmentContent 中已有尾帧描述,需要替换
  3854. if ($contentHasTailFrame) {
  3855. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3856. }
  3857. } elseif ($contentHasTailFrame) {
  3858. // segmentContent 中有尾帧描述,使用它
  3859. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3860. } else {
  3861. // 两者都没有,使用分镜表中的尾帧描述
  3862. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3863. }
  3864. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3865. $hasDialogue = false;
  3866. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3867. $dialogue = trim($dialogueMatch[1]);
  3868. // 如果台词不为空且不是"无"
  3869. if (!empty($dialogue) && $dialogue !== '无') {
  3870. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3871. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3872. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3873. $hasDialogue = true;
  3874. }
  3875. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3876. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3877. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3878. if (!preg_match('/^[“]/', $dialogue)) {
  3879. $dialogue = '“' . $dialogue;
  3880. }
  3881. if (!preg_match('/[”]$/', $dialogue)) {
  3882. $dialogue .= '”';
  3883. }
  3884. // 将修改后的台词替换回 $segmentContent
  3885. $originalDialogue = $dialogueMatch[1];
  3886. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3887. }
  3888. }
  3889. // 构建完整的提示词
  3890. $fullPrompt = $segmentContent;
  3891. if ($finalTailFrame && !$contentHasTailFrame) {
  3892. // 只有当 segmentContent 中没有尾帧描述时才追加
  3893. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3894. }
  3895. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3896. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3897. $fullPrompt = trim($fullPrompt);
  3898. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3899. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3900. // 智能选择视频时长
  3901. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3902. $videoDuration = -1;
  3903. // 处理视频模型
  3904. $model = getProp($data, 'model');
  3905. if (!$model) {
  3906. // 用户没有输入,从episode表获取
  3907. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3908. $model = getProp($episode, 'video_model');
  3909. if (!$model) {
  3910. // episode表也没有,使用默认值
  3911. $model = 'doubao-seedance-1-5-pro-251215';
  3912. }
  3913. }
  3914. // 验证模型是否在可用模型表中
  3915. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3916. $model = 'doubao-seedance-1-5-pro-251215';
  3917. }
  3918. // 保存到episode表
  3919. $episode_id = getProp($segment, 'episode_id');
  3920. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3921. 'video_model' => $model,
  3922. 'updated_at' => date('Y-m-d H:i:s')
  3923. ]);
  3924. // 构建视频生成参数
  3925. $videoParams = [
  3926. 'model' => $model,
  3927. 'alias_segment_id' => $segment_id,
  3928. 'prompt' => trim($fullPrompt),
  3929. 'video_duration' => $videoDuration,
  3930. 'video_resolution' => '720P',
  3931. 'seed' => -1,
  3932. 'ratio' => $ratio,
  3933. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3934. 'draft' => false,
  3935. 'watermark' => false,
  3936. 'camera_fixed' => false,
  3937. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3938. ];
  3939. // 如果分镜有图片,作为首帧
  3940. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3941. $hasVideo = !empty(getProp($segment, 'video_url'));
  3942. if ($hasImage) {
  3943. if ($first_frame_url) {
  3944. $videoParams['first_frame_url'] = $first_frame_url;
  3945. }else {
  3946. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  3947. }
  3948. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  3949. }
  3950. // 构建content数组
  3951. $videoParams['content'] = [
  3952. [
  3953. 'type' => 'text',
  3954. 'text' => $videoParams['prompt'],
  3955. ]
  3956. ];
  3957. // 如果有首帧图片,添加到content中
  3958. if ($hasImage) {
  3959. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  3960. $videoParams['content'][] = [
  3961. 'type' => 'image_url',
  3962. 'image_url' => [
  3963. 'url' => $videoParams['first_frame_url'],
  3964. ],
  3965. 'role' => 'reference_image',
  3966. ];
  3967. if (isset($videoParams['tail_frame_url'])) {
  3968. $videoParams['content'][] = [
  3969. 'type' => 'image_url',
  3970. 'image_url' => [
  3971. 'url' => $videoParams['tail_frame_url'],
  3972. ],
  3973. 'role' => 'reference_image',
  3974. ];
  3975. }
  3976. }else {
  3977. $videoParams['content'][] = [
  3978. 'type' => 'image_url',
  3979. 'image_url' => [
  3980. 'url' => $videoParams['first_frame_url'],
  3981. ],
  3982. 'role' => 'first_frame',
  3983. ];
  3984. if (isset($videoParams['tail_frame_url'])) {
  3985. $videoParams['content'][] = [
  3986. 'type' => 'image_url',
  3987. 'image_url' => [
  3988. 'url' => $videoParams['tail_frame_url'],
  3989. ],
  3990. 'role' => 'last_frame',
  3991. ];
  3992. }
  3993. }
  3994. }
  3995. // 获取配音音频URL
  3996. $audioUrl = getProp($segment, 'audio_url');
  3997. $audioDuration = getProp($segment, 'audio_duration');
  3998. // 音频传入的前提:必须有至少一张图片或一个视频
  3999. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4000. // 余额预检:按预估时长计算所需积分,不足直接报错
  4001. $chargeDuration = (int)ceil((float)$audioDuration);
  4002. if ($chargeDuration <= 0) {
  4003. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4004. }
  4005. $this->pointsService->checkUserPointsEnough(
  4006. $this->pointsService->getVideoChargePoints([
  4007. 'model' => $model,
  4008. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4009. 'video_duration' => $chargeDuration,
  4010. 'ratio' => $ratio,
  4011. 'generate_audio' => $current_generate_audio,
  4012. ])
  4013. );
  4014. // dd($videoParams);
  4015. // 根据模型选择不同的视频生成方法
  4016. if (strpos($model, 'jimeng') !== false) {
  4017. // 即梦模型参数调整
  4018. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4019. unset($videoParams['content']); // 即梦不使用content格式
  4020. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4021. } elseif (strpos($model, 'kling') !== false) {
  4022. // Keling模型参数调整
  4023. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4024. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4025. unset($videoParams['ratio']);
  4026. unset($videoParams['content']); // Keling不使用content格式
  4027. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4028. } elseif (strpos($model, 'zhizhen') !== false) {
  4029. // 智帧20等新模型使用统一API
  4030. // 构建统一API参数
  4031. $unifiedParams = [
  4032. 'model_code' => $model,
  4033. 'alias_segment_id' => $segment_id,
  4034. 'prompt' => trim($fullPrompt),
  4035. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4036. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4037. 'video_ratio' => $ratio,
  4038. 'seed' => -1,
  4039. ];
  4040. // 构建parameters参数
  4041. $parameters = [
  4042. 'seconds' => $unifiedParams['video_duration'],
  4043. 'resolution' => $unifiedParams['video_resolution'],
  4044. 'ratio' => $ratio,
  4045. // 'video_mode' => 'multi_image',
  4046. // 'mode' => 'multi_image',
  4047. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4048. ];
  4049. $hasImage = false;
  4050. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4051. if ($hasImage) {
  4052. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4053. if (isset($videoParams['tail_frame_url'])) {
  4054. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4055. }
  4056. // 只有在有图片的情况下才能添加参考音频
  4057. if ($audioUrl) {
  4058. // $parameters['reference_audios'] = [$audioUrl];
  4059. }
  4060. } else {
  4061. // 没有图片时,记录错误日志
  4062. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4063. 'segment_id' => $segment_id,
  4064. 'model' => $model
  4065. ]);
  4066. }
  4067. $unifiedParams['parameters'] = $parameters;
  4068. // 调用统一API创建任务
  4069. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4070. } else {
  4071. // Seedance模型(默认)
  4072. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4073. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4074. // 添加配音音频到content中
  4075. $videoParams['content'][] = [
  4076. 'type' => 'audio_url',
  4077. 'audio_url' => [
  4078. 'url' => $audioUrl,
  4079. ],
  4080. 'role' => 'reference_audio',
  4081. ];
  4082. // 优化提示词,增加音频相关描述
  4083. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4084. $videoParams['prompt'] = $audioPrompt;
  4085. $videoParams['content'][0]['text'] = $audioPrompt;
  4086. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4087. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4088. }
  4089. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4090. }
  4091. // 更新分镜表的视频任务信息
  4092. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4093. 'video_task_id' => $task->id,
  4094. 'video_task_status' => '生成中',
  4095. 'generate_audio' => $generate_audio,
  4096. 'updated_at' => date('Y-m-d H:i:s')
  4097. ]);
  4098. return [
  4099. 'task_id' => $task->id,
  4100. 'status' => $task->status,
  4101. 'segment_id' => $segment_id,
  4102. 'video_duration' => $videoDuration
  4103. ];
  4104. }
  4105. public function createActVideoTask($data) {
  4106. $act_id = getProp($data, 'act_id');
  4107. $first_frame_url = getProp($data, 'first_frame_url');
  4108. $tail_frame_url = getProp($data, 'tail_frame_url');
  4109. $generate_audio = getProp($data, 'generate_audio', 1);
  4110. $video_duration = getProp($data, 'video_duration');
  4111. $video_resolution = getProp($data, 'video_resolution');
  4112. $ratio = getProp($data, 'ratio');
  4113. $products = getProp($data, 'products', []);
  4114. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4115. if (!is_array($reference_images) || !is_array($products)) {
  4116. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4117. }
  4118. if (!$act_id) {
  4119. Utils::throwError('1002:片段ID不能为空');
  4120. }
  4121. // 获取片段信息
  4122. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4123. if (!$act) {
  4124. Utils::throwError('20003:片段不存在');
  4125. }
  4126. $act = (array)$act;
  4127. $anime_id = getProp($act, 'anime_id');
  4128. $episode_id = getProp($act, 'episode_id');
  4129. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4130. $ace_mode = getProp($anime, 'ace_mode');
  4131. $art_style_type = getProp($anime, 'art_style_type');
  4132. $art_style = getProp($anime, 'art_style');
  4133. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4134. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4135. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4136. // 将资产中新出现的资产放到extra_products中
  4137. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4138. if (!empty($products) && $episode) {
  4139. // 获取剧集中的角色、场景和道具列表
  4140. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4141. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4142. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4143. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4144. // 构建角色名称列表
  4145. $role_names = array_column($roles, 'role');
  4146. // 构建场景名称列表
  4147. $scene_names = array_column($scenes, 'scene');
  4148. // 构建道具名称列表
  4149. $prop_names = array_column($props, 'prop');
  4150. // 遍历传入的products
  4151. foreach ($products as $product) {
  4152. $product_name = getProp($product, 'product_name');
  4153. // 如果product_name不在roles、scenes和props中
  4154. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4155. // 查找是否在extra_products中存在同名的
  4156. $found = false;
  4157. foreach ($extra_products as $key => $extra_product) {
  4158. if (getProp($extra_product, 'product_name') === $product_name) {
  4159. // 有同名的则覆盖
  4160. $extra_products[$key] = $product;
  4161. $found = true;
  4162. break;
  4163. }
  4164. }
  4165. // 没有则新增
  4166. if (!$found) {
  4167. $extra_products[] = $product;
  4168. }
  4169. }
  4170. }
  4171. if ($extra_products) {
  4172. // 保存到数据库
  4173. DB::table('mp_anime_episodes')
  4174. ->where('id', $episode_id)
  4175. ->update([
  4176. 'extra_products' => json_encode($extra_products, 256),
  4177. 'updated_at' => date('Y-m-d H:i:s')
  4178. ]);
  4179. }
  4180. }
  4181. // 获取分镜内容
  4182. $actContent = getProp($act, 'act_show_content', '');
  4183. // 音效同出(默认使用)
  4184. $current_generate_audio = $generate_audio ? 1 : 0;
  4185. // 构建完整的提示词
  4186. $processResult = $this->processActContentWithProducts($actContent, $products);
  4187. $fullPrompt = $processResult['content'];
  4188. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4189. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4190. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4191. // 处理视频模型
  4192. $model = getProp($data, 'model');
  4193. if (!$model) {
  4194. $model = getProp($episode, 'video_model');
  4195. if (!$model) {
  4196. // episode表也没有,使用默认值
  4197. $model = 'zhizhen-20';
  4198. }
  4199. }
  4200. // 验证模型是否在可用模型表中
  4201. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4202. $model = 'zhizhen-20';
  4203. }
  4204. // 保存到episode表(仅在专用方法中更新模型)
  4205. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4206. // 'video_model' => $model,
  4207. // 'updated_at' => date('Y-m-d H:i:s')
  4208. // ]);
  4209. // 余额预检:按预估时长计算所需积分,不足直接报错
  4210. $chargeDuration = (int)$videoDuration;
  4211. if ($chargeDuration <= 0) {
  4212. $chargeDuration = 5; // 无时长时按默认5秒预估
  4213. }
  4214. $this->pointsService->checkUserPointsEnough(
  4215. $this->pointsService->getVideoChargePoints([
  4216. 'model' => $model,
  4217. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4218. 'video_duration' => $chargeDuration,
  4219. 'ratio' => $ratio,
  4220. 'generate_audio' => $current_generate_audio,
  4221. ])
  4222. );
  4223. // 构建视频生成参数
  4224. $videoParams = [
  4225. 'model' => $model,
  4226. 'alias_act_id' => $act_id,
  4227. 'prompt' => trim($fullPrompt),
  4228. 'video_duration' => $videoDuration,
  4229. 'video_resolution' => $video_resolution,
  4230. 'seed' => -1,
  4231. 'ratio' => $ratio,
  4232. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4233. 'draft' => false,
  4234. 'watermark' => false,
  4235. 'camera_fixed' => false,
  4236. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4237. ];
  4238. // 如果分镜有图片,作为首帧
  4239. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4240. $hasVideo = !empty(getProp($act, 'video_url'));
  4241. if ($hasImage) {
  4242. if ($first_frame_url) {
  4243. $videoParams['first_frame_url'] = $first_frame_url;
  4244. }else {
  4245. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4246. }
  4247. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4248. }
  4249. // 构建content数组
  4250. $videoParams['content'] = [
  4251. [
  4252. 'type' => 'text',
  4253. 'text' => $videoParams['prompt'],
  4254. ]
  4255. ];
  4256. // 如果有首帧图片,添加到content中
  4257. if ($hasImage) {
  4258. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0'])) {
  4259. $videoParams['content'][] = [
  4260. 'type' => 'image_url',
  4261. 'image_url' => [
  4262. 'url' => $videoParams['first_frame_url'],
  4263. ],
  4264. 'role' => 'reference_image',
  4265. ];
  4266. if (isset($videoParams['tail_frame_url'])) {
  4267. $videoParams['content'][] = [
  4268. 'type' => 'image_url',
  4269. 'image_url' => [
  4270. 'url' => $videoParams['tail_frame_url'],
  4271. ],
  4272. 'role' => 'reference_image',
  4273. ];
  4274. }
  4275. }else {
  4276. $videoParams['content'][] = [
  4277. 'type' => 'image_url',
  4278. 'image_url' => [
  4279. 'url' => $videoParams['first_frame_url'],
  4280. ],
  4281. 'role' => 'first_frame',
  4282. ];
  4283. if (isset($videoParams['tail_frame_url'])) {
  4284. $videoParams['content'][] = [
  4285. 'type' => 'image_url',
  4286. 'image_url' => [
  4287. 'url' => $videoParams['tail_frame_url'],
  4288. ],
  4289. 'role' => 'last_frame',
  4290. ];
  4291. }
  4292. }
  4293. }
  4294. // dd($videoParams);
  4295. // 根据模型选择不同的视频生成方法
  4296. if (strpos($model, 'jimeng') !== false) {
  4297. // 即梦模型参数调整
  4298. unset($videoParams['content']); // 即梦不使用content格式
  4299. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4300. } elseif (strpos($model, 'kling') !== false) {
  4301. // Keling模型参数调整
  4302. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4303. unset($videoParams['ratio']);
  4304. unset($videoParams['content']); // Keling不使用content格式
  4305. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4306. } elseif (strpos($model, 'zhizhen') !== false) {
  4307. // 智帧20等新模型使用统一API
  4308. // 构建统一API参数
  4309. $unifiedParams = [
  4310. 'model_code' => $model,
  4311. 'alias_act_id' => $act_id,
  4312. 'prompt' => trim($fullPrompt),
  4313. 'video_duration' => $videoDuration,
  4314. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4315. 'video_ratio' => $ratio,
  4316. 'seed' => -1,
  4317. ];
  4318. // 构建parameters参数
  4319. $parameters = [
  4320. 'seconds' => $unifiedParams['video_duration'],
  4321. 'resolution' => $unifiedParams['video_resolution'],
  4322. 'ratio' => $ratio,
  4323. // 'video_mode' => 'multi_image',
  4324. // 'mode' => 'multi_image',
  4325. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4326. ];
  4327. $hasImage = false;
  4328. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4329. if ($hasImage) {
  4330. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4331. if (isset($videoParams['tail_frame_url'])) {
  4332. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4333. }
  4334. } else {
  4335. // 没有图片时,记录错误日志
  4336. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4337. 'act_id' => $act_id,
  4338. 'model' => $model
  4339. ]);
  4340. }
  4341. if ($reference_images) {
  4342. // 限制只传入9张参考图
  4343. $reference_images = array_slice($reference_images, 0, 9);
  4344. // 在处理之前先保存原始reference_images到任务参数中
  4345. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4346. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4347. $parameters['reference_images'] = $reference_images;
  4348. $parameters['video_mode'] = 'multi_image';
  4349. $parameters['mode'] = 'multi_image';
  4350. }
  4351. $unifiedParams['parameters'] = $parameters;
  4352. // 调用统一API创建任务
  4353. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4354. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4355. // 豆包Seedance 2.0(百度AI网关):图片需要先上传为素材
  4356. // 保存原始参考图用于任务记录
  4357. $videoParams['reference_images'] = $reference_images;
  4358. if ($reference_images) {
  4359. // 限制只传入9张参考图
  4360. $reference_images = array_slice($reference_images, 0, 9);
  4361. // 参考图上传为百度网关素材,上传失败时同步清理提示词中的<图片N>标记
  4362. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt);
  4363. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4364. $videoParams['prompt'] = trim($fullPrompt);
  4365. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4366. $videoParams['reference_image_assets'] = $reference_image_assets;
  4367. }
  4368. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4369. } else {
  4370. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4371. }
  4372. // 更新分镜表的视频任务信息
  4373. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4374. 'video_task_id' => $task->id,
  4375. 'video_task_status' => '生成中',
  4376. 'generate_audio' => $generate_audio,
  4377. 'updated_at' => date('Y-m-d H:i:s')
  4378. ]);
  4379. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4380. $episode_number = getProp($act, 'episode_number');
  4381. $act_number = getProp($act, 'act_number');
  4382. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4383. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4384. }
  4385. return [
  4386. 'task_id' => $task->id,
  4387. 'status' => $task->status,
  4388. 'act_id' => $act_id,
  4389. 'video_duration' => $videoDuration
  4390. ];
  4391. }
  4392. /**
  4393. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4394. *
  4395. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4396. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4397. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4398. *
  4399. * @param array $data
  4400. * @return array
  4401. */
  4402. public function previewCharge(array $data): array
  4403. {
  4404. $mode = (string)getProp($data, 'mode', '');
  4405. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4406. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4407. }
  4408. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4409. $scene = (string)getProp($data, 'scene', 'video_generation');
  4410. $items = [];
  4411. $model = '';
  4412. $resolution = '';
  4413. if ($mode === 'video') {
  4414. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4415. $model = (string)getProp($data, 'model', '');
  4416. if (!$model) {
  4417. Utils::throwError('1002:model参数不能为空');
  4418. }
  4419. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4420. $duration = (int)getProp($data, 'video_duration', 5);
  4421. if ($duration <= 0) {
  4422. $duration = 5;
  4423. }
  4424. $count = max(1, (int)getProp($data, 'count', 1));
  4425. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4426. 'model' => $model,
  4427. 'video_resolution' => $resolution,
  4428. 'video_duration' => $duration,
  4429. 'mode' => $scene,
  4430. ]);
  4431. $points = $pointsPerVideo * $count;
  4432. $items[] = [
  4433. 'type' => 'video',
  4434. 'model' => $model,
  4435. 'video_resolution' => $resolution,
  4436. 'video_duration' => $duration,
  4437. 'count' => $count,
  4438. 'points' => $points,
  4439. ];
  4440. } elseif ($mode === 'image') {
  4441. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4442. $model = (string)getProp($data, 'model', '');
  4443. if (!$model) {
  4444. Utils::throwError('1002:model参数不能为空');
  4445. }
  4446. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4447. if (!$resolution) {
  4448. $width = (int)getProp($data, 'width', 0);
  4449. $height = (int)getProp($data, 'height', 0);
  4450. if ($width <= 0 || $height <= 0) {
  4451. $width = 1600;
  4452. $height = 2848;
  4453. }
  4454. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4455. }
  4456. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4457. $points = $this->pointsService->getImageChargePoints([
  4458. 'model' => $model,
  4459. 'resolution' => $resolution,
  4460. ]) * $imageNum;
  4461. $items[] = [
  4462. 'type' => 'image',
  4463. 'model' => $model,
  4464. 'resolution' => $resolution,
  4465. 'image_num' => $imageNum,
  4466. 'points' => $points,
  4467. ];
  4468. } else {
  4469. // AI对话预估:单次10积分;批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算
  4470. $count = max(1, (int)getProp($data, 'count', 1));
  4471. $animeId = getProp($data, 'anime_id');
  4472. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4473. if ($animeId && $generateEpisodes > 0) {
  4474. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4475. ->where('anime_id', $animeId)
  4476. ->where('is_default', 1)
  4477. ->max('episode_number');
  4478. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4479. $startEpisodeNumber = $currentMaxEpisode + 1;
  4480. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4481. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4482. ->where('anime_id', $animeId)
  4483. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4484. ->whereIn('status', ['pending', 'processing', 'completed'])
  4485. ->count();
  4486. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4487. if ($count < 0) {
  4488. $count = 0;
  4489. }
  4490. }
  4491. $points = PointsService::CHAT_CHARGE_POINTS * $count;
  4492. $items[] = [
  4493. 'type' => 'chat',
  4494. 'count' => $count,
  4495. 'points' => $points,
  4496. ];
  4497. }
  4498. $totalPoints = 0;
  4499. foreach ($items as $item) {
  4500. $totalPoints += $item['points'];
  4501. }
  4502. return [
  4503. 'mode' => $mode,
  4504. 'total_points' => $totalPoints,
  4505. 'items' => $items,
  4506. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4507. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  4508. ];
  4509. }
  4510. /**
  4511. * 根据提示词内容智能计算最优视频时长
  4512. *
  4513. * @param string $segmentContent 分镜内容
  4514. * @param string $tailFrame 尾帧描述
  4515. * @return int 视频时长(2-12秒)
  4516. */
  4517. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4518. // 合并所有文本内容
  4519. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4520. // 如果没有内容,返回默认时长
  4521. if (empty($fullText)) {
  4522. return 5;
  4523. }
  4524. // 计算文本长度(中文字符按2个字符计算)
  4525. $textLength = mb_strlen($fullText, 'UTF-8');
  4526. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4527. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4528. // 分析内容复杂度
  4529. $complexityScore = $this->analyzeContentComplexity($fullText);
  4530. // 基础时长计算(根据文本长度)
  4531. $baseDuration = 3; // 默认2秒
  4532. // if ($adjustedLength <= 20) {
  4533. // $baseDuration = 3;
  4534. // } elseif ($adjustedLength <= 40) {
  4535. // $baseDuration = 4;
  4536. // } elseif ($adjustedLength <= 60) {
  4537. // $baseDuration = 5;
  4538. // } elseif ($adjustedLength <= 80) {
  4539. // $baseDuration = 6;
  4540. // } elseif ($adjustedLength <= 100) {
  4541. // $baseDuration = 7;
  4542. // } elseif ($adjustedLength <= 120) {
  4543. // $baseDuration = 8;
  4544. // } else {
  4545. // $baseDuration = 9;
  4546. // }
  4547. // 根据内容复杂度调整时长
  4548. $finalDuration = $baseDuration + $complexityScore;
  4549. // 确保时长在2-12秒范围内
  4550. return max(4, min(12, $finalDuration));
  4551. }
  4552. /**
  4553. * 分析内容复杂度,返回时长调整值
  4554. *
  4555. * @param string $text 文本内容
  4556. * @return int 调整值(-2到+3)
  4557. */
  4558. private function analyzeContentComplexity($text) {
  4559. $score = 0;
  4560. // 动作关键词(需要更长时间展现)
  4561. $actionKeywords = [
  4562. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4563. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4564. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4565. ];
  4566. // 静态关键词(可以用较短时间)
  4567. $staticKeywords = [
  4568. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4569. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4570. ];
  4571. // 复杂场景关键词(需要更长时间)
  4572. $complexSceneKeywords = [
  4573. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4574. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4575. ];
  4576. // 情感关键词(需要适中时间表现)
  4577. $emotionKeywords = [
  4578. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4579. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4580. ];
  4581. // 检查动作关键词
  4582. foreach ($actionKeywords as $keyword) {
  4583. if (strpos($text, $keyword) !== false) {
  4584. $score += 1;
  4585. break; // 避免重复加分
  4586. }
  4587. }
  4588. // 检查静态关键词
  4589. foreach ($staticKeywords as $keyword) {
  4590. if (strpos($text, $keyword) !== false) {
  4591. $score -= 1;
  4592. break;
  4593. }
  4594. }
  4595. // 检查复杂场景关键词
  4596. foreach ($complexSceneKeywords as $keyword) {
  4597. if (strpos($text, $keyword) !== false) {
  4598. $score += 1;
  4599. break;
  4600. }
  4601. }
  4602. // 检查情感关键词
  4603. foreach ($emotionKeywords as $keyword) {
  4604. if (strpos($text, $keyword) !== false) {
  4605. $score += 1;
  4606. break;
  4607. }
  4608. }
  4609. // 检查时间相关词汇
  4610. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4611. $score += 1;
  4612. }
  4613. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4614. $score -= 1;
  4615. }
  4616. // 检查转场词汇
  4617. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4618. $score += 1;
  4619. }
  4620. // 检查环境描述(复杂环境需要更多时间)
  4621. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4622. $score += 1;
  4623. }
  4624. // 检查对话内容(对话需要更多时间)
  4625. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4626. $score += 1;
  4627. }
  4628. // 限制调整范围
  4629. return max(-1, min(4, $score));
  4630. }
  4631. /**
  4632. * 创建完整视频合成任务
  4633. *
  4634. * @param array $data
  4635. * @return array
  4636. */
  4637. public function createCompleteVideoTask($data)
  4638. {
  4639. $animeId = getProp($data, 'anime_id');
  4640. $episodeId = getProp($data, 'episode_id');
  4641. // 验证参数
  4642. if (!$animeId || !$episodeId) {
  4643. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4644. }
  4645. // 检查是否已存在处理中的任务
  4646. $existingTask = DB::table('mp_complete_video_tasks')
  4647. ->where('anime_id', $animeId)
  4648. ->where('episode_id', $episodeId)
  4649. ->whereIn('generate_status', ['执行中'])
  4650. ->first();
  4651. if ($existingTask) {
  4652. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4653. }
  4654. // 获取全能模式状态
  4655. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4656. if ((int)$ace_mode === 1) {
  4657. // 获取所有片段的配音视频,按 act_number 排序
  4658. $segments = DB::table('mp_episode_segments')
  4659. ->where('anime_id', $animeId)
  4660. ->where('episode_id', $episodeId)
  4661. ->orderBy('segment_number')
  4662. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4663. ->get();
  4664. // 检查是否所有片段都有视频
  4665. $missingVideos = $segments->filter(function($segment) {
  4666. return empty($segment->video_url);
  4667. });
  4668. if ($missingVideos->isNotEmpty()) {
  4669. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4670. }
  4671. }else {
  4672. // 获取所有分镜的配音视频,按 segment_number 排序
  4673. $segments = DB::table('mp_episode_segments')
  4674. ->where('anime_id', $animeId)
  4675. ->where('episode_id', $episodeId)
  4676. ->orderBy('segment_number')
  4677. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4678. ->get();
  4679. // 检查是否所有分镜都有配音和视频
  4680. $missingVideos = $segments->filter(function($segment) {
  4681. return empty($segment->audio_url) || empty($segment->video_url);
  4682. });
  4683. if ($missingVideos->isNotEmpty()) {
  4684. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4685. }
  4686. }
  4687. if ($segments->isEmpty()) {
  4688. Utils::throwError('20003:未找到该剧集的分镜数据');
  4689. }
  4690. // 获取当前完整视频url
  4691. $completeVideoUrl = DB::table('mp_anime_episodes')
  4692. ->where('anime_id', $animeId)
  4693. ->where('id', $episodeId)
  4694. ->value('complete_video_url');
  4695. // 构建 generate_json
  4696. $generateJson = [];
  4697. $sequence = 1;
  4698. foreach ($segments as $segment) {
  4699. if ((int)$ace_mode === 1) {
  4700. $generateJson[] = [
  4701. 'sequence' => $sequence++,
  4702. 'video_url' => $segment->video_url,
  4703. 'video_time_point_start' => $segment->video_time_point_start,
  4704. 'video_time_point_end' => $segment->video_time_point_end
  4705. ];
  4706. }else {
  4707. $generateJson[] = [
  4708. 'sequence' => $sequence++,
  4709. 'video_url' => $segment->video_url,
  4710. 'audio_url' => $segment->audio_url,
  4711. 'video_time_point_start' => $segment->video_time_point_start,
  4712. 'video_time_point_end' => $segment->video_time_point_end
  4713. ];
  4714. }
  4715. }
  4716. // 创建任务
  4717. $now = date('Y-m-d H:i:s');
  4718. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4719. 'anime_id' => $animeId,
  4720. 'episode_id' => $episodeId,
  4721. 'generate_json' => json_encode($generateJson, 256),
  4722. 'generate_status' => '执行中',
  4723. 'complete_video_url' => '',
  4724. 'created_at' => $now,
  4725. 'updated_at' => $now
  4726. ]);
  4727. if (!$taskId) {
  4728. Utils::throwError('20003:创建任务失败');
  4729. }
  4730. // 更新剧集表的任务ID和状态
  4731. $boolen = DB::table('mp_anime_episodes')
  4732. ->where('anime_id', $animeId)
  4733. ->where('id', $episodeId)
  4734. ->update([
  4735. 'complete_video_task_id' => $taskId,
  4736. 'complete_video_task_status' => '执行中',
  4737. 'updated_at' => $now
  4738. ]);
  4739. if (!$boolen) {
  4740. Utils::throwError('20003:更新剧集表失败');
  4741. }
  4742. dLog('anime')->info('创建完整视频合成任务', [
  4743. 'task_id' => $taskId,
  4744. 'anime_id' => $animeId,
  4745. 'episode_id' => $episodeId,
  4746. 'segment_count' => count($generateJson)
  4747. ]);
  4748. // 请求远程服务器执行生成
  4749. $client = new Client(['timeout' => 600, 'verify' => false]);
  4750. try {
  4751. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4752. $response = $result->getBody()->getContents();
  4753. $response_arr = json_decode($response, true);
  4754. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4755. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4756. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4757. // // 更新任务状态为失败
  4758. // DB::table('mp_complete_video_tasks')
  4759. // ->where('id', $taskId)
  4760. // ->update([
  4761. // 'generate_status' => '执行失败',
  4762. // 'error_message' => $error_msg,
  4763. // 'updated_at' => date('Y-m-d H:i:s')
  4764. // ]);
  4765. // // 同步更新剧集表状态
  4766. // DB::table('mp_anime_episodes')
  4767. // ->where('complete_video_task_id', $taskId)
  4768. // ->update([
  4769. // 'complete_video_task_status' => '执行失败',
  4770. // 'updated_at' => date('Y-m-d H:i:s')
  4771. // ]);
  4772. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4773. }
  4774. } catch (\Exception $e) {
  4775. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4776. // 更新任务状态为失败
  4777. DB::table('mp_complete_video_tasks')
  4778. ->where('id', $taskId)
  4779. ->update([
  4780. 'generate_status' => '执行失败',
  4781. 'error_message' => $e->getMessage(),
  4782. 'updated_at' => date('Y-m-d H:i:s')
  4783. ]);
  4784. // 同步更新剧集表状态
  4785. DB::table('mp_anime_episodes')
  4786. ->where('complete_video_task_id', $taskId)
  4787. ->update([
  4788. 'complete_video_task_status' => '执行失败',
  4789. 'updated_at' => date('Y-m-d H:i:s')
  4790. ]);
  4791. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4792. }
  4793. // 开始轮询任务状态
  4794. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4795. $pollInterval = 5; // 每5秒轮询一次
  4796. $attempt = 0;
  4797. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4798. while ($attempt < $maxAttempts) {
  4799. sleep($pollInterval);
  4800. $attempt++;
  4801. // 查询任务状态
  4802. $task = DB::table('mp_complete_video_tasks')
  4803. ->where('id', $taskId)
  4804. ->first();
  4805. if (!$task) {
  4806. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4807. Utils::throwError('20003:任务不存在');
  4808. }
  4809. dLog('anime')->info('轮询任务状态', [
  4810. 'task_id' => $taskId,
  4811. 'attempt' => $attempt,
  4812. 'status' => $task->generate_status
  4813. ]);
  4814. // 检查任务是否完成
  4815. if ($task->generate_status === '执行成功') {
  4816. // 同步更新剧集表状态
  4817. $boolen3 = DB::table('mp_anime_episodes')
  4818. ->where('anime_id', $animeId)
  4819. ->where('id', $episodeId)
  4820. ->update([
  4821. 'complete_video_url' => $task->complete_video_url,
  4822. 'complete_video_task_status' => '执行成功',
  4823. 'updated_at' => date('Y-m-d H:i:s')
  4824. ]);
  4825. dLog('anime')->info('视频合成任务完成', [
  4826. 'task_id' => $taskId,
  4827. 'video_url' => $task->complete_video_url,
  4828. 'attempts' => $attempt
  4829. ]);
  4830. // 如果更新成功则远程删除之前的文件
  4831. if ($boolen3 && $completeVideoUrl) {
  4832. $encode_url = urlencode($completeVideoUrl);
  4833. $client = new Client(['timeout' => 300, 'verify' => false]);
  4834. // 根据ID通过API通知合成音频
  4835. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4836. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4837. $response = $result->getBody()->getContents();
  4838. $response_arr = json_decode($response, true);
  4839. Log::info('火山删除音频返回: '.$response);
  4840. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4841. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4842. Log::info('火山删除音频失败: '.$error_msg);
  4843. // Utils::throwError('20003:火山删除音频失败');
  4844. }
  4845. }
  4846. return [
  4847. 'task_id' => $taskId,
  4848. 'anime_id' => $animeId,
  4849. 'episode_id' => $episodeId,
  4850. 'segment_count' => count($generateJson),
  4851. 'generate_status' => '执行成功',
  4852. 'complete_video_url' => $task->complete_video_url,
  4853. ];
  4854. }
  4855. // 检查任务是否失败
  4856. if ($task->generate_status === '执行失败') {
  4857. // 同步更新剧集表状态
  4858. DB::table('mp_anime_episodes')
  4859. ->where('anime_id', $animeId)
  4860. ->where('id', $episodeId)
  4861. ->update([
  4862. 'complete_video_task_status' => '执行失败',
  4863. 'updated_at' => date('Y-m-d H:i:s')
  4864. ]);
  4865. $errorMessage = $task->error_message ?? '未知错误';
  4866. dLog('anime')->error('视频合成任务失败', [
  4867. 'task_id' => $taskId,
  4868. 'error' => $errorMessage,
  4869. 'attempts' => $attempt
  4870. ]);
  4871. return [
  4872. 'task_id' => $taskId,
  4873. 'anime_id' => $animeId,
  4874. 'episode_id' => $episodeId,
  4875. 'segment_count' => count($generateJson),
  4876. 'generate_status' => '执行失败',
  4877. 'error_message' => $errorMessage
  4878. ];
  4879. }
  4880. }
  4881. // 超时处理
  4882. dLog('anime')->warning('视频合成任务超时', [
  4883. 'task_id' => $taskId,
  4884. 'max_attempts' => $maxAttempts,
  4885. 'timeout_seconds' => $maxAttempts * $pollInterval
  4886. ]);
  4887. // 更新任务状态为超时
  4888. DB::table('mp_complete_video_tasks')
  4889. ->where('id', $taskId)
  4890. ->update([
  4891. 'generate_status' => '超时',
  4892. 'error_message' => '任务执行超时(5分钟)',
  4893. 'updated_at' => date('Y-m-d H:i:s')
  4894. ]);
  4895. return [
  4896. 'task_id' => $taskId,
  4897. 'anime_id' => $animeId,
  4898. 'episode_id' => $episodeId,
  4899. 'segment_count' => count($generateJson),
  4900. 'generate_status' => '超时',
  4901. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4902. ];
  4903. }
  4904. /**
  4905. * 根据 inner_prompt_type 附加内置提示词
  4906. *
  4907. * @param string $prompt 用户提示词
  4908. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  4909. * @return string 合并后的提示词
  4910. */
  4911. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  4912. {
  4913. $innerPromptMap = [
  4914. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  4915. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  4916. ];
  4917. if (!isset($innerPromptMap[$innerPromptType])) {
  4918. return $prompt;
  4919. }
  4920. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  4921. }
  4922. /**
  4923. * 根据 inner_prompt_type 获取生成图片数量
  4924. *
  4925. * @param int $innerPromptType 内置提示词类型
  4926. * @return int 图片数量
  4927. */
  4928. public static function getInnerImageNum($innerPromptType = 0)
  4929. {
  4930. return (int)$innerPromptType === 2 ? 9 : 1;
  4931. }
  4932. /**
  4933. * 提取图片生成结果URL
  4934. *
  4935. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  4936. * @param int $innerPromptType 内置提示词类型
  4937. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  4938. */
  4939. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  4940. {
  4941. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  4942. if (is_array($resultUrls) && !empty($resultUrls)) {
  4943. $resultUrls = array_values($resultUrls);
  4944. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  4945. }
  4946. if (!empty($resultUrl)) {
  4947. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  4948. }
  4949. return (int)$innerPromptType === 2 ? [] : '';
  4950. }
  4951. public function generateImg($data) {
  4952. $prompt = getProp($data, 'prompt');
  4953. $episode_id = getProp($data, 'episode_id');
  4954. $ref_img_urls = getProp($data, 'ref_img_urls');
  4955. $ratio = getProp($data, 'ratio', '9:16');
  4956. $resolution = getProp($data, 'resolution', '2k');
  4957. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  4958. // 定义分辨率和宽高比对应的尺寸映射表
  4959. $sizeMap = [
  4960. '2k' => [
  4961. '1:1' => ['width' => 2048, 'height' => 2048],
  4962. '4:3' => ['width' => 2304, 'height' => 1728],
  4963. '3:4' => ['width' => 1728, 'height' => 2304],
  4964. '16:9' => ['width' => 2848, 'height' => 1600],
  4965. '9:16' => ['width' => 1600, 'height' => 2848],
  4966. '3:2' => ['width' => 2496, 'height' => 1664],
  4967. '2:3' => ['width' => 1664, 'height' => 2496],
  4968. '21:9' => ['width' => 3136, 'height' => 1344],
  4969. ],
  4970. '3k' => [
  4971. '1:1' => ['width' => 3072, 'height' => 3072],
  4972. '4:3' => ['width' => 3456, 'height' => 2592],
  4973. '3:4' => ['width' => 2592, 'height' => 3456],
  4974. '16:9' => ['width' => 4096, 'height' => 2304],
  4975. '9:16' => ['width' => 2304, 'height' => 4096],
  4976. '2:3' => ['width' => 2496, 'height' => 3744],
  4977. '3:2' => ['width' => 3744, 'height' => 2496],
  4978. '21:9' => ['width' => 4704, 'height' => 2016],
  4979. ],
  4980. '4k' => [
  4981. '1:1' => ['width' => 4096, 'height' => 4096],
  4982. '3:4' => ['width' => 3520, 'height' => 4704],
  4983. '4:3' => ['width' => 4704, 'height' => 3520],
  4984. '16:9' => ['width' => 5504, 'height' => 3040],
  4985. '9:16' => ['width' => 3040, 'height' => 5504],
  4986. '2:3' => ['width' => 3328, 'height' => 4992],
  4987. '3:2' => ['width' => 4992, 'height' => 3328],
  4988. '21:9' => ['width' => 6240, 'height' => 2656],
  4989. ],
  4990. ];
  4991. // 参数验证
  4992. $resolution = strtolower($resolution);
  4993. if (!isset($sizeMap[$resolution])) {
  4994. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  4995. }
  4996. if (!isset($sizeMap[$resolution][$ratio])) {
  4997. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  4998. }
  4999. // 根据 ratio 和 resolution 确定宽高
  5000. $width = $sizeMap[$resolution][$ratio]['width'];
  5001. $height = $sizeMap[$resolution][$ratio]['height'];
  5002. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5003. if (is_json($ref_img_urls)) {
  5004. $ref_img_urls = json_decode($ref_img_urls, true);
  5005. }else {
  5006. $ref_img_urls = explode(',', $ref_img_urls);
  5007. }
  5008. }
  5009. // 处理图片模型
  5010. $model = getProp($data, 'model');
  5011. if (!$model) {
  5012. // 用户没有输入,从episode表获取
  5013. if ($episode_id) {
  5014. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5015. $model = getProp($episode, 'image_model');
  5016. }
  5017. if (!$model) {
  5018. // episode表也没有,使用默认值
  5019. $model = 'doubao-seedream-5-0-lite-260128';
  5020. }
  5021. }
  5022. // 验证模型是否在可用模型表中
  5023. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5024. // $model = 'doubao-seedream-5-0-lite-260128';
  5025. Utils::throwError('20003:该模型已不可用,请更换!');
  5026. }
  5027. // 保存到episode表
  5028. if ($episode_id) {
  5029. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5030. 'image_model' => $model,
  5031. 'updated_at' => date('Y-m-d H:i:s')
  5032. ]);
  5033. }
  5034. // 参数验证
  5035. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5036. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5037. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5038. $imageNum = self::getInnerImageNum($inner_prompt_type);
  5039. try {
  5040. // 创建图片生成任务
  5041. $params = [
  5042. 'prompt' => $prompt,
  5043. 'model' => $model,
  5044. 'ref_img_urls' => '',
  5045. 'width' => $width,
  5046. 'height' => $height,
  5047. 'image_num' => $imageNum
  5048. ];
  5049. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5050. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5051. $task_id = $task->id;
  5052. if (!$task_id) {
  5053. Utils::throwError('20003:创建图片生成任务失败');
  5054. }
  5055. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5056. $model = getProp($task, 'model');
  5057. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5058. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5059. $isSyncModel = $isVolcModel || $isGptModel;
  5060. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5061. $start_time = time();
  5062. $timeout = 300; // 5分钟
  5063. $img_url = '';
  5064. while (time() - $start_time < $timeout) {
  5065. sleep(3);
  5066. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5067. if ($isSyncModel) {
  5068. // 刷新任务状态
  5069. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5070. if ($task->status === 'success' && $task->result_url) {
  5071. $img_url = self::extractResultUrls($task->result_url, $inner_prompt_type);
  5072. break;
  5073. } elseif ($task->status === 'failed') {
  5074. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5075. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5076. }
  5077. // // 如果还在处理中,提示用户稍后查看
  5078. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5079. }else {
  5080. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5081. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5082. if ($statusInfo['status'] === 'success') {
  5083. $task->updateStatus('success', [
  5084. 'result_url' => $statusInfo['result_url'],
  5085. 'result_json' => $statusInfo['result_json'] ?? []
  5086. ]);
  5087. $img_url = self::extractResultUrls($statusInfo['result_url'], $inner_prompt_type);
  5088. break;
  5089. } elseif ($statusInfo['status'] === 'failed') {
  5090. $task->updateStatus('failed', [
  5091. 'error_message' => $statusInfo['error_message'],
  5092. 'result_json' => $statusInfo['result_json'] ?? []
  5093. ]);
  5094. dLog('anime')->error('图片生成失败,', [
  5095. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5096. ]);
  5097. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5098. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5099. }
  5100. }
  5101. }
  5102. if (empty($img_url)) {
  5103. Utils::throwError('20003:图片生成超时,请稍后重试');
  5104. }
  5105. return $img_url;
  5106. } catch (\Exception $e) {
  5107. dLog('anime')->error('更新角色或场景失败', [
  5108. 'error' => $e->getMessage()
  5109. ]);
  5110. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5111. Utils::throwError('20003:' . $e->getMessage());
  5112. }
  5113. }
  5114. /**
  5115. * 使用文生文模型解析分镜内容
  5116. */
  5117. private function parseSegmentContentWithAI($segment_content) {
  5118. try {
  5119. // 使用DeepSeek服务的公开方法解析分镜内容
  5120. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5121. } catch (\Exception $e) {
  5122. // 如果AI解析失败,记录日志并返回原内容
  5123. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5124. return $segment_content;
  5125. }
  5126. }
  5127. /**
  5128. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5129. *
  5130. * @param int $episode_id 分集ID
  5131. * @param int $anime_id 动漫ID
  5132. * @param array $roles 分集角色数组(引用传递)
  5133. * @param array $scenes 分集场景数组(引用传递)
  5134. * @param array $episode 分集数据
  5135. */
  5136. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5137. // 获取全局动漫的角色和场景数据
  5138. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5139. if (!$anime) return;
  5140. $art_style_type = getProp($anime, 'art_style_type');
  5141. $character_prefix = '';
  5142. $scene_prefix = '';
  5143. if ($art_style_type) {
  5144. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5145. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5146. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5147. }
  5148. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5149. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5150. $roles_updated = false;
  5151. $scenes_updated = false;
  5152. // 处理角色
  5153. foreach ($roles as &$role) {
  5154. $role_name = getProp($role, 'role');
  5155. $role_description = getProp($role, 'description');
  5156. $role_pic_prompt = getProp($role, 'pic_prompt');
  5157. $role_url = getProp($role, 'url');
  5158. $role_task_id = getProp($role, 'task_id');
  5159. // 如果已有URL或已有任务ID,跳过
  5160. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5161. continue;
  5162. }
  5163. $url_inherited = false;
  5164. // 尝试从全局数据中继承
  5165. foreach ($global_roles as $global_role) {
  5166. $global_role_name = getProp($global_role, 'role');
  5167. $global_role_description = getProp($global_role, 'description');
  5168. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5169. $global_role_url = getProp($global_role, 'url');
  5170. $global_role_task_id = getProp($global_role, 'task_id');
  5171. $global_role_task_status = getProp($global_role, 'task_status');
  5172. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5173. if ($role_name === $global_role_name
  5174. && $role_description === $global_role_description
  5175. && $role_pic_prompt === $global_role_pic_prompt
  5176. && !empty($global_role_url)) {
  5177. // 继承 task_id、task_status 和 url
  5178. $role['task_id'] = $global_role_task_id;
  5179. $role['task_status'] = $global_role_task_status;
  5180. $role['url'] = $global_role_url;
  5181. $roles_updated = true;
  5182. $url_inherited = true;
  5183. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5184. break;
  5185. }
  5186. }
  5187. // 如果无法继承且没有任务ID,创建新任务
  5188. if (!$url_inherited && empty($role_task_id)) {
  5189. try {
  5190. $art_style = getProp($episode, 'art_style');
  5191. // 优先使用 pic_prompt,如果没有则使用 description
  5192. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5193. // if ($art_style) {
  5194. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5195. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5196. // }
  5197. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5198. $params = [
  5199. 'prompt' => $description,
  5200. 'ref_img_urls' => []
  5201. ];
  5202. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5203. $task_id = $task->id;
  5204. if ($task_id) {
  5205. $role['task_id'] = $task_id;
  5206. $role['task_status'] = 'processing';
  5207. $roles_updated = true;
  5208. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5209. }
  5210. } catch (\Exception $e) {
  5211. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5212. }
  5213. }
  5214. }
  5215. // 处理场景
  5216. foreach ($scenes as &$scene) {
  5217. $scene_name = getProp($scene, 'scene');
  5218. $scene_description = getProp($scene, 'description');
  5219. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5220. $scene_url = getProp($scene, 'url');
  5221. $scene_task_id = getProp($scene, 'task_id');
  5222. // 如果已有URL或已有任务ID,跳过
  5223. if (!empty($scene_url) || !empty($scene_task_id)) {
  5224. continue;
  5225. }
  5226. $url_inherited = false;
  5227. // 尝试从全局数据中继承
  5228. foreach ($global_scenes as $global_scene) {
  5229. $global_scene_name = getProp($global_scene, 'scene');
  5230. $global_scene_description = getProp($global_scene, 'description');
  5231. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5232. $global_scene_url = getProp($global_scene, 'url');
  5233. $global_scene_task_id = getProp($global_scene, 'task_id');
  5234. $global_scene_task_status = getProp($global_scene, 'task_status');
  5235. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5236. if ($scene_name === $global_scene_name
  5237. && $scene_description === $global_scene_description
  5238. && $scene_pic_prompt === $global_scene_pic_prompt
  5239. && !empty($global_scene_url)) {
  5240. // 继承 task_id、task_status 和 url
  5241. $scene['task_id'] = $global_scene_task_id;
  5242. $scene['task_status'] = $global_scene_task_status;
  5243. $scene['url'] = $global_scene_url;
  5244. $scenes_updated = true;
  5245. $url_inherited = true;
  5246. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5247. break;
  5248. }
  5249. }
  5250. // 如果无法继承且没有任务ID,创建新任务
  5251. if (!$url_inherited && empty($scene_task_id)) {
  5252. try {
  5253. $art_style = getProp($episode, 'art_style');
  5254. // 优先使用 pic_prompt,如果没有则使用 description
  5255. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5256. // if ($art_style) {
  5257. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5258. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5259. // }
  5260. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5261. $params = [
  5262. 'prompt' => $description,
  5263. 'ref_img_urls' => []
  5264. ];
  5265. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5266. $task_id = $task->id;
  5267. if ($task_id) {
  5268. $scene['task_id'] = $task_id;
  5269. $scene['task_status'] = 'processing';
  5270. $scenes_updated = true;
  5271. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5272. }
  5273. } catch (\Exception $e) {
  5274. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5275. }
  5276. }
  5277. }
  5278. // 如果有更新,保存到数据库
  5279. if ($roles_updated || $scenes_updated) {
  5280. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5281. if ($roles_updated) {
  5282. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5283. }
  5284. if ($scenes_updated) {
  5285. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5286. }
  5287. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5288. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5289. }
  5290. }
  5291. /**
  5292. * 根据图片URL使用AI反推图片提示词
  5293. *
  5294. * @param string $img_url 图片URL
  5295. * @return string 反推的提示词
  5296. */
  5297. private function generateImagePromptFromUrl($img_url) {
  5298. try {
  5299. // 获取默认模型
  5300. $model = 'doubao-seed-2-0-mini-260215';
  5301. // 构建messages参数
  5302. $messages = [
  5303. [
  5304. 'role' => 'user',
  5305. 'content' => [
  5306. [
  5307. 'type' => 'text',
  5308. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5309. ],
  5310. [
  5311. 'type' => 'image_url',
  5312. 'image_url' => [
  5313. 'url' => $img_url
  5314. ]
  5315. ]
  5316. ]
  5317. ]
  5318. ];
  5319. // 构建请求参数
  5320. $params = [
  5321. 'model' => $model,
  5322. 'messages' => $messages,
  5323. 'stream' => false,
  5324. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5325. ];
  5326. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5327. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5328. // 返回生成的内容
  5329. return getProp($result, 'fullContent', '图片描述生成失败');
  5330. } catch (\Exception $e) {
  5331. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5332. 'img_url' => $img_url
  5333. ]);
  5334. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5335. 'error' => $e->getMessage(),
  5336. 'img_url' => $img_url
  5337. ]);
  5338. return '图片描述生成失败: ' . $e->getMessage();
  5339. }
  5340. }
  5341. /**
  5342. * 音频试听接口
  5343. * 创建音频任务并轮询获取结果
  5344. *
  5345. * @param array $data 参数数组
  5346. * @return array 返回音频URL或错误信息
  5347. */
  5348. public function previewAudio($data) {
  5349. $dialogue = getProp($data, 'dialogue');
  5350. // 必填参数验证
  5351. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5352. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5353. $voice_type = getProp($data, 'voice_type');
  5354. $voice_name = getProp($data, 'voice_name');
  5355. $voice_actor = getProp($data, 'voice_actor');
  5356. $emotion_type = getProp($data, 'emotion_type');
  5357. $gender = getProp($data, 'gender', 0);
  5358. $emotion = getProp($data, 'emotion');
  5359. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5360. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5361. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5362. $pitch = getProp($data, 'pitch', 0);
  5363. try {
  5364. $now = date('Y-m-d H:i:s');
  5365. // 构建生成参数
  5366. $generate_json = json_encode([
  5367. 'text' => $dialogue,
  5368. 'role' => $voice_actor,
  5369. 'voice_type' => $voice_type,
  5370. 'voice_name' => $voice_name,
  5371. 'emotion' => $emotion,
  5372. 'emotion_type' => $emotion_type,
  5373. 'gender' => $gender,
  5374. 'speed_ratio' => $speed_ratio,
  5375. 'loudness_ratio' => $loudness_ratio,
  5376. 'emotion_scale' => $emotion_scale,
  5377. 'pitch' => $pitch,
  5378. ], 256);
  5379. // 请求远程服务器执行生成
  5380. $client = new Client(['timeout' => 600, 'verify' => false]);
  5381. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5382. $response = $result->getBody()->getContents();
  5383. $response_arr = json_decode($response, true);
  5384. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5385. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5386. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5387. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5388. }
  5389. $arr = $response_arr['data'];
  5390. $subtitle_info = $arr['subtitle_info'];
  5391. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5392. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5393. return [
  5394. 'audio_url' => $arr['url'],
  5395. 'subtitle_info' => $subtitle_info,
  5396. 'audio_duration' => round($audio_duration, 2)
  5397. ];
  5398. } catch (\Exception $e) {
  5399. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5400. Utils::throwError('20003:' . $e->getMessage());
  5401. }
  5402. }
  5403. /**
  5404. * 获取角色库列表(支持文件夹递归查询)
  5405. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5406. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5407. */
  5408. public function globalProducts($data) {
  5409. $uid = Site::getUid();
  5410. $cpid = Site::getCpid();
  5411. $role = Site::getRole();
  5412. $id = getProp($data, 'id', 0);
  5413. $parent_id = getProp($data, 'parent_id', 0);
  5414. $product_name = getProp($data, 'product_name');
  5415. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5416. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5417. if (!$product) {
  5418. Utils::throwError('20003:请选择产品类型');
  5419. }
  5420. // 根据角色和is_public参数确定查询范围
  5421. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5422. // user角色:根据is_public参数筛选
  5423. $query_user_ids = [];
  5424. if ($role === 'admin') {
  5425. // admin获取所有个人库和公共库
  5426. $query_user_ids = [$uid, 0];
  5427. } else {
  5428. // user角色根据is_public参数筛选
  5429. if ($is_public == 2) {
  5430. // 个人库+公共库
  5431. $query_user_ids = [$uid, 0];
  5432. } elseif ($is_public == 0) {
  5433. // 仅个人库
  5434. $query_user_ids = [$uid];
  5435. } elseif ($is_public == 1) {
  5436. // 仅公共库
  5437. $query_user_ids = [0];
  5438. }
  5439. }
  5440. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5441. if ($id || $product_name) {
  5442. $query = DB::table('mp_products')
  5443. ->where('cpid', $cpid)
  5444. ->whereIn('user_id', $query_user_ids)
  5445. ->where('is_deleted', 0);
  5446. // 如果指定了 id,按 id 精确查询
  5447. if ($id) {
  5448. $query->where('id', $id);
  5449. }
  5450. // 如果指定了 product_name,按名称模糊查询
  5451. if ($product_name) {
  5452. $query->where('product_name', 'like', "%{$product_name}%");
  5453. }
  5454. // 如果指定了 product,添加筛选条件
  5455. if ($product) {
  5456. $query->where('product', $product);
  5457. }
  5458. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5459. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5460. ->get()
  5461. ->map(function($value) {
  5462. $value = (array)$value;
  5463. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5464. $value['type'] = (int)$value['type'];
  5465. $value['parent_id'] = (int)$value['parent_id'];
  5466. $value['level'] = (int)$value['level'];
  5467. $value['product'] = (int)($value['product'] ?? 1);
  5468. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5469. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5470. unset($value['user_id']);
  5471. return $value;
  5472. })
  5473. ->toArray();
  5474. return $result;
  5475. }
  5476. // 递归获取所有子目录和角色
  5477. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5478. }
  5479. /**
  5480. * 递归获取指定目录下的所有子目录和角色
  5481. * @param int $cpid 公司ID
  5482. * @param int $parent_id 父目录ID
  5483. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5484. * @param array $query_user_ids 用户ID数组(支持多个)
  5485. * @param int $current_uid 当前用户ID(用于排序)
  5486. * @return array
  5487. */
  5488. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5489. // 查询当前层级的所有项(文件夹和角色)
  5490. $query = DB::table('mp_products')
  5491. ->where('cpid', $cpid)
  5492. ->where('is_deleted', 0)
  5493. ->where('parent_id', $parent_id);
  5494. // 添加用户ID验证(支持多个user_id)
  5495. if (!empty($query_user_ids)) {
  5496. $query->whereIn('user_id', $query_user_ids);
  5497. }
  5498. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5499. if ($product) {
  5500. $query->where('product', $product);
  5501. }
  5502. // 排序规则:
  5503. // 1. 文件夹在前(type DESC)
  5504. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5505. // 3. 其他排序规则
  5506. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5507. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5508. ->get();
  5509. $result = [];
  5510. foreach ($items as $item) {
  5511. $itemArray = [
  5512. 'id' => $item->id,
  5513. 'type' => (int)$item->type,
  5514. 'parent_id' => (int)$item->parent_id,
  5515. 'level' => (int)$item->level,
  5516. 'product_name' => $item->product_name,
  5517. 'url' => $item->url,
  5518. 'pic_prompt' => $item->pic_prompt ?? '',
  5519. 'three_view_image_url' => $item->three_view_image_url,
  5520. 'product' => (int)($item->product ?? 1),
  5521. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5522. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5523. ];
  5524. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5525. // 如果是文件夹,递归获取其子项
  5526. if ($item->type == 2) {
  5527. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5528. if (!empty($children)) {
  5529. $itemArray['children'] = $children;
  5530. }
  5531. }
  5532. $result[] = $itemArray;
  5533. }
  5534. return $result;
  5535. }
  5536. /**
  5537. * 创建文件夹
  5538. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5539. * @return int 返回新建文件夹ID
  5540. */
  5541. public function createFolder($data) {
  5542. $uid = Site::getUid();
  5543. $cpid = Site::getCpid();
  5544. $role = Site::getRole();
  5545. $parent_id = getProp($data, 'parent_id', 0);
  5546. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5547. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5548. // 如果是公共库操作,需要admin权限
  5549. if ($is_public && $role !== 'admin') {
  5550. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5551. }
  5552. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5553. $store_uid = $is_public ? 0 : $uid;
  5554. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5555. $product = getProp($data, 'product');
  5556. if (!in_array($product, [1, 2, 3])) {
  5557. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5558. }
  5559. // 验证父文件夹
  5560. $parent_level = 0;
  5561. if ($parent_id > 0) {
  5562. $parent = DB::table('mp_products')
  5563. ->where('id', $parent_id)
  5564. ->where('cpid', $cpid)
  5565. ->where('user_id', $store_uid)
  5566. ->where('type', 2)
  5567. ->where('is_deleted', 0)
  5568. ->first();
  5569. if (!$parent) {
  5570. Utils::throwError('20003:父文件夹不存在');
  5571. }
  5572. // 检查父文件夹的 product 类型是否一致
  5573. if ($parent->product != $product) {
  5574. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5575. }
  5576. $parent_level = $parent->level;
  5577. // 检查层级限制(最多3层)
  5578. if ($parent_level >= 3) {
  5579. Utils::throwError('20003:文件夹层级不能超过3层');
  5580. }
  5581. }
  5582. // 检查当前目录下是否已存在空白文件夹
  5583. $empty_folder_exists = DB::table('mp_products')
  5584. ->where('parent_id', $parent_id)
  5585. ->where('cpid', $cpid)
  5586. ->where('user_id', $store_uid)
  5587. ->where('type', 2)
  5588. ->where('product', $product)
  5589. ->where('product_name', '新建文件夹')
  5590. ->where('is_deleted', 0)
  5591. ->exists();
  5592. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5593. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5594. }
  5595. // 创建文件夹
  5596. $folder_id = DB::table('mp_products')->insertGetId([
  5597. 'user_id' => $store_uid,
  5598. 'cpid' => $cpid,
  5599. 'type' => 2,
  5600. 'parent_id' => $parent_id,
  5601. 'level' => $parent_level + 1,
  5602. 'product_name' => $folder_name,
  5603. 'product' => $product,
  5604. 'sort_order' => time(), // 使用时间戳作为排序权重
  5605. 'is_deleted' => 0,
  5606. 'created_at' => date('Y-m-d H:i:s'),
  5607. 'updated_at' => date('Y-m-d H:i:s')
  5608. ]);
  5609. return [
  5610. 'id' => $folder_id,
  5611. 'type' => 2,
  5612. 'parent_id' => $parent_id,
  5613. 'level' => $parent_level + 1,
  5614. 'product_name' => $folder_name,
  5615. 'product' => $product,
  5616. ];
  5617. }
  5618. /**
  5619. * 重命名文件夹或角色
  5620. * @param array $data 包含 id、product_name(新名称)
  5621. * @return bool
  5622. */
  5623. public function renameFolder($data) {
  5624. $uid = Site::getUid();
  5625. $cpid = Site::getCpid();
  5626. $role = Site::getRole();
  5627. $id = getProp($data, 'id');
  5628. $new_name = getProp($data, 'product_name');
  5629. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5630. if (!$id || !$new_name) {
  5631. Utils::throwError('20003:参数不完整');
  5632. }
  5633. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5634. $query_uid = $is_public ? 0 : $uid;
  5635. // 如果是公共库操作,需要admin权限
  5636. if ($is_public && $role !== 'admin') {
  5637. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5638. }
  5639. // 检查是否存在
  5640. $item = DB::table('mp_products')
  5641. ->where('id', $id)
  5642. ->where('cpid', $cpid)
  5643. ->where('user_id', $query_uid)
  5644. ->where('is_deleted', 0)
  5645. ->first();
  5646. if (!$item) {
  5647. Utils::throwError('20003:项目不存在');
  5648. }
  5649. return DB::table('mp_products')
  5650. ->where('id', $id)
  5651. ->where('cpid', $cpid)
  5652. ->where('user_id', $query_uid)
  5653. ->update([
  5654. 'product_name' => $new_name,
  5655. 'updated_at' => date('Y-m-d H:i:s')
  5656. ]);
  5657. }
  5658. /**
  5659. * 移动角色或文件夹到指定文件夹
  5660. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5661. * @return bool
  5662. */
  5663. public function moveProductOrFolder($data) {
  5664. $uid = Site::getUid();
  5665. $cpid = Site::getCpid();
  5666. $role = Site::getRole();
  5667. $id = getProp($data, 'id');
  5668. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5669. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5670. if (!$id) {
  5671. Utils::throwError('20003:请选择要移动的项目');
  5672. }
  5673. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5674. $query_uid = $is_public ? 0 : $uid;
  5675. // 如果是公共库操作,需要admin权限
  5676. if ($is_public && $role !== 'admin') {
  5677. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5678. }
  5679. // 检查要移动的项目
  5680. $item = DB::table('mp_products')
  5681. ->where('id', $id)
  5682. ->where('cpid', $cpid)
  5683. ->where('user_id', $query_uid)
  5684. ->where('is_deleted', 0)
  5685. ->first();
  5686. if (!$item) {
  5687. Utils::throwError('20003:项目不存在');
  5688. }
  5689. // 验证目标文件夹
  5690. $target_level = 0;
  5691. $target_product = $item->product; // 默认使用当前项目的 product
  5692. if ($target_parent_id > 0) {
  5693. $target_parent = DB::table('mp_products')
  5694. ->where('id', $target_parent_id)
  5695. ->where('cpid', $cpid)
  5696. ->where('user_id', $query_uid)
  5697. ->where('type', 2)
  5698. ->where('is_deleted', 0)
  5699. ->first();
  5700. if (!$target_parent) {
  5701. Utils::throwError('20003:目标文件夹不存在');
  5702. }
  5703. // 检查 product 类型是否一致
  5704. if ($target_parent->product != $item->product) {
  5705. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5706. }
  5707. $target_level = $target_parent->level;
  5708. $target_product = $target_parent->product;
  5709. // 如果移动的是文件夹,需要检查层级
  5710. if ($item->type == 2) {
  5711. // 计算移动后的最大层级
  5712. $max_child_level = $this->getMaxChildLevel($id);
  5713. $depth = $max_child_level - $item->level;
  5714. if ($target_level + 1 + $depth > 3) {
  5715. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5716. }
  5717. // 不能移动到自己或自己的子文件夹下
  5718. if ($this->isDescendant($target_parent_id, $id)) {
  5719. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5720. }
  5721. }
  5722. }
  5723. // 更新父文件夹和层级
  5724. $new_level = $target_level + 1;
  5725. DB::table('mp_products')
  5726. ->where('id', $id)
  5727. ->update([
  5728. 'parent_id' => $target_parent_id,
  5729. 'level' => $new_level,
  5730. 'updated_at' => date('Y-m-d H:i:s')
  5731. ]);
  5732. // 如果是文件夹,需要递归更新所有子项的层级
  5733. if ($item->type == 2) {
  5734. $this->updateChildrenLevel($id, $new_level);
  5735. }
  5736. return true;
  5737. }
  5738. /**
  5739. * 获取文件夹下最大子层级
  5740. * @param int $folder_id
  5741. * @return int
  5742. */
  5743. private function getMaxChildLevel($folder_id) {
  5744. $max_level = DB::table('mp_products')
  5745. ->where('parent_id', $folder_id)
  5746. ->where('is_deleted', 0)
  5747. ->max('level');
  5748. if (!$max_level) {
  5749. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5750. }
  5751. // 递归查找子文件夹
  5752. $children = DB::table('mp_products')
  5753. ->where('parent_id', $folder_id)
  5754. ->where('type', 2)
  5755. ->where('is_deleted', 0)
  5756. ->pluck('id');
  5757. foreach ($children as $child_id) {
  5758. $child_max = $this->getMaxChildLevel($child_id);
  5759. if ($child_max > $max_level) {
  5760. $max_level = $child_max;
  5761. }
  5762. }
  5763. return $max_level;
  5764. }
  5765. /**
  5766. * 检查 target_id 是否是 folder_id 的后代
  5767. * @param int $target_id
  5768. * @param int $folder_id
  5769. * @return bool
  5770. */
  5771. private function isDescendant($target_id, $folder_id) {
  5772. if ($target_id == $folder_id) {
  5773. return true;
  5774. }
  5775. $parent = DB::table('mp_products')
  5776. ->where('id', $target_id)
  5777. ->where('is_deleted', 0)
  5778. ->first();
  5779. if (!$parent || $parent->parent_id == 0) {
  5780. return false;
  5781. }
  5782. return $this->isDescendant($parent->parent_id, $folder_id);
  5783. }
  5784. /**
  5785. * 递归更新子项层级
  5786. * @param int $parent_id
  5787. * @param int $parent_level
  5788. */
  5789. private function updateChildrenLevel($parent_id, $parent_level) {
  5790. $children = DB::table('mp_products')
  5791. ->where('parent_id', $parent_id)
  5792. ->where('is_deleted', 0)
  5793. ->get();
  5794. foreach ($children as $child) {
  5795. $new_level = $parent_level + 1;
  5796. DB::table('mp_products')
  5797. ->where('id', $child->id)
  5798. ->update([
  5799. 'level' => $new_level,
  5800. 'updated_at' => date('Y-m-d H:i:s')
  5801. ]);
  5802. // 如果是文件夹,继续递归
  5803. if ($child->type == 2) {
  5804. $this->updateChildrenLevel($child->id, $new_level);
  5805. }
  5806. }
  5807. }
  5808. /**
  5809. * 获取文件夹路径(面包屑导航)
  5810. * @param array $data 包含 folder_id
  5811. * @return array 返回路径数组
  5812. */
  5813. public function getFolderPath($data) {
  5814. $uid = Site::getUid();
  5815. $cpid = Site::getCpid();
  5816. $folder_id = getProp($data, 'id', 0);
  5817. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5818. if ($folder_id == 0) {
  5819. return [
  5820. ['id' => 0, 'name' => '根目录']
  5821. ];
  5822. }
  5823. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5824. $query_uid = $is_public ? 0 : $uid;
  5825. $path = [];
  5826. $current_id = $folder_id;
  5827. while ($current_id > 0) {
  5828. $folder = DB::table('mp_products')
  5829. ->where('id', $current_id)
  5830. ->where('cpid', $cpid)
  5831. ->where('user_id', $query_uid)
  5832. ->where('type', 2)
  5833. ->where('is_deleted', 0)
  5834. ->first();
  5835. if (!$folder) {
  5836. break;
  5837. }
  5838. array_unshift($path, [
  5839. 'id' => $folder->id,
  5840. 'name' => $folder->product_name
  5841. ]);
  5842. $current_id = $folder->parent_id;
  5843. }
  5844. // 添加根目录
  5845. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5846. return $path;
  5847. }
  5848. public function createProduct($data) {
  5849. $uid = Site::getUid();
  5850. $cpid = Site::getCpid();
  5851. $role = Site::getRole();
  5852. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5853. // 如果是公共库操作,需要admin权限
  5854. if ($is_public && $role !== 'admin') {
  5855. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5856. }
  5857. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5858. $store_uid = $is_public ? 0 : $uid;
  5859. $product_name = trim(getProp($data, 'product_name'));
  5860. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5861. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5862. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5863. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5864. $url = trim(getProp($data, 'url'));
  5865. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5866. $versions = getProp($data, 'versions');
  5867. // 检查是否是正确的图片格式
  5868. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5869. $urlPath = parse_url($url, PHP_URL_PATH);
  5870. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5871. if (!in_array($extension, $allowedExtensions)) {
  5872. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5873. }
  5874. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5875. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5876. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5877. $product = getProp($data, 'product');
  5878. if (!in_array($product, [1, 2, 3])) {
  5879. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5880. }
  5881. // 获取父文件夹ID和层级
  5882. $parent_id = getProp($data, 'parent_id', 0);
  5883. $parent_level = 0;
  5884. if ($parent_id > 0) {
  5885. $parent = DB::table('mp_products')
  5886. ->where('id', $parent_id)
  5887. ->where('cpid', $cpid)
  5888. ->where('user_id', $store_uid)
  5889. ->where('type', 2)
  5890. ->where('is_deleted', 0)
  5891. ->first();
  5892. if (!$parent) {
  5893. Utils::throwError('20003:父文件夹不存在');
  5894. }
  5895. $parent_level = $parent->level;
  5896. }
  5897. $id = DB::table('mp_products')->insertGetId([
  5898. 'user_id' => $store_uid,
  5899. 'cpid' => $cpid,
  5900. 'type' => 1, // 1=角色图片
  5901. 'parent_id' => $parent_id,
  5902. 'level' => $parent_level + 1,
  5903. 'product_name' => $product_name,
  5904. 'url' => $url,
  5905. 'pic_prompt' => $pic_prompt,
  5906. 'product' => $product,
  5907. 'versions' => json_encode($versions, 256),
  5908. 'sort_order' => time(), // 使用时间戳作为排序权重
  5909. 'created_at' => date('Y-m-d H:i:s'),
  5910. 'updated_at' => date('Y-m-d H:i:s')
  5911. ]);
  5912. if (!$id) Utils::throwError('20003:创建失败');
  5913. return [
  5914. 'id' => $id,
  5915. 'type' => 1,
  5916. 'parent_id' => $parent_id,
  5917. 'level' => $parent_level + 1,
  5918. 'product_name' => $product_name,
  5919. 'url' => $url,
  5920. 'pic_prompt' => $pic_prompt,
  5921. 'product' => $product,
  5922. 'versions' => $versions
  5923. ];
  5924. }
  5925. public function editProduct($data) {
  5926. $uid = Site::getUid();
  5927. $cpid = Site::getCpid();
  5928. $role = Site::getRole();
  5929. $id = getProp($data, 'id');
  5930. if (!$id) Utils::throwError('20003:ID不能为空');
  5931. $versions = getProp($data, 'versions');
  5932. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5933. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5934. $query_uid = $is_public ? 0 : $uid;
  5935. // 如果是公共库操作,需要admin权限
  5936. if ($is_public && $role !== 'admin') {
  5937. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5938. }
  5939. // 检查是否存在且属于当前用户或公共库
  5940. $role = DB::table('mp_products')
  5941. ->where('id', $id)
  5942. ->where('cpid', $cpid)
  5943. ->where('user_id', $query_uid)
  5944. ->where('type', 1)->first();
  5945. if (!$role) Utils::throwError('20003:记录不存在');
  5946. $updateData = [];
  5947. // $needVersionRecord = false; // 是否需要记录版本
  5948. // 名称
  5949. $product_name = trim(getProp($data, 'product_name'));
  5950. if ($product_name) {
  5951. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5952. $updateData['product_name'] = $product_name;
  5953. }
  5954. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5955. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  5956. // 图片地址
  5957. $url = trim(getProp($data, 'url'));
  5958. if ($url) {
  5959. // 检查是否是正确的图片格式
  5960. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5961. $urlPath = parse_url($url, PHP_URL_PATH);
  5962. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5963. if (!in_array($extension, $allowedExtensions)) {
  5964. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5965. }
  5966. // // 如果 url 有变更,记录版本
  5967. // if ($url !== $role->url) {
  5968. // $needVersionRecord = true;
  5969. // }
  5970. $updateData['url'] = $url;
  5971. }
  5972. // 提示词
  5973. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5974. if ($pic_prompt) {
  5975. // // 如果 pic_prompt 有变更,记录版本
  5976. // if ($pic_prompt !== $role->pic_prompt) {
  5977. // $needVersionRecord = true;
  5978. // }
  5979. $updateData['pic_prompt'] = $pic_prompt;
  5980. }
  5981. if (empty($updateData)) {
  5982. Utils::throwError('20003:没有需要更新的数据');
  5983. }
  5984. // // 如果需要记录版本,将数据添加到 versions 数组
  5985. // if ($needVersionRecord) {
  5986. // // 获取现有的 versions 数据
  5987. // $versions = json_decode($role->versions, true) ?: [];
  5988. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  5989. // // 如果是第一次记录版本,先添加旧版本(变更前)
  5990. // if ($isFirstVersion) {
  5991. // $oldVersion = [
  5992. // 'url' => $role->url,
  5993. // 'description' => $role->pic_prompt,
  5994. // ];
  5995. // // 旧版本添加到数组末尾
  5996. // $versions[] = $oldVersion;
  5997. // }
  5998. // // 构建新版本(变更后)
  5999. // $newVersion = [
  6000. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6001. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6002. // ];
  6003. // // 检查新版本是否已存在于历史版本中
  6004. // $existingIndex = -1;
  6005. // foreach ($versions as $index => $version) {
  6006. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6007. // $existingIndex = $index;
  6008. // break;
  6009. // }
  6010. // }
  6011. // if ($existingIndex !== -1) {
  6012. // // 如果已存在,移除旧的位置
  6013. // array_splice($versions, $existingIndex, 1);
  6014. // }
  6015. // // 新版本添加到数组开头(最新的在前)
  6016. // array_unshift($versions, $newVersion);
  6017. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6018. // // if (count($versions) > 10) {
  6019. // // $versions = array_slice($versions, 0, 10);
  6020. // // }
  6021. // $updateData['versions'] = json_encode($versions, 256);
  6022. // }
  6023. if ($versions) {
  6024. $updateData['versions'] = json_encode($versions, 256);
  6025. }
  6026. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6027. return DB::table('mp_products')
  6028. ->where('cpid', $cpid)
  6029. ->where('id', $id)->update($updateData);
  6030. }
  6031. /**
  6032. * 获取角色版本历史
  6033. * @param array $data 包含 id(角色ID)
  6034. * @return array 返回版本历史列表
  6035. */
  6036. public function getProductVersions($data) {
  6037. $cpid = Site::getCpid();
  6038. $id = getProp($data, 'id');
  6039. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6040. $role = DB::table('mp_products')
  6041. ->where('id', $id)
  6042. ->where('cpid', $cpid)
  6043. ->where('type', 1)
  6044. ->first();
  6045. if (!$role) Utils::throwError('20003:角色不存在');
  6046. // 获取版本历史
  6047. $versions = json_decode($role->versions, true) ?: [];
  6048. // 添加当前版本作为最新版本
  6049. $currentVersion = [
  6050. 'version' => 0, // 0 表示当前版本
  6051. 'url' => $role->url,
  6052. 'pic_prompt' => $role->pic_prompt,
  6053. 'updated_at' => $role->updated_at,
  6054. 'is_current' => true
  6055. ];
  6056. array_unshift($versions, $currentVersion);
  6057. return $versions;
  6058. }
  6059. /**
  6060. * 恢复到指定版本
  6061. * @param array $data 包含 id(角色ID)、version(版本号)
  6062. * @return bool
  6063. */
  6064. public function restoreProductVersion($data) {
  6065. $uid = Site::getUid();
  6066. $cpid = Site::getCpid();
  6067. $id = getProp($data, 'id');
  6068. $version = getProp($data, 'version');
  6069. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6070. if (!$version) Utils::throwError('20003:版本号不能为空');
  6071. $role = DB::table('mp_products')
  6072. ->where('id', $id)
  6073. ->where('cpid', $cpid)
  6074. ->where('type', 1)
  6075. ->first();
  6076. if (!$role) Utils::throwError('20003:角色不存在');
  6077. // 获取版本历史
  6078. $versions = json_decode($role->versions, true) ?: [];
  6079. // 查找指定版本
  6080. $targetVersion = null;
  6081. foreach ($versions as $v) {
  6082. if ($v['version'] == $version) {
  6083. $targetVersion = $v;
  6084. break;
  6085. }
  6086. }
  6087. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6088. // 先将当前版本保存到历史
  6089. $newVersion = [
  6090. 'version' => count($versions) + 1,
  6091. 'url' => $role->url,
  6092. 'pic_prompt' => $role->pic_prompt,
  6093. 'updated_at' => date('Y-m-d H:i:s'),
  6094. 'updated_by' => $uid
  6095. ];
  6096. array_unshift($versions, $newVersion);
  6097. // 限制版本数量
  6098. if (count($versions) > 10) {
  6099. $versions = array_slice($versions, 0, 10);
  6100. }
  6101. // 恢复到指定版本
  6102. return DB::table('mp_products')
  6103. ->where('id', $id)
  6104. ->where('cpid', $cpid)
  6105. ->update([
  6106. 'url' => $targetVersion['url'],
  6107. 'pic_prompt' => $targetVersion['pic_prompt'],
  6108. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6109. 'updated_at' => date('Y-m-d H:i:s')
  6110. ]);
  6111. }
  6112. public function deleteProduct($data) {
  6113. $uid = Site::getUid();
  6114. $cpid = Site::getCpid();
  6115. $role = Site::getRole();
  6116. $id = getProp($data, 'id');
  6117. if (!$id) Utils::throwError('20003:ID不能为空');
  6118. $ids = explode(',', $id);
  6119. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6120. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6121. $query_uid = $is_public ? 0 : $uid;
  6122. // 如果是公共库操作,需要admin权限
  6123. if ($is_public && $role !== 'admin') {
  6124. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6125. }
  6126. // 检查是否存在且属于当前用户或公共库
  6127. $role = DB::table('mp_products')
  6128. ->whereIn('id', $ids)
  6129. ->where('cpid', $cpid)
  6130. ->where('user_id', $query_uid)
  6131. ->get();
  6132. if (!$role) Utils::throwError('20003:记录不存在');
  6133. return DB::table('mp_products')
  6134. ->where('cpid', $cpid)
  6135. ->where('user_id', $query_uid)
  6136. ->whereIn('id', $ids)
  6137. ->update([
  6138. 'is_deleted' => 1,
  6139. 'updated_at' => date('Y-m-d H:i:s')
  6140. ]);
  6141. }
  6142. public function generateThreeView($data) {
  6143. $uid = Site::getUid();
  6144. $cpid = Site::getCpid();
  6145. $role = Site::getRole();
  6146. $id = getProp($data, 'id');
  6147. if (!$id) Utils::throwError('20003:ID不能为空');
  6148. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6149. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6150. $query_uid = $is_public ? 0 : $uid;
  6151. // 如果是公共库操作,需要admin权限
  6152. if ($is_public && $role !== 'admin') {
  6153. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6154. }
  6155. // 检查是否存在且属于当前用户或公共库
  6156. $product = DB::table('mp_products')
  6157. ->where('id', $id)
  6158. ->where('cpid', $cpid)
  6159. ->where('user_id', $query_uid)
  6160. ->where('type', 1)->first();
  6161. if (!$product) Utils::throwError('20003:资产不存在');
  6162. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6163. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6164. if (!$ref_img_url) {
  6165. // 如果没有传入参考图,使用角色表中的图片
  6166. $ref_img_url = $product->url ?? '';
  6167. if (!$ref_img_url) {
  6168. Utils::throwError('20003:参考图不能为空');
  6169. }
  6170. }
  6171. $pic_prompt = getProp($product, 'pic_prompt');
  6172. if ($pic_prompt) {
  6173. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6174. }
  6175. // 检查参考图是否是正确的图片格式
  6176. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6177. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6178. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6179. if (!in_array($extension, $allowedExtensions)) {
  6180. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6181. }
  6182. // 处理图片模型
  6183. $model = getProp($data, 'model');
  6184. if (!$model) {
  6185. // 使用默认模型
  6186. $model = 'doubao-seedream-5-0-lite-260128';
  6187. }
  6188. // 验证模型是否在可用模型表中
  6189. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6190. Utils::throwError('20003:该模型已不可用,请更换!');
  6191. }
  6192. $ratio = getProp($data, 'ratio', '16:9');
  6193. $resolution = getProp($data, 'resolution', '2k');
  6194. // 定义分辨率和宽高比对应的尺寸映射表
  6195. $sizeMap = [
  6196. '2k' => [
  6197. '1:1' => ['width' => 2048, 'height' => 2048],
  6198. '4:3' => ['width' => 2304, 'height' => 1728],
  6199. '3:4' => ['width' => 1728, 'height' => 2304],
  6200. '16:9' => ['width' => 2848, 'height' => 1600],
  6201. '9:16' => ['width' => 1600, 'height' => 2848],
  6202. '3:2' => ['width' => 2496, 'height' => 1664],
  6203. '2:3' => ['width' => 1664, 'height' => 2496],
  6204. '21:9' => ['width' => 3136, 'height' => 1344],
  6205. ],
  6206. '3k' => [
  6207. '1:1' => ['width' => 3072, 'height' => 3072],
  6208. '4:3' => ['width' => 3456, 'height' => 2592],
  6209. '3:4' => ['width' => 2592, 'height' => 3456],
  6210. '16:9' => ['width' => 4096, 'height' => 2304],
  6211. '9:16' => ['width' => 2304, 'height' => 4096],
  6212. '2:3' => ['width' => 2496, 'height' => 3744],
  6213. '3:2' => ['width' => 3744, 'height' => 2496],
  6214. '21:9' => ['width' => 4704, 'height' => 2016],
  6215. ],
  6216. '4k' => [
  6217. '1:1' => ['width' => 4096, 'height' => 4096],
  6218. '3:4' => ['width' => 3520, 'height' => 4704],
  6219. '4:3' => ['width' => 4704, 'height' => 3520],
  6220. '16:9' => ['width' => 5504, 'height' => 3040],
  6221. '9:16' => ['width' => 3040, 'height' => 5504],
  6222. '2:3' => ['width' => 3328, 'height' => 4992],
  6223. '3:2' => ['width' => 4992, 'height' => 3328],
  6224. '21:9' => ['width' => 6240, 'height' => 2656],
  6225. ],
  6226. ];
  6227. // 参数验证
  6228. $resolution = strtolower($resolution);
  6229. if (!isset($sizeMap[$resolution])) {
  6230. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6231. }
  6232. if (!isset($sizeMap[$resolution][$ratio])) {
  6233. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6234. }
  6235. // 根据 ratio 和 resolution 确定宽高
  6236. $width = $sizeMap[$resolution][$ratio]['width'];
  6237. $height = $sizeMap[$resolution][$ratio]['height'];
  6238. try {
  6239. // 创建图片生成任务
  6240. $params = [
  6241. 'prompt' => $prompt,
  6242. 'model' => $model,
  6243. 'ref_img_urls' => [$ref_img_url],
  6244. 'width' => $width,
  6245. 'height' => $height
  6246. ];
  6247. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6248. $task_id = $task->id;
  6249. if (!$task_id) {
  6250. Utils::throwError('20003:创建图片生成任务失败');
  6251. }
  6252. // 轮询获取结果
  6253. // 只查询数据库,不调用API,不更新任务表
  6254. $start_time = time();
  6255. $timeout = 1800;
  6256. $img_url = '';
  6257. while (time() - $start_time < $timeout) {
  6258. sleep(5);
  6259. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6260. $task = DB::table('mp_generate_pic_tasks')
  6261. ->where('id', $task_id)
  6262. ->first();
  6263. if (!$task) {
  6264. Utils::throwError('20003:任务不存在');
  6265. }
  6266. if ($task->status === 'success' && $task->result_url) {
  6267. $result_urls = is_string($task->result_url)
  6268. ? json_decode($task->result_url, true)
  6269. : $task->result_url;
  6270. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6271. break;
  6272. } elseif ($task->status === 'failed') {
  6273. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6274. }
  6275. // 其他状态继续轮询
  6276. }
  6277. if (empty($img_url)) {
  6278. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6279. }
  6280. // 更新 mp_products 表(不是任务表)
  6281. DB::table('mp_products')
  6282. ->where('id', $id)
  6283. ->where('cpid', $cpid)
  6284. ->update([
  6285. 'three_view_image_url' => $img_url,
  6286. 'updated_at' => date('Y-m-d H:i:s')
  6287. ]);
  6288. return ['three_view_image_url' => $img_url];
  6289. } catch (\Exception $e) {
  6290. dLog('anime')->error('生成三视图失败', [
  6291. 'error' => $e->getMessage()
  6292. ]);
  6293. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6294. Utils::throwError('20003:' . $e->getMessage());
  6295. }
  6296. }
  6297. /**
  6298. * 推送(复制)资产或文件夹到目标位置
  6299. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6300. * @return array 返回推送结果
  6301. */
  6302. public function pushProductOrFolder($data) {
  6303. $uid = Site::getUid();
  6304. $cpid = Site::getCpid();
  6305. $role = Site::getRole();
  6306. $product_id = getProp($data, 'product_id');
  6307. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6308. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6309. if (!$product_id) {
  6310. Utils::throwError('20003:请选择要推送的项目');
  6311. }
  6312. // 查询源项目(只通过cpid查询,不限制user_id)
  6313. $sourceItem = DB::table('mp_products')
  6314. ->where('id', $product_id)
  6315. ->where('cpid', $cpid)
  6316. ->where('is_deleted', 0)
  6317. ->first();
  6318. if (!$sourceItem) {
  6319. Utils::throwError('20003:要推送的项目不存在');
  6320. }
  6321. // 通过user_id判断源是公共库还是个人库
  6322. $source_uid = $sourceItem->user_id;
  6323. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6324. // 验证目标文件夹并确定目标是公共库还是个人库
  6325. $target_level = 0;
  6326. $target_uid = $uid; // 默认推送到个人库
  6327. $target_is_public = 0;
  6328. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6329. if ($target_parent_id > 0) {
  6330. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6331. $targetParent = DB::table('mp_products')
  6332. ->where('id', $target_parent_id)
  6333. ->where('cpid', $cpid)
  6334. ->where('type', 2)
  6335. ->where('is_deleted', 0)
  6336. ->first();
  6337. if (!$targetParent) {
  6338. Utils::throwError('20003:目标文件夹不存在');
  6339. }
  6340. // 通过user_id判断目标是公共库还是个人库
  6341. $target_level = $targetParent->level;
  6342. $target_uid = $targetParent->user_id;
  6343. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6344. // 使用目标文件夹的 product 类型
  6345. $final_product_type = $targetParent->product;
  6346. }
  6347. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6348. else {
  6349. $push_to_public = getProp($data, 'push_to_public');
  6350. if ($push_to_public === '') {
  6351. Utils::throwError('20003:请选择是否推送到公共库');
  6352. }
  6353. if ($push_to_public) {
  6354. $target_uid = 0;
  6355. $target_is_public = 1;
  6356. }
  6357. // 推送到根目录时,必须指定 product 类型
  6358. if ($target_product === null || $target_product === '') {
  6359. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6360. }
  6361. $final_product_type = $target_product;
  6362. }
  6363. // 如果目标是公共库,需要admin权限
  6364. if ($target_is_public && $role !== 'admin') {
  6365. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6366. }
  6367. // 权限验证:验证是否符合允许的推送规则
  6368. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6369. try {
  6370. DB::beginTransaction();
  6371. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6372. if ($sourceItem->type == 1) {
  6373. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6374. DB::commit();
  6375. return [
  6376. 'product_id' => $newId,
  6377. ];
  6378. }
  6379. // 如果是文件夹,递归复制(支持跨类型推送)
  6380. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6381. DB::commit();
  6382. return [
  6383. 'product_id' => $newFolderId,
  6384. ];
  6385. } catch (\Exception $e) {
  6386. DB::rollBack();
  6387. dLog('anime')->error('推送失败', [
  6388. 'error' => $e->getMessage(),
  6389. 'product_id' => $product_id
  6390. ]);
  6391. Utils::throwError('20003:' . $e->getMessage());
  6392. }
  6393. }
  6394. /**
  6395. * 验证推送权限
  6396. * 允许的推送规则:
  6397. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6398. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6399. * 3. 公共库推送给公共库(公共库 → 公共库)
  6400. *
  6401. * @param int $source_uid 源的user_id
  6402. * @param int $target_uid 目标的user_id
  6403. * @param int $current_uid 当前用户ID
  6404. * @throws \Exception
  6405. */
  6406. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6407. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6408. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6409. return; // 允许
  6410. }
  6411. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6412. if ($source_uid == 0 && $target_uid == $current_uid) {
  6413. return; // 允许
  6414. }
  6415. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6416. if ($source_uid == 0 && $target_uid == 0) {
  6417. return; // 允许
  6418. }
  6419. // 其他情况都不允许
  6420. if ($source_uid != 0 && $source_uid != $current_uid) {
  6421. // 源是别人的个人库
  6422. Utils::throwError('20003:无权限访问该资产');
  6423. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6424. // 个人库推送给公共库(不允许)
  6425. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6426. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6427. // 不同用户的个人库之间推送(不允许)
  6428. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6429. } else {
  6430. // 其他未知情况
  6431. Utils::throwError('20003:不允许的推送操作');
  6432. }
  6433. }
  6434. /**
  6435. * 复制单个资产
  6436. * @param object $sourceProduct 源资产对象
  6437. * @param int $targetParentId 目标父文件夹ID
  6438. * @param int $targetLevel 目标层级
  6439. * @param int $cpid 公司ID
  6440. * @param int $targetUid 目标用户ID
  6441. * @return int 返回新资产ID
  6442. */
  6443. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  6444. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6445. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  6446. $newProductData = [
  6447. 'user_id' => $targetUid,
  6448. 'cpid' => $cpid,
  6449. 'type' => 1,
  6450. 'parent_id' => $targetParentId,
  6451. 'level' => $targetLevel,
  6452. 'product_name' => $sourceProduct->product_name,
  6453. 'url' => $sourceProduct->url,
  6454. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6455. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6456. 'product' => $finalProductType,
  6457. 'versions' => $sourceProduct->versions ?? '',
  6458. 'sort_order' => time(),
  6459. 'is_deleted' => 0,
  6460. 'created_at' => date('Y-m-d H:i:s'),
  6461. 'updated_at' => date('Y-m-d H:i:s')
  6462. ];
  6463. return DB::table('mp_products')->insertGetId($newProductData);
  6464. }
  6465. /**
  6466. * 递归复制文件夹及其子项
  6467. * @param object $sourceFolder 源文件夹对象
  6468. * @param int $targetParentId 目标父文件夹ID
  6469. * @param int $targetLevel 目标层级
  6470. * @param int $cpid 公司ID
  6471. * @param int $targetUid 目标用户ID
  6472. * @param int $sourceUid 源用户ID
  6473. * @return int 返回新文件夹ID
  6474. */
  6475. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  6476. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6477. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  6478. // 创建新文件夹
  6479. $newFolderData = [
  6480. 'user_id' => $targetUid,
  6481. 'cpid' => $cpid,
  6482. 'type' => 2,
  6483. 'parent_id' => $targetParentId,
  6484. 'level' => $targetLevel,
  6485. 'product_name' => $sourceFolder->product_name,
  6486. 'product' => $finalProductType,
  6487. 'sort_order' => time(),
  6488. 'is_deleted' => 0,
  6489. 'created_at' => date('Y-m-d H:i:s'),
  6490. 'updated_at' => date('Y-m-d H:i:s')
  6491. ];
  6492. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  6493. // 获取源文件夹下的所有子项
  6494. $children = DB::table('mp_products')
  6495. ->where('parent_id', $sourceFolder->id)
  6496. ->where('cpid', $cpid)
  6497. ->where('user_id', $sourceUid)
  6498. ->where('is_deleted', 0)
  6499. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  6500. ->get();
  6501. // 递归复制子项(子项继承目标文件夹的 product 类型)
  6502. foreach ($children as $child) {
  6503. if ($child->type == 1) {
  6504. // 资产
  6505. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  6506. } else {
  6507. // 文件夹
  6508. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  6509. }
  6510. }
  6511. return $newFolderId;
  6512. }
  6513. /**
  6514. * 保存剧本资产关联关系
  6515. * @param array $data 请求参数
  6516. * @return bool
  6517. */
  6518. public function saveScriptProducts($data) {
  6519. $uid = Site::getUid();
  6520. $cpid = Site::getCpid();
  6521. $script_id = getProp($data, 'script_id');
  6522. $products = getProp($data, 'products', []);
  6523. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  6524. if (!$script_id) {
  6525. Utils::throwError('20003:请提供剧本ID');
  6526. }
  6527. // 验证剧本是否存在
  6528. $script = DB::table('mp_scripts')
  6529. ->where('id', $script_id)
  6530. ->where('is_deleted', 0)
  6531. ->first();
  6532. if (!$script) {
  6533. Utils::throwError('20003:剧本不存在');
  6534. }
  6535. // 处理图片模型
  6536. $model = getProp($data, 'model');
  6537. if (!$model) {
  6538. // 使用默认模型
  6539. $model = 'doubao-seedream-5-0-lite-260128';
  6540. }
  6541. // 验证模型是否在可用模型表中
  6542. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6543. Utils::throwError('20003:该模型已不可用,请更换!');
  6544. }
  6545. $ratio = getProp($data, 'ratio', '9:16');
  6546. $resolution = getProp($data, 'resolution', '2k');
  6547. // 定义分辨率和宽高比对应的尺寸映射表
  6548. $sizeMap = [
  6549. '2k' => [
  6550. '1:1' => ['width' => 2048, 'height' => 2048],
  6551. '4:3' => ['width' => 2304, 'height' => 1728],
  6552. '3:4' => ['width' => 1728, 'height' => 2304],
  6553. '16:9' => ['width' => 2848, 'height' => 1600],
  6554. '9:16' => ['width' => 1600, 'height' => 2848],
  6555. '3:2' => ['width' => 2496, 'height' => 1664],
  6556. '2:3' => ['width' => 1664, 'height' => 2496],
  6557. '21:9' => ['width' => 3136, 'height' => 1344],
  6558. ],
  6559. '3k' => [
  6560. '1:1' => ['width' => 3072, 'height' => 3072],
  6561. '4:3' => ['width' => 3456, 'height' => 2592],
  6562. '3:4' => ['width' => 2592, 'height' => 3456],
  6563. '16:9' => ['width' => 4096, 'height' => 2304],
  6564. '9:16' => ['width' => 2304, 'height' => 4096],
  6565. '2:3' => ['width' => 2496, 'height' => 3744],
  6566. '3:2' => ['width' => 3744, 'height' => 2496],
  6567. '21:9' => ['width' => 4704, 'height' => 2016],
  6568. ],
  6569. '4k' => [
  6570. '1:1' => ['width' => 4096, 'height' => 4096],
  6571. '3:4' => ['width' => 3520, 'height' => 4704],
  6572. '4:3' => ['width' => 4704, 'height' => 3520],
  6573. '16:9' => ['width' => 5504, 'height' => 3040],
  6574. '9:16' => ['width' => 3040, 'height' => 5504],
  6575. '2:3' => ['width' => 3328, 'height' => 4992],
  6576. '3:2' => ['width' => 4992, 'height' => 3328],
  6577. '21:9' => ['width' => 6240, 'height' => 2656],
  6578. ],
  6579. ];
  6580. // 参数验证
  6581. $resolution = strtolower($resolution);
  6582. if (!isset($sizeMap[$resolution])) {
  6583. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6584. }
  6585. if (!isset($sizeMap[$resolution][$ratio])) {
  6586. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6587. }
  6588. // 根据 ratio 和 resolution 确定宽高
  6589. $width = $sizeMap[$resolution][$ratio]['width'];
  6590. $height = $sizeMap[$resolution][$ratio]['height'];
  6591. $script_name = $script->script_name ?? 'script_' . $script_id;
  6592. // 检查是否已经有该剧本的资产数据
  6593. $existingMappings = DB::table('mp_script_product_mappings')
  6594. ->where('script_id', $script_id)
  6595. ->get();
  6596. if ($existingMappings->isNotEmpty()) {
  6597. // 已存在资产映射,检查是否所有资产都有图片生成任务
  6598. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  6599. // 查询这些资产的图片生成任务状态
  6600. $productsWithTasks = DB::table('mp_products')
  6601. ->whereIn('id', $productIds)
  6602. ->where('is_deleted', 0)
  6603. ->get();
  6604. $productTaskMap = [];
  6605. $typeFolderIds = [];
  6606. $hasAllTasks = true;
  6607. foreach ($productsWithTasks as $product) {
  6608. // 收集类型文件夹ID
  6609. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  6610. $parentFolder = DB::table('mp_products')
  6611. ->where('id', $product->parent_id)
  6612. ->where('type', 2)
  6613. ->first();
  6614. if ($parentFolder) {
  6615. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  6616. }
  6617. }
  6618. // 检查是否有图片生成任务
  6619. if (!empty($product->pic_task_id)) {
  6620. $productTaskMap[$product->id] = $product->pic_task_id;
  6621. } else if($product->url && $product->pic_task_status == '生成成功') {
  6622. continue;
  6623. } else {
  6624. // 有资产没有图片任务
  6625. $hasAllTasks = false;
  6626. }
  6627. }
  6628. // 如果所有资产都有任务ID,直接轮询返回结果
  6629. if ($hasAllTasks && !empty($productTaskMap)) {
  6630. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  6631. 'script_id' => $script_id,
  6632. 'script_name' => $script_name,
  6633. 'product_count' => count($productTaskMap)
  6634. ]);
  6635. // 直接返回 SSE 流轮询结果
  6636. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6637. }
  6638. // 如果部分资产没有任务ID,只为这些资产创建任务
  6639. if (!$hasAllTasks && $auto_generate_images) {
  6640. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  6641. 'script_id' => $script_id,
  6642. 'script_name' => $script_name
  6643. ]);
  6644. // 开启事务
  6645. DB::beginTransaction();
  6646. try {
  6647. foreach ($productsWithTasks as $product) {
  6648. // 跳过已有任务的资产
  6649. if (!empty($product->pic_task_id)) {
  6650. continue;
  6651. }
  6652. // 跳过没有提示词的资产
  6653. if (empty($product->pic_prompt)) {
  6654. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6655. 'product_id' => $product->id,
  6656. 'product_name' => $product->product_name
  6657. ]);
  6658. continue;
  6659. }
  6660. try {
  6661. // 创建图片生成任务
  6662. $params = [
  6663. 'prompt' => $product->pic_prompt,
  6664. 'model' => $model,
  6665. 'ref_img_urls' => [],
  6666. 'width' => $width,
  6667. 'height' => $height
  6668. ];
  6669. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6670. $task_id = $task->id;
  6671. if ($task_id) {
  6672. $productTaskMap[$product->id] = $task_id;
  6673. // 在事务中更新资产表的任务ID和状态
  6674. DB::table('mp_products')
  6675. ->where('id', $product->id)
  6676. ->update([
  6677. 'pic_task_id' => $task_id,
  6678. 'pic_task_status' => '生成中',
  6679. 'updated_at' => now()
  6680. ]);
  6681. dLog('anime')->info('为已存在资产创建图片生成任务', [
  6682. 'product_id' => $product->id,
  6683. 'task_id' => $task_id
  6684. ]);
  6685. }
  6686. } catch (\Exception $e) {
  6687. dLog('anime')->error('创建资产图片生成任务失败', [
  6688. 'product_id' => $product->id,
  6689. 'error' => $e->getMessage()
  6690. ]);
  6691. // 标记为失败(仍在事务中)
  6692. DB::table('mp_products')
  6693. ->where('id', $product->id)
  6694. ->update([
  6695. 'pic_task_status' => '生成失败',
  6696. 'updated_at' => now()
  6697. ]);
  6698. }
  6699. }
  6700. // 提交事务
  6701. DB::commit();
  6702. // 如果有新创建的任务,返回 SSE 流
  6703. if (!empty($productTaskMap)) {
  6704. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6705. }
  6706. } catch (\Exception $e) {
  6707. // 回滚事务
  6708. DB::rollback();
  6709. dLog('anime')->error('为已存在资产创建图片任务失败', [
  6710. 'script_id' => $script_id,
  6711. 'error' => $e->getMessage()
  6712. ]);
  6713. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  6714. }
  6715. }
  6716. // 如果不需要生成图片,返回已存在的信息
  6717. return [
  6718. 'success' => true,
  6719. 'message' => '剧本资产已存在',
  6720. 'script_id' => $script_id,
  6721. 'script_name' => $script_name,
  6722. 'type_folder_ids' => $typeFolderIds,
  6723. 'existing_products' => count($productIds),
  6724. 'tasks_count' => count($productTaskMap)
  6725. ];
  6726. }
  6727. // 解析 products(可能是 JSON 字符串或数组)
  6728. if (is_string($products)) {
  6729. $products = json_decode($products, true);
  6730. if (json_last_error() !== JSON_ERROR_NONE) {
  6731. Utils::throwError('20003:产品数据格式错误');
  6732. }
  6733. }
  6734. if (!is_array($products) || empty($products)) {
  6735. Utils::throwError('20003:产品数据不能为空');
  6736. }
  6737. // 以下是原有的创建逻辑...
  6738. // 开启事务
  6739. DB::beginTransaction();
  6740. try {
  6741. $now = now();
  6742. $mappingRecords = [];
  6743. $createdProductIds = []; // 记录所有创建的资产ID
  6744. // 获取剧本名称
  6745. $script_name = $script->script_name ?? 'script_' . $script_id;
  6746. // 存储每个类型的根文件夹ID
  6747. $typeFolderIds = [];
  6748. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  6749. foreach ($products as $productGroup) {
  6750. $type = getProp($productGroup, 'type');
  6751. $title = getProp($productGroup, 'title', '');
  6752. $content = getProp($productGroup, 'content', []);
  6753. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  6754. continue;
  6755. }
  6756. // 为当前类型创建根文件夹(如果还未创建)
  6757. if (!isset($typeFolderIds[$type])) {
  6758. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  6759. 'user_id' => $uid,
  6760. 'cpid' => $cpid,
  6761. 'type' => 2, // 1.资产 2文件夹
  6762. 'product' => $type, // 1.主体 2.场景 3.道具
  6763. 'parent_id' => 0, // 根文件夹,parent_id=0
  6764. 'level' => 1, // 第一层级
  6765. 'product_name' => $script_name,
  6766. 'sort_order' => time() + $type,
  6767. 'is_deleted' => 0,
  6768. 'created_at' => $now,
  6769. 'updated_at' => $now
  6770. ]);
  6771. }
  6772. $folder_id = $typeFolderIds[$type];
  6773. // 获取表头(第一行)并查找关键列的位置
  6774. $headers = $content[0];
  6775. $nameColumnIndex = -1; // 资产名称列索引
  6776. $sequenceColumnIndex = -1; // 使用范围列索引
  6777. $promptColumnIndex = -1; // 参考提示词列索引
  6778. foreach ($headers as $index => $header) {
  6779. // 查找"资产名称"列
  6780. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  6781. $nameColumnIndex = $index;
  6782. }
  6783. // 查找"使用范围"列
  6784. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  6785. $sequenceColumnIndex = $index;
  6786. }
  6787. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  6788. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  6789. $promptColumnIndex = $index;
  6790. }
  6791. }
  6792. // 验证必要的列是否都找到了
  6793. if ($nameColumnIndex === -1) {
  6794. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  6795. continue;
  6796. }
  6797. if ($sequenceColumnIndex === -1) {
  6798. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  6799. continue;
  6800. }
  6801. // 跳过表头,解析每一行数据
  6802. for ($i = 1; $i < count($content); $i++) {
  6803. $row = $content[$i];
  6804. // 确保行数据有效
  6805. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  6806. continue;
  6807. }
  6808. // 根据动态查找的列索引提取数据
  6809. $product_name = isset($row[$nameColumnIndex]) ? trim($row[$nameColumnIndex]) : '';
  6810. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  6811. $pic_prompt = '';
  6812. // 提取参考提示词(如果找到了该列)
  6813. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  6814. $pic_prompt = trim($row[$promptColumnIndex]);
  6815. }
  6816. // 解析使用范围(逗号分隔的序号)
  6817. $sequences = [];
  6818. if (!empty($sequence_str)) {
  6819. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  6820. foreach ($sequenceParts as $part) {
  6821. if (is_numeric($part)) {
  6822. $sequences[] = (int)$part;
  6823. }
  6824. }
  6825. }
  6826. if (empty($product_name)) {
  6827. continue;
  6828. }
  6829. // 处理product_name两边的符号
  6830. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6831. // 如果名称不存在则跳过
  6832. if (!$product_name) continue;
  6833. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  6834. $product_id = DB::table('mp_products')->insertGetId([
  6835. 'product_name' => $product_name,
  6836. 'type' => 1, // 1=资产 2.文件夹
  6837. 'product' => $type, // 1=角色, 2=场景, 3=道具
  6838. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  6839. 'level' => 2, // 第二层级
  6840. 'pic_prompt' => $pic_prompt,
  6841. 'user_id' => $uid,
  6842. 'cpid' => $cpid,
  6843. 'sort_order' => time(),
  6844. 'is_deleted' => 0,
  6845. 'created_at' => $now,
  6846. 'updated_at' => $now,
  6847. ]);
  6848. // 记录创建的资产ID
  6849. $createdProductIds[] = $product_id;
  6850. // 为每个序号创建映射记录
  6851. if (!empty($sequences)) {
  6852. foreach ($sequences as $sequence) {
  6853. $mappingRecords[] = [
  6854. 'script_id' => $script_id,
  6855. 'product_id' => $product_id,
  6856. 'episode_number' => $sequence,
  6857. 'created_at' => $now,
  6858. 'updated_at' => $now,
  6859. ];
  6860. }
  6861. } else {
  6862. // 如果没有指定序号,创建一个默认映射(序号为0)
  6863. $mappingRecords[] = [
  6864. 'script_id' => $script_id,
  6865. 'product_id' => $product_id,
  6866. 'episode_number' => 0,
  6867. 'created_at' => $now,
  6868. 'updated_at' => $now,
  6869. ];
  6870. }
  6871. }
  6872. }
  6873. if (empty($mappingRecords)) {
  6874. Utils::throwError('20003:没有有效的产品数据');
  6875. }
  6876. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  6877. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  6878. // 如果需要自动生成图片,在事务中创建图片生成任务
  6879. $productTaskMap = [];
  6880. if ($auto_generate_images && !empty($createdProductIds)) {
  6881. // 查询所有创建的资产
  6882. $productsToGenerate = DB::table('mp_products')
  6883. ->whereIn('id', $createdProductIds)
  6884. ->where('is_deleted', 0)
  6885. ->get();
  6886. foreach ($productsToGenerate as $product) {
  6887. if (empty($product->pic_prompt)) {
  6888. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6889. 'product_id' => $product->id,
  6890. 'product_name' => $product->product_name
  6891. ]);
  6892. continue;
  6893. }
  6894. try {
  6895. // 创建图片生成任务
  6896. $params = [
  6897. 'prompt' => $product->pic_prompt,
  6898. 'model' => $model,
  6899. 'ref_img_urls' => [],
  6900. 'width' => $width,
  6901. 'height' => $height
  6902. ];
  6903. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6904. $task_id = $task->id;
  6905. if ($task_id) {
  6906. $productTaskMap[$product->id] = $task_id;
  6907. // 在事务中更新资产表的任务ID和状态
  6908. DB::table('mp_products')
  6909. ->where('id', $product->id)
  6910. ->update([
  6911. 'pic_task_id' => $task_id,
  6912. 'pic_task_status' => '生成中',
  6913. 'updated_at' => now()
  6914. ]);
  6915. dLog('anime')->info('创建资产图片生成任务', [
  6916. 'product_id' => $product->id,
  6917. 'task_id' => $task_id
  6918. ]);
  6919. }
  6920. } catch (\Exception $e) {
  6921. dLog('anime')->error('创建资产图片生成任务失败', [
  6922. 'product_id' => $product->id,
  6923. 'error' => $e->getMessage()
  6924. ]);
  6925. // 标记为失败(仍在事务中)
  6926. DB::table('mp_products')
  6927. ->where('id', $product->id)
  6928. ->update([
  6929. 'pic_task_status' => '生成失败',
  6930. 'updated_at' => now()
  6931. ]);
  6932. }
  6933. }
  6934. }
  6935. // 提交事务
  6936. DB::commit();
  6937. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  6938. if ($auto_generate_images && !empty($productTaskMap)) {
  6939. // 返回 SSE 流(事务外轮询)
  6940. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6941. }
  6942. // 如果不需要生成图片,返回普通结果
  6943. return [
  6944. 'success' => true,
  6945. 'type_folder_ids' => $typeFolderIds,
  6946. 'inserted_count' => $insertedCount,
  6947. 'total_records' => count($mappingRecords),
  6948. 'created_products' => count($createdProductIds),
  6949. 'image_tasks_created' => count($productTaskMap)
  6950. ];
  6951. } catch (\Exception $e) {
  6952. // 回滚事务
  6953. DB::rollback();
  6954. // 记录错误日志
  6955. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  6956. 'script_id' => $script_id,
  6957. 'error' => $e->getMessage(),
  6958. 'trace' => $e->getTraceAsString()
  6959. ]);
  6960. // 统一使用 Utils::throwError 抛出错误
  6961. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  6962. }
  6963. }
  6964. /**
  6965. * 批量为剧本资产生成图片
  6966. *
  6967. * @param array $data 请求参数
  6968. * @return \Generator 返回 SSE 流
  6969. */
  6970. public function batchGenerateProductImages($data) {
  6971. $script_id = getProp($data, 'script_id');
  6972. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  6973. if (!$script_id) {
  6974. Utils::throwError('20003:请提供剧本ID');
  6975. }
  6976. // 验证剧本是否存在
  6977. $script = DB::table('mp_scripts')
  6978. ->where('id', $script_id)
  6979. ->where('is_deleted', 0)
  6980. ->first();
  6981. if (!$script) {
  6982. Utils::throwError('20003:剧本不存在');
  6983. }
  6984. $script_name = $script->script_name ?? 'script_' . $script_id;
  6985. // 获取需要生成图片的所有资产
  6986. $products = DB::table('mp_products')
  6987. ->whereIn('parent_id', array_values($type_folder_ids))
  6988. ->where('is_deleted', 0)
  6989. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  6990. ->get();
  6991. if ($products->isEmpty()) {
  6992. Utils::throwError('20003:没有找到需要生成图片的资产');
  6993. }
  6994. // 默认参数
  6995. $model = 'doubao-seedream-5-0-lite-260128';
  6996. $width = 1600;
  6997. $height = 2848;
  6998. // 开始为每个资产创建图片生成任务
  6999. $taskIds = [];
  7000. $productTaskMap = []; // 资产ID到任务ID的映射
  7001. foreach ($products as $product) {
  7002. if (empty($product->pic_prompt)) {
  7003. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  7004. continue;
  7005. }
  7006. try {
  7007. // 创建图片生成任务
  7008. $params = [
  7009. 'prompt' => $product->pic_prompt,
  7010. 'model' => $model,
  7011. 'ref_img_urls' => [],
  7012. 'width' => $width,
  7013. 'height' => $height
  7014. ];
  7015. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7016. $task_id = $task->id;
  7017. if ($task_id) {
  7018. $taskIds[] = $task_id;
  7019. $productTaskMap[$product->id] = $task_id;
  7020. // 更新资产表的任务ID和状态
  7021. DB::table('mp_products')
  7022. ->where('id', $product->id)
  7023. ->update([
  7024. 'pic_task_id' => $task_id,
  7025. 'pic_task_status' => '生成中',
  7026. 'updated_at' => now()
  7027. ]);
  7028. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  7029. }
  7030. } catch (\Exception $e) {
  7031. dLog('anime')->error('创建资产图片生成任务失败', [
  7032. 'product_id' => $product->id,
  7033. 'error' => $e->getMessage()
  7034. ]);
  7035. // 标记为失败
  7036. DB::table('mp_products')
  7037. ->where('id', $product->id)
  7038. ->update([
  7039. 'pic_task_status' => '生成失败',
  7040. 'updated_at' => now()
  7041. ]);
  7042. }
  7043. }
  7044. if (empty($taskIds)) {
  7045. Utils::throwError('20003:没有成功创建任何图片生成任务');
  7046. }
  7047. // 返回 SSE 流
  7048. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  7049. }
  7050. /**
  7051. * 轮询资产图片生成任务状态(SSE流式返回)
  7052. * 只通过查询数据库获取任务状态,不主动调用API
  7053. *
  7054. * @param int $script_id 剧本ID
  7055. * @param string $script_name 剧本名称
  7056. * @param array $productTaskMap 资产ID到任务ID的映射
  7057. * @param array $type_folder_ids 类型文件夹ID映射
  7058. * @return \Generator
  7059. */
  7060. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  7061. $startTime = time();
  7062. $timeout = 1800; // 30分钟超时
  7063. $pollInterval = 10; // 10秒轮询一次
  7064. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  7065. // 定义类型名称映射
  7066. $typeNames = [
  7067. 1 => 'roles', // 角色
  7068. 2 => 'scenes', // 场景
  7069. 3 => 'props' // 道具
  7070. ];
  7071. while (time() - $startTime < $timeout) {
  7072. sleep($pollInterval);
  7073. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  7074. $mappings = DB::table('mp_script_product_mappings')
  7075. ->where('script_id', $script_id)
  7076. ->pluck('product_id')
  7077. ->unique()
  7078. ->toArray();
  7079. if (empty($mappings)) {
  7080. dLog('anime')->warning('该剧本没有关联的资产', [
  7081. 'script_id' => $script_id,
  7082. 'script_name' => $script_name
  7083. ]);
  7084. break;
  7085. }
  7086. // 查询所有资产的当前状态
  7087. $products = DB::table('mp_products')
  7088. ->whereIn('id', $mappings)
  7089. ->where('is_deleted', 0)
  7090. ->get();
  7091. // 统计各类型的状态(使用类型名称作为键名)
  7092. $stats = [
  7093. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  7094. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  7095. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  7096. ];
  7097. $allCompleted = true;
  7098. $hasStatusChange = false;
  7099. foreach ($products as $product) {
  7100. $type = $product->product;
  7101. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  7102. // 如果类型名称不在 stats 中,初始化
  7103. if (!isset($stats[$typeName])) {
  7104. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  7105. }
  7106. $stats[$typeName]['total']++;
  7107. $task_id = $product->pic_task_id;
  7108. $currentStatus = $product->pic_task_status;
  7109. // 检查状态是否有变化
  7110. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  7111. $hasStatusChange = true;
  7112. $lastStatus[$product->id] = $currentStatus;
  7113. }
  7114. // 如果是生成中,查询任务表状态
  7115. if ($currentStatus === '生成中' && $task_id) {
  7116. // 只查询数据库,不调用API
  7117. $task = DB::table('mp_generate_pic_tasks')
  7118. ->where('id', $task_id)
  7119. ->first();
  7120. if ($task) {
  7121. // 检查任务状态
  7122. if ($task->status === 'success' && $task->result_url) {
  7123. // 解析图片URL
  7124. $result_urls = $task->result_url;
  7125. if (is_string($result_urls)) {
  7126. $result_urls = json_decode($result_urls, true);
  7127. }
  7128. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7129. // 更新资产表状态
  7130. DB::table('mp_products')
  7131. ->where('id', $product->id)
  7132. ->update([
  7133. 'pic_task_status' => '生成成功',
  7134. 'url' => $img_url,
  7135. 'updated_at' => now()
  7136. ]);
  7137. $stats[$typeName]['success']++;
  7138. $stats[$typeName]['completed']++;
  7139. $hasStatusChange = true;
  7140. dLog('anime')->info('资产图片生成成功', [
  7141. 'product_id' => $product->id,
  7142. 'task_id' => $task_id,
  7143. 'img_url' => $img_url
  7144. ]);
  7145. } elseif ($task->status === 'failed') {
  7146. // 更新资产表状态
  7147. DB::table('mp_products')
  7148. ->where('id', $product->id)
  7149. ->update([
  7150. 'pic_task_status' => '生成失败',
  7151. 'updated_at' => now()
  7152. ]);
  7153. $stats[$typeName]['completed']++;
  7154. $hasStatusChange = true;
  7155. dLog('anime')->warning('资产图片生成失败', [
  7156. 'product_id' => $product->id,
  7157. 'task_id' => $task_id,
  7158. 'error' => $task->error_message ?? '未知错误'
  7159. ]);
  7160. } else {
  7161. // 任务还在处理中
  7162. $allCompleted = false;
  7163. }
  7164. } else {
  7165. // 任务不存在,标记为失败
  7166. DB::table('mp_products')
  7167. ->where('id', $product->id)
  7168. ->update([
  7169. 'pic_task_status' => '生成失败',
  7170. 'updated_at' => now()
  7171. ]);
  7172. $stats[$type]['completed']++;
  7173. $hasStatusChange = true;
  7174. dLog('anime')->error('图片生成任务不存在', [
  7175. 'product_id' => $product->id,
  7176. 'task_id' => $task_id
  7177. ]);
  7178. }
  7179. } elseif ($currentStatus === '生成成功') {
  7180. $stats[$typeName]['success']++;
  7181. $stats[$typeName]['completed']++;
  7182. } elseif ($currentStatus === '生成失败') {
  7183. $stats[$typeName]['completed']++;
  7184. } else {
  7185. // 其他状态也认为未完成
  7186. $allCompleted = false;
  7187. }
  7188. }
  7189. // 移除没有数据的类型(total=0)
  7190. foreach ($stats as $typeName => $stat) {
  7191. if ($stat['total'] === 0) {
  7192. unset($stats[$typeName]);
  7193. }
  7194. }
  7195. // 如果有状态变化,发送 SSE 更新
  7196. if ($hasStatusChange) {
  7197. $eventType = $allCompleted ? 'complete' : 'update';
  7198. $response = [
  7199. 'type' => $eventType,
  7200. 'script_id' => $script_id,
  7201. 'script_name' => $script_name,
  7202. 'stats' => $stats,
  7203. 'timestamp' => date('Y-m-d H:i:s')
  7204. ];
  7205. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7206. dLog('anime')->info('SSE更新', [
  7207. 'event_type' => $eventType,
  7208. 'script_id' => $script_id,
  7209. 'script_name' => $script_name,
  7210. 'stats' => $stats
  7211. ]);
  7212. if ($allCompleted) {
  7213. dLog('anime')->info('所有资产图片生成任务已完成', [
  7214. 'script_id' => $script_id,
  7215. 'script_name' => $script_name,
  7216. 'stats' => $stats
  7217. ]);
  7218. break;
  7219. }
  7220. }
  7221. }
  7222. // 超时处理
  7223. if (time() - $startTime >= $timeout && !$allCompleted) {
  7224. $response = [
  7225. 'type' => 'timeout',
  7226. 'message' => '部分任务超时,请稍后查看结果',
  7227. 'script_id' => $script_id,
  7228. 'script_name' => $script_name,
  7229. 'timestamp' => date('Y-m-d H:i:s')
  7230. ];
  7231. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7232. dLog('anime')->warning('资产图片生成任务超时', [
  7233. 'script_id' => $script_id,
  7234. 'script_name' => $script_name,
  7235. 'timeout' => $timeout
  7236. ]);
  7237. }
  7238. }
  7239. /**
  7240. * 获取剧本关联的资产列表
  7241. * @param array $data 请求参数
  7242. * @return array
  7243. */
  7244. public function getScriptProducts($data) {
  7245. $uid = Site::getUid();
  7246. $cpid = Site::getCpid();
  7247. $script_id = getProp($data, 'script_id');
  7248. $episode_number = getProp($data, 'episode_number');
  7249. if (!$script_id) {
  7250. Utils::throwError('20003:请提供剧本ID');
  7251. }
  7252. // 验证剧本是否存在
  7253. $script = DB::table('mp_scripts')
  7254. ->where('id', $script_id)
  7255. ->where('is_deleted', 0)
  7256. ->first();
  7257. if (!$script) {
  7258. Utils::throwError('20003:剧本不存在');
  7259. }
  7260. // 联表查询资产信息
  7261. $query = DB::table('mp_script_product_mappings as mapping')
  7262. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7263. ->where('mapping.script_id', $script_id)
  7264. ->where('product.cpid', $cpid)
  7265. ->where('product.is_deleted', 0);
  7266. // 如果提供了 episode_number,则过滤指定集数
  7267. if ($episode_number !== null && $episode_number !== '') {
  7268. $query->where('mapping.episode_number', $episode_number);
  7269. }
  7270. $mappings = $query->select(
  7271. 'mapping.script_id',
  7272. 'mapping.product_id',
  7273. 'mapping.episode_number',
  7274. 'product.product_name',
  7275. 'product.type',
  7276. 'product.product',
  7277. 'product.pic_prompt',
  7278. 'product.url',
  7279. 'product.pic_task_id',
  7280. 'product.pic_task_status',
  7281. 'product.three_view_image_url',
  7282. 'mapping.created_at'
  7283. )
  7284. ->orderBy('mapping.product_id', 'asc')
  7285. ->orderBy('mapping.episode_number', 'asc')
  7286. ->get();
  7287. // 按 product_id 分组,合并 episode_number
  7288. $productMap = [];
  7289. foreach ($mappings as $item) {
  7290. $product_id = $item->product_id;
  7291. if (!isset($productMap[$product_id])) {
  7292. $productMap[$product_id] = [
  7293. 'product_id' => $product_id,
  7294. 'product_name' => $item->product_name,
  7295. 'type' => (int)$item->type,
  7296. 'product' => (int)$item->product,
  7297. 'pic_prompt' => $item->pic_prompt,
  7298. 'url' => $item->url,
  7299. 'pic_task_id' => $item->pic_task_id,
  7300. 'pic_task_status' => $item->pic_task_status,
  7301. 'episode_numbers' => [],
  7302. 'created_at' => $item->created_at,
  7303. ];
  7304. }
  7305. // 添加 episode_number(去重)
  7306. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7307. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7308. }
  7309. }
  7310. // 按类型分组
  7311. $roles = []; // type=1 角色/主体
  7312. $scenes = []; // type=2 场景
  7313. $props = []; // type=3 道具
  7314. foreach ($productMap as $product) {
  7315. // 将 episode_numbers 数组转换为逗号分隔的字符串
  7316. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  7317. // 构造返回数据
  7318. $productData = [
  7319. 'product_id' => $product['product_id'],
  7320. 'product_name' => $product['product_name'],
  7321. 'product' => $product['product'],
  7322. 'pic_prompt' => $product['pic_prompt'],
  7323. 'url' => $product['url'],
  7324. 'pic_task_id' => $product['pic_task_id'],
  7325. 'pic_task_status' => $product['pic_task_status'],
  7326. 'episode_numbers' => $episodeNumbersStr,
  7327. 'created_at' => $product['created_at'],
  7328. ];
  7329. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  7330. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  7331. switch ($product['product']) {
  7332. case 1:
  7333. $roles[] = $productData;
  7334. break;
  7335. case 2:
  7336. $scenes[] = $productData;
  7337. break;
  7338. case 3:
  7339. $props[] = $productData;
  7340. break;
  7341. }
  7342. }
  7343. return [
  7344. 'script_id' => $script_id,
  7345. 'script_name' => $script->script_name ?? '',
  7346. 'roles' => $roles, // 主体
  7347. 'scenes' => $scenes, // 场景
  7348. 'props' => $props, // 道具
  7349. ];
  7350. }
  7351. /**
  7352. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  7353. * @param string $actContent 原始内容
  7354. * @param array $products 产品数组(包含product_name和url)
  7355. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  7356. */
  7357. public function processActContentWithProducts($actContent, $products) {
  7358. if (empty($actContent) || empty($products)) {
  7359. return [
  7360. 'content' => $actContent,
  7361. 'reference_images' => []
  7362. ];
  7363. }
  7364. // 构建产品名称到产品信息的映射
  7365. $product_dict = [];
  7366. foreach ($products as $product) {
  7367. $product_name = getProp($product, 'product_name');
  7368. if ($product_name) {
  7369. $product_dict[$product_name] = [
  7370. 'url' => getProp($product, 'url'),
  7371. 'voice_prompt' => getProp($product, 'voice_prompt')
  7372. ];
  7373. }
  7374. }
  7375. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  7376. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  7377. $reference_images = [];
  7378. $product_index_map = []; // 产品名称 => 图片序号的映射
  7379. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  7380. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  7381. $current_index = 1;
  7382. if (!empty($matches[1])) {
  7383. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  7384. $seen_products = []; // 用于去重
  7385. foreach ($matches[1] as $product_name) {
  7386. // 跳过已处理的产品
  7387. if (isset($seen_products[$product_name])) {
  7388. continue;
  7389. }
  7390. $seen_products[$product_name] = true;
  7391. // 检查产品是否在字典中
  7392. if (isset($product_dict[$product_name])) {
  7393. $url = $product_dict[$product_name]['url'];
  7394. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  7395. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  7396. if (!empty($voice_prompt) && $product_name !== '旁白') {
  7397. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  7398. }
  7399. // 只有URL非空才分配序号和添加到参考图片
  7400. if (!empty($url)) {
  7401. // 检查URL是否已经在reference_images中(去重)
  7402. if (!in_array($url, $reference_images)) {
  7403. $reference_images[] = $url;
  7404. $product_index_map[$product_name] = $current_index;
  7405. $current_index++;
  7406. } else {
  7407. // URL重复,找到已有的序号
  7408. $existing_index = array_search($url, $reference_images) + 1;
  7409. $product_index_map[$product_name] = $existing_index;
  7410. }
  7411. } else {
  7412. // URL为空,不分配序号(后续直接去掉{})
  7413. $product_index_map[$product_name] = 0;
  7414. }
  7415. } else {
  7416. // 产品不在字典中,不分配序号
  7417. $product_index_map[$product_name] = 0;
  7418. }
  7419. }
  7420. }
  7421. // 第二步:替换内容中的 {产品名称}
  7422. $processedContent = $actContent;
  7423. foreach ($product_index_map as $product_name => $index) {
  7424. $escaped_name = preg_quote($product_name, '/');
  7425. if ($index > 0) {
  7426. // 有图片,替换为:产品名称(图X)
  7427. $replacement = $product_name . '<图片' . $index . '>';
  7428. } else {
  7429. // 无图片,只保留产品名称
  7430. $replacement = $product_name;
  7431. }
  7432. // 替换所有 {产品名称} 为处理后的格式
  7433. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  7434. }
  7435. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  7436. foreach ($products as $product) {
  7437. $product_name = getProp($product, 'product_name');
  7438. $voice_prompt = getProp($product, 'voice_prompt');
  7439. if ($product_name === '旁白' && !empty($voice_prompt)) {
  7440. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  7441. break; // 找到旁白后退出循环
  7442. }
  7443. }
  7444. // 第四步:将voice_prompt信息添加到内容最前面
  7445. $voice_prompt_prefix = '';
  7446. if (!empty($voice_prompts)) {
  7447. $voice_prompt_prefix .= implode('', $voice_prompts);
  7448. }
  7449. // 旁白的voice_prompt放在最后
  7450. if (!empty($narrator_voice_prompt)) {
  7451. $voice_prompt_prefix .= $narrator_voice_prompt;
  7452. }
  7453. // 如果有voice_prompt信息,添加到内容开头
  7454. if (!empty($voice_prompt_prefix)) {
  7455. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  7456. }
  7457. return [
  7458. 'content' => $processedContent,
  7459. 'reference_images' => $reference_images
  7460. ];
  7461. }
  7462. public function saveActVideoGenerateParams($data) {
  7463. $episode_id = getProp($data, 'episode_id');
  7464. $model = getProp($data, 'video_model');
  7465. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  7466. Utils::throwError('20003:该模型不可用');
  7467. }
  7468. if (!$model) {
  7469. // 使用默认模型
  7470. $model = 'zhizhen-20';
  7471. }
  7472. // 验证模型是否在可用模型表中
  7473. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7474. Utils::throwError('20003:该模型已不可用,请更换!');
  7475. }
  7476. $video_resolution = getProp($data, 'video_resolution', '720p');
  7477. $ratio = getProp($data, 'ratio');
  7478. if (!$ratio) $ratio = '9:16';
  7479. return DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7480. 'video_model' => $model,
  7481. 'video_resolution' => $video_resolution,
  7482. 'ratio' => $ratio,
  7483. 'updated_at' => date('Y-m-d H:i:s')
  7484. ]);
  7485. }
  7486. public function confirmActs($data) {
  7487. $episode_id = getProp($data, 'episode_id');
  7488. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  7489. if (!$episode) {
  7490. Utils::throwError('20003:分集不存在');
  7491. }
  7492. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  7493. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  7494. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  7495. // 获取所有片段数据
  7496. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7497. // 收集所有资产名称(角色、场景、道具)
  7498. $product_names = [];
  7499. // 收集角色名称
  7500. foreach ($roles as $role) {
  7501. $role_name = getProp($role, 'role');
  7502. if ($role_name && $role_name != '旁白') {
  7503. $product_names[] = $role_name;
  7504. }
  7505. }
  7506. // 收集场景名称
  7507. foreach ($scenes as $scene) {
  7508. $scene_name = getProp($scene, 'scene');
  7509. if ($scene_name) {
  7510. $product_names[] = $scene_name;
  7511. }
  7512. }
  7513. // 收集道具名称
  7514. foreach ($props as $prop) {
  7515. $prop_name = getProp($prop, 'prop');
  7516. if ($prop_name) {
  7517. $product_names[] = $prop_name;
  7518. }
  7519. }
  7520. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  7521. $product_names = array_unique($product_names);
  7522. usort($product_names, function($a, $b) {
  7523. return mb_strlen($b) - mb_strlen($a);
  7524. });
  7525. try {
  7526. DB::beginTransaction();
  7527. // 处理每个片段
  7528. foreach ($acts as $act) {
  7529. $act_content = getProp($act, 'act_content');
  7530. if (!$act_content) continue;
  7531. $processed_content = $act_content;
  7532. // 统一替换所有资产名称为 {资产名} 格式
  7533. // 使用占位符避免嵌套替换问题
  7534. $placeholder_map = [];
  7535. $placeholder_index = 0;
  7536. foreach ($product_names as $product_name) {
  7537. // 转义特殊字符
  7538. $escaped_product = preg_quote($product_name, '/');
  7539. // 检查是否匹配且未被 {} 包裹
  7540. $processed_content = preg_replace_callback(
  7541. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  7542. function($matches) use (&$placeholder_map, &$placeholder_index) {
  7543. // 使用唯一占位符
  7544. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  7545. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  7546. $placeholder_index++;
  7547. return $placeholder;
  7548. },
  7549. $processed_content
  7550. );
  7551. }
  7552. // 将所有占位符替换回实际内容
  7553. foreach ($placeholder_map as $placeholder => $replacement) {
  7554. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  7555. }
  7556. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  7557. $shot_counter = 0;
  7558. $processed_content = preg_replace_callback(
  7559. '/【(?:镜头|分镜)(\d+)】/u',
  7560. function($matches) use (&$shot_counter) {
  7561. $shot_counter++;
  7562. return '【镜头' . $shot_counter . '】';
  7563. },
  7564. $processed_content
  7565. );
  7566. // 更新数据库
  7567. $boolen = DB::table('mp_episode_segments')
  7568. ->where('id', $act->id)
  7569. ->update([
  7570. 'act_show_content' => $processed_content,
  7571. 'updated_at' => date('Y-m-d H:i:s')
  7572. ]);
  7573. if (!$boolen) {
  7574. Utils::throwError('20003:片段处理失败');
  7575. }
  7576. }
  7577. }catch (\Exception $e) {
  7578. DB::rollBack();
  7579. Utils::throwError('20003:'.$e->getMessage());
  7580. }
  7581. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7582. 'is_generated' => 1,
  7583. 'updated_at' => date('Y-m-d H:i:s')
  7584. ]);
  7585. if (!$boolen1) {
  7586. DB::rollBack();
  7587. Utils::throwError('20003:分集处理失败!');
  7588. }
  7589. DB::commit();
  7590. // 重新查询更新后的片段数据
  7591. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7592. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  7593. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  7594. $products = [];
  7595. // 先处理角色数组
  7596. foreach ($roles as $role) {
  7597. $product = $role;
  7598. // 将role字段重命名为product_name
  7599. if (isset($product['role'])) {
  7600. $product['product_name'] = $product['role'];
  7601. unset($product['role']);
  7602. $product['product'] = 1; // 标记类型为角色
  7603. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7604. }
  7605. }
  7606. // 处理场景数组
  7607. foreach ($scenes as $scene) {
  7608. $product = $scene;
  7609. // 将scene字段重命名为product_name
  7610. if (isset($product['scene'])) {
  7611. $product['product_name'] = $product['scene'];
  7612. unset($product['scene']);
  7613. $product['product'] = 2; // 标记类型为场景
  7614. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7615. }
  7616. }
  7617. // 处理道具数组(逻辑与场景一致)
  7618. foreach ($props as $prop) {
  7619. $product = $prop;
  7620. // 将prop字段重命名为product_name
  7621. if (isset($product['prop'])) {
  7622. $product['product_name'] = $product['prop'];
  7623. unset($product['prop']);
  7624. $product['product'] = 3; // 标记类型为道具
  7625. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7626. }
  7627. }
  7628. // extra_products优先级更高,直接覆盖同名的roles和scenes
  7629. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  7630. foreach ($extra_products as $extra_product) {
  7631. $product_name = getProp($extra_product, 'product_name');
  7632. if ($product_name) {
  7633. $products[$product_name] = $extra_product; // 覆盖同名数据
  7634. }
  7635. }
  7636. // 重新索引数组(去除key)
  7637. $products = array_values($products);
  7638. // 构建返回的acts数组
  7639. $return_acts = [];
  7640. foreach ($acts as $act) {
  7641. $return_acts[] = [
  7642. 'act_id' => getProp($act, 'id'),
  7643. 'act_number' => getProp($act, 'act_number'),
  7644. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  7645. 'act_show_content' => getProp($act, 'act_show_content'),
  7646. 'video_url' => getProp($act, 'video_url'),
  7647. 'video_duration' => getProp($act, 'video_duration'),
  7648. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  7649. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  7650. ];
  7651. }
  7652. return [
  7653. 'anime_id' => getProp($episode, 'anime_id'),
  7654. 'episode_id' => $episode_id,
  7655. 'title' => getProp($episode, 'title'),
  7656. 'episode_number' => getProp($episode, 'episode_number'),
  7657. 'is_generated' => getProp($episode, 'is_generated'),
  7658. 'products' => $products,
  7659. 'acts' => $return_acts
  7660. ];
  7661. }
  7662. }