AnimeService.php 394 KB

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