AnimeService.php 396 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211
  1. <?php
  2. namespace App\Services\Anime;
  3. use App\Consts\BaseConst;
  4. use App\Consts\ErrorConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use App\Models\MpGeneratePicTask;
  8. use App\Services\AIGeneration\AIImageGenerationService;
  9. use App\Services\AIGeneration\AIVideoGenerationService;
  10. use App\Services\DeepSeek\DeepSeekService;
  11. use Dflydev\DotAccessData\Util;
  12. use GuzzleHttp\Client;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Redis;
  16. use OSS\Core\OssException;
  17. use OSS\OssClient;
  18. class AnimeService
  19. {
  20. protected $aiImageGenerationService;
  21. protected $aiVideoGenerationService;
  22. protected $DeepSeekService;
  23. private $url;
  24. private $api_key;
  25. private $headers;
  26. public function __construct(
  27. AIImageGenerationService $aiImageGenerationService,
  28. AIVideoGenerationService $aiVideoGenerationService,
  29. DeepSeekService $DeepSeekService
  30. ) {
  31. $this->aiImageGenerationService = $aiImageGenerationService;
  32. $this->aiVideoGenerationService = $aiVideoGenerationService;
  33. $this->DeepSeekService = $DeepSeekService;
  34. $this->url = 'https://api.deepseek.com/chat/completions';
  35. $this->api_key = env('DEEPSEEK_API_KEY');
  36. $this->headers = [
  37. 'Authorization' => 'Bearer '.$this->api_key,
  38. 'Content-Type' => 'application/json; charset=UTF-8'
  39. ];
  40. }
  41. /**
  42. * 构建统一的分镜数据结构(episodeInfo格式)
  43. * @param array $segments 分镜数据数组
  44. * @return array 返回包含acts和total_duration的数组
  45. */
  46. public function buildEpisodeSegmentsStructure($segments) {
  47. $acts = [];
  48. $totalDuration = 0; // 初始化总时长
  49. foreach($segments as $segment) {
  50. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  51. $videoDuration = getProp($segment, 'video_duration');
  52. $audioDuration = getProp($segment, 'audio_duration');
  53. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  54. $totalDuration += floatval($videoDuration);
  55. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  56. $totalDuration += floatval($audioDuration);
  57. } else {
  58. $totalDuration += 5; // 默认5秒
  59. }
  60. $segment_content = getProp($segment, 'segment_content');
  61. // 判断是否有尾帧描述,如果有则去掉这部分内容
  62. if (strpos($segment_content, '尾帧') !== false) {
  63. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  64. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  65. }
  66. // 构建分镜信息
  67. $segmentInfo = [
  68. 'segment_id' => getProp($segment, 'segment_id'),
  69. 'segment_number' => getProp($segment, 'segment_number'),
  70. 'segment_content' => $segment_content,
  71. 'description' => getProp($segment, 'description'),
  72. 'composition' => getProp($segment, 'composition'),
  73. 'camera_movement' => getProp($segment, 'camera_movement'),
  74. 'voice_actor' => getProp($segment, 'voice_actor'),
  75. 'dialogue' => getProp($segment, 'dialogue'),
  76. 'frame_type' => getProp($segment, 'frame_type'),
  77. 'scene' => getProp($segment, 'scene'),
  78. 'characters' => getProp($segment, 'characters'),
  79. 'tail_frame' => getProp($segment, 'tail_frame'),
  80. 'emotion' => getProp($segment, 'emotion'),
  81. 'emotion_type' => getProp($segment, 'emotion_type'),
  82. 'gender' => getProp($segment, 'gender'),
  83. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  84. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  85. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  86. 'pitch' => getProp($segment, 'pitch'),
  87. 'voice_name' => getProp($segment, 'voice_name'),
  88. 'voice_type' => getProp($segment, 'voice_type'),
  89. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  90. 'img_url' => getProp($segment, 'img_url'),
  91. 'audio_url' => getProp($segment, 'audio_url'),
  92. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  93. 'video_url' => getProp($segment, 'video_url'),
  94. 'video_duration' => getProp($segment, 'video_duration', 0),
  95. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  96. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  97. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  98. 'current_type' => getProp($segment, 'current_type'),
  99. ];
  100. $actNumber = getProp($segment, 'act_number');
  101. if (isset($acts[$actNumber])) {
  102. $acts[$actNumber]['segments'][] = $segmentInfo;
  103. } else {
  104. $acts[$actNumber] = [
  105. 'act_number' => $actNumber,
  106. 'act_title' => getProp($segment, 'act_title'),
  107. 'act_duration' => getProp($segment, 'act_duration'),
  108. 'segments' => [$segmentInfo]
  109. ];
  110. }
  111. }
  112. return [
  113. 'acts' => array_values($acts),
  114. 'total_duration' => intval(round($totalDuration))
  115. ];
  116. }
  117. /**
  118. * 构建统一的分段数据结构(episodeInfoForAce格式)
  119. * @param array $segments 分段数据数组
  120. * @return array 返回包含acts和total_duration的数组
  121. */
  122. public function buildEpisodeActsStructureForAce($segments) {
  123. $acts = [];
  124. $totalDuration = 0; // 初始化总时长
  125. foreach($segments as $segment) {
  126. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  127. $videoDuration = getProp($segment, 'video_duration');
  128. $actDuration = getProp($segment, 'act_duration');
  129. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  130. $totalDuration += floatval($videoDuration);
  131. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  132. $totalDuration += floatval($actDuration);
  133. } else {
  134. $totalDuration += 5; // 默认5秒
  135. }
  136. // 构建分镜信息
  137. $segmentInfo = [
  138. 'act_id' => getProp($segment, 'id'),
  139. 'act_number' => getProp($segment, 'act_number'),
  140. 'act_title' => getProp($segment, 'act_title'),
  141. 'act_duration' => getProp($segment, 'act_duration'),
  142. 'act_content' => getProp($segment, 'act_content'),
  143. 'video_url' => getProp($segment, 'video_url'),
  144. 'video_duration' => getProp($segment, 'video_duration', 0),
  145. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  146. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  147. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  148. 'current_type' => getProp($segment, 'current_type'),
  149. ];
  150. $acts[] = $segmentInfo;
  151. }
  152. return [
  153. 'acts' => array_values($acts),
  154. 'total_duration' => intval(round($totalDuration))
  155. ];
  156. }
  157. /**
  158. * 验证画面比例是否有效
  159. * @param string $ratio 画面比例
  160. * @return bool
  161. */
  162. public function validateRatio($ratio) {
  163. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  164. }
  165. /**
  166. * 获取画面比例对应的宽高
  167. * @param string $ratio 画面比例
  168. * @return array ['width' => int, 'height' => int]
  169. * @throws \Exception
  170. */
  171. private function getRatioDimensions($ratio) {
  172. if ($ratio && !$this->validateRatio($ratio)) {
  173. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  174. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  175. }
  176. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  177. }
  178. public function createAnime($data) {
  179. $uid = Site::getUid();
  180. $cpid = Site::getCpid();
  181. $input_art_style = getProp($data, 'art_style');
  182. $file = getProp($data, 'file');
  183. $content = getProp($data, 'content', '');
  184. $bid = getProp($data, 'bid', 0);
  185. $script_id = getProp($data, 'script_id', 0);
  186. $ace_mode = getProp($data, 'ace_mode', 0);
  187. $extra_products = getProp($data, 'products', []);
  188. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  189. if (!is_array($extra_products)) {
  190. Utils::throwError('20003:传入的资产格式不正确');
  191. }
  192. // 替换美术风格
  193. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  194. // 提取文件内容
  195. if ($file) {
  196. $content = $this->DeepSeekService->extractFileContent($file);
  197. if (!$content) {
  198. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  199. }
  200. } elseif ($script_id) {
  201. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  202. if (!$content) {
  203. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  204. }
  205. } elseif ($bid) {
  206. $content = $this->DeepSeekService->getContentByBid($bid);
  207. if (!$content) {
  208. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  209. }
  210. } elseif ($content) {
  211. $content = filterContent($content);
  212. }else {
  213. $content = '';
  214. }
  215. $anime_data = [
  216. 'user_id' => $uid,
  217. 'cpid' => $cpid,
  218. 'anime_name' => '新剧本策划',
  219. 'is_multi' => getProp($data, 'is_multi', 1),
  220. 'content' => $content,
  221. 'art_style_type' => $input_art_style,
  222. 'ace_mode' => $ace_mode,
  223. 'script_id' => $script_id,
  224. 'extra_products' => json_encode($extra_products, 256),
  225. 'created_at' => date('Y-m-d H:i:s'),
  226. 'updated_at' => date('Y-m-d H:i:s'),
  227. ];
  228. // 处理文本模型
  229. $model = getProp($data, 'model');
  230. if (!$model) {
  231. // 用户没有输入,使用默认值
  232. $model = 'deepseek-v4-pro';
  233. }
  234. // 验证模型是否在可用模型表中
  235. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  236. $model = 'deepseek-v4-pro';
  237. }
  238. $anime_data['model'] = $model;
  239. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  240. return DB::table('mp_animes')->insertGetId($anime_data);
  241. }
  242. public function chatList($data) {
  243. $uid = Site::getUid();
  244. $anime_name = getProp($data, 'anime_name');
  245. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  246. if ($anime_name) {
  247. $query->where('anime_name', 'like', "%$anime_name%");
  248. }
  249. return $query->orderBy('id', 'desc')->paginate();
  250. }
  251. public function chatHistory($data) {
  252. $anime_id = getProp($data, 'anime_id');
  253. $sequence = getProp($data, 'sequence', 0);
  254. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  255. $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)
  256. ->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');
  257. return $query->orderBy('ar.id')->get()->map(function ($value) {
  258. $value = (array)$value;
  259. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  260. $value['created_at'] = transDate($value['created_at']);
  261. $value['episode_created_at'] = transDate($value['episode_created_at']);
  262. return $value;
  263. })->toArray();
  264. }
  265. public function batchSetRoleImg($data) {
  266. $episode_id = getProp($data, 'episode_id');
  267. if (!$episode_id) Utils::throwError('1002:请选择分集');
  268. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  269. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  270. $art_style = getProp($episode, 'art_style');
  271. $anime_id = getProp($episode, 'anime_id');
  272. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  273. $art_style_type = getProp($anime, 'art_style_type');
  274. $character_prefix = '';
  275. $scene_prefix = '';
  276. if ($art_style_type) {
  277. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  278. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  279. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  280. }
  281. foreach ($roles as &$role) {
  282. $role_name = getProp($role, 'role');
  283. if ($role_name == '旁白') continue;
  284. // 优先使用 pic_prompt,如果没有则使用 description
  285. $pic_prompt = getProp($role, 'pic_prompt');
  286. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  287. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  288. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  289. // 参考图地址
  290. $ref_img_url = getProp($role, 'url');
  291. if ($ref_img_url) continue; // 已有图片则跳过
  292. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  293. try {
  294. $params = [
  295. 'prompt' => $description,
  296. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  297. ];
  298. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  299. $task_id = $task->id;
  300. if (!$task_id) {
  301. Utils::throwError("20003:角色({$role_name})生成图片失败");
  302. }
  303. $role['task_id'] = $task_id;
  304. $role['task_status'] = 'processing';
  305. } catch (\Exception $e) {
  306. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  307. Utils::throwError("20003:" . $e->getMessage());
  308. }
  309. }
  310. // 保存角色信息
  311. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  312. 'roles' => json_encode($roles, 256),
  313. 'generate_status' => '执行中',
  314. 'generate_at' => date('Y-m-d H:i:s'),
  315. 'updated_at' => date('Y-m-d H:i:s')
  316. ]);
  317. if (!$boolen) {
  318. Utils::throwError('20003:保存角色信息失败');
  319. }
  320. return $boolen;
  321. }
  322. public function batchSetSceneImg($data) {
  323. $episode_id = getProp($data, 'episode_id');
  324. if (!$episode_id) Utils::throwError('1002:请选择分集');
  325. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  326. $scenes = json_decode(getProp($episode, 'scenes'), true);
  327. $art_style = getProp($episode, 'art_style');
  328. $target_scene = getProp($data, 'target_scene');
  329. $anime_id = getProp($episode, 'anime_id');
  330. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  331. $art_style_type = getProp($anime, 'art_style_type');
  332. $character_prefix = '';
  333. $scene_prefix = '';
  334. if ($art_style_type) {
  335. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  336. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  337. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  338. }
  339. foreach ($scenes as &$scene) {
  340. $scene_name = getProp($scene, 'scene');
  341. if ($scene_name != $target_scene) continue;
  342. // 优先使用 pic_prompt,如果没有则使用 description
  343. $pic_prompt = getProp($scene, 'pic_prompt');
  344. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  345. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  346. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  347. // 参考图地址
  348. $ref_img_url = getProp($scene, 'url');
  349. if ($ref_img_url) continue; // 已有图片则跳过
  350. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  351. try {
  352. $params = [
  353. 'prompt' => $description,
  354. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  355. ];
  356. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  357. $task_id = $task->id;
  358. if (!$task_id) {
  359. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  360. }
  361. $scene['task_id'] = $task_id;
  362. $scene['task_status'] = 'processing';
  363. } catch (\Exception $e) {
  364. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  365. Utils::throwError("20003:" . $e->getMessage());
  366. }
  367. }
  368. // 保存场景信息
  369. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  370. 'scenes' => json_encode($scenes, 256),
  371. 'generate_status' => '执行中',
  372. 'generate_at' => date('Y-m-d H:i:s'),
  373. 'updated_at' => date('Y-m-d H:i:s')
  374. ]);
  375. if (!$boolen) {
  376. Utils::throwError('20003:保存角色信息失败');
  377. }
  378. return $boolen;
  379. }
  380. public function editAnime($data) {
  381. $anime_id = getProp($data, 'anime_id');
  382. $anime_name = trim(getProp($data, 'anime_name'));
  383. // 确认对话名称唯一性
  384. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  385. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  386. }
  387. if (!$anime_id || !$anime_name) {
  388. Utils::throwError('20003:参数异常');
  389. }
  390. return DB::table('mp_animes')->where('id', $anime_id)->update([
  391. 'anime_name' => $anime_name,
  392. 'updated_at' => date('Y-m-d H:i:s')
  393. ]);
  394. // $script_arr =getProp($data, 'script', []);
  395. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  396. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  397. // $anime_id = getProp($data, 'anime_id');
  398. // try {
  399. // DB::beginTransaction();
  400. // $table_data = [
  401. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  402. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  403. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  404. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  405. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  406. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  407. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  408. // 'status' => 3,
  409. // 'start_episode_sequence' => $start_episode_sequence,
  410. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  411. // 'episode_num' => count($script_arr['episodes']),
  412. // 'updated_at' => date('Y-m-d H:i:s')
  413. // ];
  414. // // 保存剧本内容
  415. // if (!empty($anime_id)) {
  416. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  417. // if (!$boolen) {
  418. // dLog('anime')->info('对话保存失败', $table_data);
  419. // Utils::throwError('20003:对话保存失败');
  420. // }
  421. // }else {
  422. // $table['created_at'] = $table_data['updated_at'];
  423. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  424. // if (!$anime_id) {
  425. // dLog('anime')->info('对话保存失败', $table_data);
  426. // Utils::throwError('20003:对话保存失败');
  427. // }
  428. // }
  429. // // 保存分集内容
  430. // // 删除历史分集内容
  431. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  432. // $episodes = [];
  433. // $sequence = 1;
  434. // foreach ($script_arr['episodes'] as $episode) {
  435. // $segment_number = 1;
  436. // foreach($episode['segments'] as $segment) {
  437. // $episodes[] = [
  438. // 'anime_id' => $anime_id,
  439. // 'episode_number' => $episode['episode_number'],
  440. // 'title' => $episode['title'],
  441. // // 'content' => $episode['content'],
  442. // 'content' => '',
  443. // 'segment_number' => $segment_number,
  444. // 'segment_content' => $segment['segment_content'],
  445. // 'sequence' => $sequence,
  446. // 'created_at' => date('Y-m-d H:i:s'),
  447. // 'updated_at' => date('Y-m-d H:i:s')
  448. // ];
  449. // $sequence++;
  450. // $segment_number++;
  451. // }
  452. // }
  453. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  454. // if (!$boolen2) {
  455. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  456. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  457. // Utils::throwError('20003:分集内容保存失败');
  458. // }
  459. // } catch (\Exception $e) {
  460. // DB::rollBack();
  461. // Utils::throwError('20003:'.$e->getMessage());
  462. // }
  463. // DB::commit();
  464. // return true;
  465. }
  466. public function delAnime($data) {
  467. $anime_id = getProp($data, 'anime_id');
  468. if (!$anime_id) {
  469. Utils::throwError('20003:请选择剧本');
  470. }
  471. return DB::table('mp_animes')->where('id', $anime_id)->update([
  472. 'is_deleted' => 1,
  473. 'updated_at' => date('Y-m-d H:i:s')
  474. ]);
  475. }
  476. public function animeDetail($data) {
  477. $uid = Site::getUid();
  478. $anime_id = getProp($data, 'anime_id');
  479. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  480. ->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();
  481. if (!$anime) Utils::throwError('20003:权限不足');
  482. $anime = (array)$anime;
  483. $anime['roles'] = json_decode($anime['roles']);
  484. $anime['scenes'] = json_decode($anime['scenes']);
  485. // 获取分集信息
  486. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  487. ->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"))
  488. ->orderBy('episode_number')->get()->map(function ($value) {
  489. return (array)$value;
  490. })->toArray();
  491. $anime['episodes'] = $episodes;
  492. return $anime;
  493. }
  494. public function episodeInfo($data) {
  495. $uid = Site::getUid();
  496. $anime_id = getProp($data, 'anime_id');
  497. $episode_id = getProp($data, 'episode_id');
  498. if (!$anime_id || !$episode_id) {
  499. Utils::throwError('1002:请选择剧集');
  500. }
  501. // 验证用户权限
  502. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  503. if (!$anime) Utils::throwError('20003:权限不足');
  504. $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();
  505. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  506. $episode = (array)$episode;
  507. $episode['roles'] = json_decode($episode['roles'], true);
  508. // foreach($episode['roles'] as &$item) {
  509. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  510. // }
  511. $episode['scenes'] = json_decode($episode['scenes'], true);
  512. // foreach($episode['scenes'] as &$item) {
  513. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  514. // }
  515. // 获取分镜信息
  516. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  517. ->select('*')->get()->map(function ($value) {
  518. return (array)$value;
  519. })->toArray();
  520. // 使用公共方法构建分镜结构
  521. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  522. $episode['acts'] = $segmentsStructure['acts'];
  523. $episode['total_duration'] = $segmentsStructure['total_duration'];
  524. return $episode;
  525. }
  526. public function episodeInfoForAce($data) {
  527. $anime_id = getProp($data, 'anime_id');
  528. $episode_id = getProp($data, 'episode_id');
  529. if (!$anime_id || !$episode_id) {
  530. Utils::throwError('1002:请选择剧集');
  531. }
  532. $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();
  533. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  534. $episode = (array)$episode;
  535. $episode['roles'] = json_decode($episode['roles'], true);
  536. // foreach($episode['roles'] as &$item) {
  537. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  538. // }
  539. $episode['scenes'] = json_decode($episode['scenes'], true);
  540. // foreach($episode['scenes'] as &$item) {
  541. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  542. // }
  543. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  544. // 获取分镜信息
  545. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  546. ->select('*')->get()->map(function ($value) {
  547. return (array)$value;
  548. })->toArray();
  549. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  550. $episode['acts'] = $segmentsStructure['acts'];
  551. $episode['total_duration'] = $segmentsStructure['total_duration'];
  552. // 获取mp_animes表中的视频参数
  553. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  554. $episode['video_params'] = [
  555. 'video_model' => getProp($anime, 'video_model'),
  556. 'video_resolution' => getProp($anime, 'video_resolution'),
  557. 'ratio' => getProp($anime, 'video_ratio'),
  558. ];
  559. return $episode;
  560. }
  561. public function segmentInfo($data) {
  562. $uid = Site::getUid();
  563. $segment_id = getProp($data, 'segment_id');
  564. if (!$segment_id) {
  565. Utils::throwError('1002:请选择分镜');
  566. }
  567. // 获取分镜信息
  568. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  569. // 验证用户权限
  570. if ($segment) {
  571. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  572. if (!$anime) Utils::throwError('20003:权限不足');
  573. }
  574. $result = [
  575. 'segment_id' => getProp($segment, 'segment_id'),
  576. 'segment_number' => getProp($segment, 'segment_number'),
  577. 'segment_content' => getProp($segment, 'segment_content'),
  578. 'description' => getProp($segment, 'description'),
  579. 'composition' => getProp($segment, 'composition'),
  580. 'camera_movement' => getProp($segment, 'camera_movement'),
  581. 'voice_actor' => getProp($segment, 'voice_actor'),
  582. 'dialogue' => getProp($segment, 'dialogue'),
  583. 'frame_type' => getProp($segment, 'frame_type'),
  584. 'scene' => getProp($segment, 'scene'),
  585. 'characters' => getProp($segment, 'characters'),
  586. 'tail_frame' => getProp($segment, 'tail_frame'),
  587. 'emotion' => getProp($segment, 'emotion'),
  588. 'emotion_type' => getProp($segment, 'emotion_type'),
  589. 'gender' => getProp($segment, 'gender'),
  590. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  591. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  592. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  593. 'pitch' => getProp($segment, 'pitch'),
  594. 'voice_name' => getProp($segment, 'voice_name'),
  595. 'voice_type' => getProp($segment, 'voice_type'),
  596. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  597. 'img_url' => getProp($segment, 'img_url'),
  598. 'video_url' => getProp($segment, 'video_url'),
  599. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  600. ];
  601. return $result;
  602. }
  603. public function copyEpisodeVersion($data) {
  604. $episode_id = getProp($data, 'episode_id');
  605. $uid = Site::getUid();
  606. $cpid = Site::getCpid();
  607. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  608. if (!$episode) Utils::throwError('20003:该剧集不存在');
  609. $episode = (array)$episode;
  610. $anime_id = $episode['anime_id'];
  611. $episode_number = $episode['episode_number'];
  612. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  613. $sequence = $count + 1;
  614. unset($episode['id']);
  615. $now = date('Y-m-d H:i:s');
  616. $episode['created_at'] = $now;
  617. $episode['updated_at'] = $now;
  618. $episode['is_default'] = 1;
  619. // 获取版本中含有"(副本"字样的个数
  620. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  621. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  622. $episode['sequence'] = $sequence;
  623. $episode['is_generated'] = 0;
  624. $episode['cpid'] = $cpid;
  625. // 获取ace_mode
  626. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  627. try {
  628. DB::beginTransaction();
  629. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  630. // 新增副本
  631. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  632. if (!$new_episode_id) {
  633. Utils::throwError('20003:创建副本失败!');
  634. }
  635. // 获取分镜数据并准备插入
  636. $segments_for_insert = DB::table('mp_episode_segments')
  637. ->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')
  638. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  639. $item = (array)$item;
  640. $item['episode_id'] = $new_episode_id;
  641. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  642. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  643. return $item;
  644. })->toArray();
  645. // 写入分镜数据
  646. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  647. if (!$boolen2) {
  648. Utils::throwError('20003:写入分镜数据失败!');
  649. }
  650. // 写入对话历史
  651. $records = [
  652. [
  653. 'uid' => $uid,
  654. 'anime_id' => $anime_id,
  655. 'role' => 'user',
  656. 'content' => '创建副本',
  657. 'sequence' => $episode_number,
  658. 'episode_id' => $new_episode_id,
  659. 'created_at' => $now,
  660. 'updated_at' => $now
  661. ],
  662. [
  663. 'uid' => $uid,
  664. 'anime_id' => $anime_id,
  665. 'role' => 'assistant',
  666. 'content' => '好的,已为您创建副本',
  667. 'sequence' => $episode_number,
  668. 'episode_id' => $new_episode_id,
  669. 'created_at' => $now,
  670. 'updated_at' => $now
  671. ]
  672. ];
  673. $boolen3 = DB::table('mp_anime_records')->insert($records);
  674. if (!$boolen3) {
  675. Utils::throwError('20003:对话记录保存失败');
  676. }
  677. }catch (\Exception $e) {
  678. DB::rollBack();
  679. Utils::throwError('20003:'.$e->getMessage());
  680. }
  681. DB::commit();
  682. // 构建与 episodeInfo 方法一致的返回数据结构
  683. $result = [
  684. 'episode_id' => $new_episode_id,
  685. 'anime_id' => $anime_id,
  686. 'episode_number' => $episode_number,
  687. 'title' => $episode['title'],
  688. 'intro' => $episode['intro'],
  689. 'art_style' => $episode['art_style'],
  690. 'roles' => json_decode($episode['roles'], true),
  691. 'scenes' => json_decode($episode['scenes'], true),
  692. 'is_generated' => (int)$episode['is_generated']
  693. ];
  694. if ((int)$ace_mode === 1) {
  695. // 获取分镜信息
  696. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  697. ->select('*')->get()->map(function ($value) {
  698. return (array)$value;
  699. })->toArray();
  700. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  701. }else {
  702. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  703. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  704. }
  705. $result['acts'] = $segmentsStructure['acts'];
  706. $result['total_duration'] = $segmentsStructure['total_duration'];
  707. return $result;
  708. }
  709. public function episodeVersions($data) {
  710. $anime_id = getProp($data, 'anime_id');
  711. $episode_id = getProp($data, 'episode_id');
  712. if (!$anime_id || !$episode_id) {
  713. Utils::throwError('1002:请选择剧集');
  714. }
  715. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  716. $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) {
  717. return (array)$value;
  718. })->toArray();
  719. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  720. foreach($episodes as &$episode) {
  721. $episode['version'] = 'V'.$episode['sequence'];
  722. $episode['roles'] = json_decode($episode['roles'], true);
  723. $episode['scenes'] = json_decode($episode['scenes'], true);
  724. // 获取分镜信息
  725. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  726. ->select('*')->get()->map(function ($value) {
  727. return (array)$value;
  728. })->toArray();
  729. // 使用公共方法构建分镜结构
  730. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  731. $episode['acts'] = $segmentsStructure['acts'];
  732. $episode['total_duration'] = $segmentsStructure['total_duration'];
  733. }
  734. return $episodes;
  735. }
  736. public function bindEpisodeVersion($data) {
  737. $episode_id = getProp($data, 'episode_id');
  738. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  739. if (!$episode) Utils::throwError('20003:该剧集不存在');
  740. $episode = (array)$episode;
  741. if ((int)$episode['is_default'] === 1) return true;
  742. try {
  743. DB::beginTransaction();
  744. // 移除is_default标志
  745. $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')]);
  746. if (!$boolen) {
  747. Utils::throwError('20003:更新失败!');
  748. }
  749. // 绑定副本
  750. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  751. if (!$boolen2) {
  752. Utils::throwError('20003:绑定失败!');
  753. }
  754. }catch (\Exception $e) {
  755. DB::rollBack();
  756. Utils::throwError('20003:'.$e->getMessage());
  757. }
  758. DB::commit();
  759. return true;
  760. }
  761. public function chatChangeImg($data) {
  762. $segment_id = getProp($data, 'segment_id');
  763. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  764. $prompt = getProp($data, 'prompt');
  765. if (!$prompt || !$segment_id) {
  766. Utils::throwError('1002:请输入提示词,并且选择分镜');
  767. }
  768. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  769. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  770. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  771. else $ref_img_url = '';
  772. // $ref_img_url = '';
  773. if (empty($prompt)) {
  774. if (empty($ref_img_url)) {
  775. $prompt = getProp($segment, 'segment_content');
  776. }else {
  777. $prompt = '请根据图片生成';
  778. }
  779. }
  780. $anime_id = getProp($segment, 'anime_id');
  781. $episode_id = getProp($segment, 'episode_id');
  782. $episode_number = getProp($segment, 'episode_number');
  783. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  784. $ratio = getProp($data, 'ratio');
  785. if (!$ratio) {
  786. $ratio = getProp($episode, 'ratio');
  787. if (!$ratio) $ratio = '9:16';
  788. }
  789. $art_style = getProp($episode, 'art_style');
  790. if ($art_style) {
  791. $prompt = "美术风格:{$art_style}\n{$prompt}";
  792. }
  793. $dimensions = $this->getRatioDimensions($ratio);
  794. $width = $dimensions['width'];
  795. $height = $dimensions['height'];
  796. try {
  797. $params = [
  798. 'alias_segment_id' => $segment_id,
  799. 'prompt' => $prompt,
  800. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  801. 'width' => $width,
  802. 'height' => $height
  803. ];
  804. // 优化提示词(不要生成字幕)
  805. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  806. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  807. $task_id = $task->id;
  808. if (!$task_id) {
  809. Utils::throwError("20003:生成图片失败");
  810. }
  811. // 更新任务ID
  812. $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')]);
  813. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  814. } catch (\Exception $e) {
  815. Utils::throwError("20003:" . $e->getMessage());
  816. }
  817. // 创建任务之后先暂停10s等待异步任务完成
  818. sleep(10);
  819. $img_url = $this->loopGetPicTaskResult($task_id);
  820. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  821. // 图片生成后新增对话记录
  822. try {
  823. $uid = Site::getUid();
  824. $now = date('Y-m-d H:i:s');
  825. // 使用AI反推图片提示词
  826. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  827. // 保存对话记录
  828. $records = [
  829. [
  830. 'uid' => $uid,
  831. 'anime_id' => $anime_id,
  832. 'sequence' => $episode_number,
  833. 'role' => 'user',
  834. 'content' => $prompt,
  835. 'segment_id' => $segment_id,
  836. 'pic_task_id' => $task_id,
  837. 'image_url' => '',
  838. 'created_at' => $now,
  839. 'updated_at' => $now
  840. ],
  841. [
  842. 'uid' => $uid,
  843. 'anime_id' => $anime_id,
  844. 'sequence' => $episode_number,
  845. 'role' => 'assistant',
  846. 'content' => $pic_prompt,
  847. 'segment_id' => $segment_id,
  848. 'pic_task_id' => $task_id,
  849. 'image_url' => $img_url,
  850. 'created_at' => $now,
  851. 'updated_at' => $now
  852. ]
  853. ];
  854. DB::table('mp_anime_records')->insert($records);
  855. } catch (\Exception $e) {
  856. // 记录日志但不影响主流程
  857. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  858. 'segment_id' => $segment_id,
  859. 'img_url' => $img_url
  860. ]);
  861. logDB('anime', 'error', '保存对话记录失败', [
  862. 'segment_id' => $segment_id,
  863. 'img_url' => $img_url,
  864. 'error' => $e->getMessage()
  865. ]);
  866. }
  867. return $img_url;
  868. }
  869. public function segmentChatHistory($data) {
  870. $segment_id = getProp($data, 'segment_id');
  871. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  872. $query = DB::table('mp_anime_records')->where('segment_id', $segment_id)->select('role', 'content', 'segment_id', 'image_url', 'video_url', 'video_task_id', 'pic_task_id', 'created_at');
  873. $chat = $query->orderBy('id')->get()->map(function ($value) {
  874. $value = (array)$value;
  875. $value['created_at'] = transDate($value['created_at']);
  876. return $value;
  877. })->toArray();
  878. // 获取历史图片
  879. $url = [];
  880. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  881. foreach($pic_history as $task) {
  882. $result_url = getProp($task, 'result_url');
  883. if (is_json($result_url)) {
  884. $url = array_merge($url, json_decode($result_url, true));
  885. }else {
  886. $url[] = $result_url;
  887. }
  888. }
  889. // 获取历史视频
  890. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  891. foreach($video_history as $task) {
  892. $result_url = getProp($task, 'compressed_url');
  893. if (is_json($result_url)) {
  894. $url = array_merge($url, json_decode($result_url, true));
  895. }else {
  896. $url[] = $result_url;
  897. }
  898. }
  899. return compact('chat', 'url');
  900. }
  901. public function changeEpisodeRoles($data) {
  902. $anime_id = getProp($data, 'anime_id');
  903. $episode_id = getProp($data, 'episode_id');
  904. $target_roles = getProp($data, 'roles');
  905. $is_deleted = getProp($data, 'is_deleted', 0);
  906. // 参数验证
  907. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  908. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  909. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  910. // 验证剧集是否存在
  911. $episode = DB::table('mp_anime_episodes')
  912. ->where('anime_id', $anime_id)
  913. ->where('id', $episode_id)
  914. ->first();
  915. if (!$episode) Utils::throwError('20003:该剧集不存在');
  916. $roles = json_decode(getProp($episode, 'roles'), true);
  917. // 获取anime信息,检查是否有关联的script_id
  918. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  919. if (!$anime) Utils::throwError('20003:动漫不存在');
  920. $script_id = getProp($anime, 'script_id');
  921. $episode_number = getProp($episode, 'episode_number', 1);
  922. $uid = Site::getUid();
  923. $cpid = Site::getCpid();
  924. try {
  925. $target_role_name = getProp($target_roles, 'role');
  926. if (empty($target_role_name)) {
  927. Utils::throwError('20003:角色名称不能为空');
  928. }
  929. // 如果是删除操作
  930. if ($is_deleted == 1) {
  931. // 从角色列表中移除该角色
  932. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  933. return getProp($role, 'role') !== $target_role_name;
  934. }));
  935. // 更新角色列表
  936. $result = DB::table('mp_anime_episodes')
  937. ->where('anime_id', $anime_id)
  938. ->where('id', $episode_id)
  939. ->update([
  940. 'roles' => json_encode($roles, 256),
  941. 'updated_at' => date('Y-m-d H:i:s')
  942. ]);
  943. if ($result === false) {
  944. Utils::throwError('20003:删除角色失败');
  945. }
  946. } else {
  947. // 新增或更新操作
  948. $role_found = false;
  949. $is_new_role = false;
  950. // 查找并更新已存在的角色
  951. foreach($roles as &$role) {
  952. if (getProp($role, 'role') === $target_role_name) {
  953. $role = $target_roles;
  954. $role_found = true;
  955. break;
  956. }
  957. }
  958. // 如果角色不存在,则新增
  959. if (!$role_found) {
  960. $roles[] = $target_roles;
  961. $is_new_role = true;
  962. }
  963. // 更新角色列表
  964. $result = DB::table('mp_anime_episodes')
  965. ->where('anime_id', $anime_id)
  966. ->where('id', $episode_id)
  967. ->update([
  968. 'roles' => json_encode($roles, 256),
  969. 'updated_at' => date('Y-m-d H:i:s')
  970. ]);
  971. if ($result === false) {
  972. Utils::throwError('20003:更新角色列表失败');
  973. }
  974. // 同步更新分镜表中对应主体的音色信息
  975. $voice_name = getProp($target_roles, 'voice_name');
  976. $voice_type = getProp($target_roles, 'voice_type');
  977. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  978. DB::table('mp_episode_segments')
  979. ->where('anime_id', $anime_id)
  980. ->where('episode_id', $episode_id)
  981. ->where('voice_actor', $target_role_name)
  982. ->update([
  983. 'voice_name' => $voice_name,
  984. 'voice_type' => $voice_type,
  985. 'voice_audio_url' => $voice_audio_url,
  986. 'updated_at' => date('Y-m-d H:i:s')
  987. ]);
  988. // 如果有关联的script_id,则同步到mp_products表
  989. if ($script_id) {
  990. // 查询剧本信息
  991. $script = DB::table('mp_scripts')
  992. ->where('id', $script_id)
  993. ->where('is_deleted', 0)
  994. ->first();
  995. if ($script) {
  996. $script_name = $script->script_name ?? 'script_' . $script_id;
  997. $product_name = getProp($target_roles, 'role');
  998. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  999. $url = getProp($target_roles, 'url', '');
  1000. $product_type = 1; // 1=角色
  1001. // 查找或创建以script_name命名的文件夹
  1002. $folder = DB::table('mp_products')
  1003. ->where('cpid', $cpid)
  1004. ->where('type', 2) // 文件夹类型
  1005. ->where('product', $product_type) // 角色类型
  1006. ->where('product_name', $script_name)
  1007. ->where('parent_id', 0)
  1008. ->where('is_deleted', 0)
  1009. ->first();
  1010. if (!$folder) {
  1011. // 创建文件夹
  1012. $folder_id = DB::table('mp_products')->insertGetId([
  1013. 'user_id' => $uid,
  1014. 'cpid' => $cpid,
  1015. 'type' => 2, // 文件夹
  1016. 'product' => $product_type, // 角色类型
  1017. 'parent_id' => 0,
  1018. 'level' => 1,
  1019. 'product_name' => $script_name,
  1020. 'sort_order' => time(),
  1021. 'is_deleted' => 0,
  1022. 'created_at' => date('Y-m-d H:i:s'),
  1023. 'updated_at' => date('Y-m-d H:i:s')
  1024. ]);
  1025. } else {
  1026. $folder_id = $folder->id;
  1027. }
  1028. // 查找该文件夹下是否已存在同名资产
  1029. $existing_product = DB::table('mp_products')
  1030. ->where('cpid', $cpid)
  1031. ->where('type', 1) // 资产类型
  1032. ->where('product', $product_type)
  1033. ->where('parent_id', $folder_id)
  1034. ->where('product_name', $product_name)
  1035. ->where('is_deleted', 0)
  1036. ->first();
  1037. if ($existing_product) {
  1038. // 更新已存在的资产
  1039. $updateData = [
  1040. 'pic_task_status' => '生成成功',
  1041. ];
  1042. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1043. if ($url) $updateData['url'] = $url;
  1044. // 处理versions字段
  1045. $versions = getProp($target_roles, 'versions', []);
  1046. if ($versions && is_array($versions)) {
  1047. $updateData['versions'] = json_encode($versions, 256);
  1048. }
  1049. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1050. DB::table('mp_products')
  1051. ->where('id', $existing_product->id)
  1052. ->update($updateData);
  1053. $product_id = $existing_product->id;
  1054. } else {
  1055. // 创建新资产
  1056. $versions = getProp($target_roles, 'versions', []);
  1057. $product_id = DB::table('mp_products')->insertGetId([
  1058. 'user_id' => $uid,
  1059. 'cpid' => $cpid,
  1060. 'type' => 1, // 资产
  1061. 'product' => $product_type, // 角色
  1062. 'parent_id' => $folder_id,
  1063. 'level' => 2,
  1064. 'product_name' => $product_name,
  1065. 'url' => $url,
  1066. 'pic_prompt' => $pic_prompt,
  1067. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1068. 'sort_order' => time(),
  1069. 'is_deleted' => 0,
  1070. 'pic_task_status' => '生成成功',
  1071. 'created_at' => date('Y-m-d H:i:s'),
  1072. 'updated_at' => date('Y-m-d H:i:s')
  1073. ]);
  1074. }
  1075. // 建立或更新绑定关系
  1076. $existing_mapping = DB::table('mp_script_product_mappings')
  1077. ->where('script_id', $script_id)
  1078. ->where('product_id', $product_id)
  1079. ->where('episode_number', $episode_number)
  1080. ->first();
  1081. if (!$existing_mapping) {
  1082. // 创建绑定关系
  1083. DB::table('mp_script_product_mappings')->insert([
  1084. 'script_id' => $script_id,
  1085. 'product_id' => $product_id,
  1086. 'episode_number' => $episode_number,
  1087. 'created_at' => date('Y-m-d H:i:s'),
  1088. 'updated_at' => date('Y-m-d H:i:s')
  1089. ]);
  1090. }
  1091. }
  1092. }
  1093. }
  1094. } catch (\Exception $e) {
  1095. dLog('anime')->error('更新剧集角色失败', [
  1096. 'anime_id' => $anime_id,
  1097. 'episode_id' => $episode_id,
  1098. 'error' => $e->getMessage()
  1099. ]);
  1100. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1101. }
  1102. return true;
  1103. }
  1104. public function changeEpisodeScenes($data) {
  1105. $anime_id = getProp($data, 'anime_id');
  1106. $episode_id = getProp($data, 'episode_id');
  1107. $target_scenes = getProp($data, 'scenes');
  1108. $is_deleted = getProp($data, 'is_deleted', 0);
  1109. // 参数验证
  1110. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1111. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1112. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1113. // 验证剧集是否存在
  1114. $episode = DB::table('mp_anime_episodes')
  1115. ->where('anime_id', $anime_id)
  1116. ->where('id', $episode_id)
  1117. ->first();
  1118. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1119. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1120. // 获取anime信息,检查是否有关联的script_id
  1121. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1122. if (!$anime) Utils::throwError('20003:动漫不存在');
  1123. $script_id = getProp($anime, 'script_id');
  1124. $episode_number = getProp($episode, 'episode_number', 1);
  1125. $uid = Site::getUid();
  1126. $cpid = Site::getCpid();
  1127. try {
  1128. $target_scene_name = getProp($target_scenes, 'scene');
  1129. if (empty($target_scene_name)) {
  1130. Utils::throwError('20003:场景名称不能为空');
  1131. }
  1132. // 如果是删除操作
  1133. if ($is_deleted == 1) {
  1134. // 从场景列表中移除该场景
  1135. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1136. return getProp($scene, 'scene') !== $target_scene_name;
  1137. }));
  1138. // 更新场景列表
  1139. $result = DB::table('mp_anime_episodes')
  1140. ->where('anime_id', $anime_id)
  1141. ->where('id', $episode_id)
  1142. ->update([
  1143. 'scenes' => json_encode($scenes, 256),
  1144. 'updated_at' => date('Y-m-d H:i:s')
  1145. ]);
  1146. if ($result === false) {
  1147. Utils::throwError('20003:删除场景失败');
  1148. }
  1149. } else {
  1150. // 新增或更新操作
  1151. $scene_found = false;
  1152. $is_new_scene = false;
  1153. // 查找并更新已存在的场景
  1154. foreach($scenes as &$scene) {
  1155. if (getProp($scene, 'scene') === $target_scene_name) {
  1156. $scene = $target_scenes;
  1157. $scene_found = true;
  1158. break;
  1159. }
  1160. }
  1161. // 如果场景不存在,则新增
  1162. if (!$scene_found) {
  1163. $scenes[] = $target_scenes;
  1164. $is_new_scene = true;
  1165. }
  1166. // 更新场景列表
  1167. $result = DB::table('mp_anime_episodes')
  1168. ->where('anime_id', $anime_id)
  1169. ->where('id', $episode_id)
  1170. ->update([
  1171. 'scenes' => json_encode($scenes, 256),
  1172. 'updated_at' => date('Y-m-d H:i:s')
  1173. ]);
  1174. if ($result === false) {
  1175. Utils::throwError('20003:更新场景列表失败');
  1176. }
  1177. // 如果有关联的script_id,则同步到mp_products表
  1178. if ($script_id) {
  1179. // 查询剧本信息
  1180. $script = DB::table('mp_scripts')
  1181. ->where('id', $script_id)
  1182. ->where('is_deleted', 0)
  1183. ->first();
  1184. if ($script) {
  1185. $script_name = $script->script_name ?? 'script_' . $script_id;
  1186. $product_name = getProp($target_scenes, 'scene');
  1187. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1188. $url = getProp($target_scenes, 'url', '');
  1189. $product_type = 2; // 2=场景
  1190. // 查找或创建以script_name命名的文件夹
  1191. $folder = DB::table('mp_products')
  1192. ->where('cpid', $cpid)
  1193. ->where('type', 2) // 文件夹类型
  1194. ->where('product', $product_type) // 场景类型
  1195. ->where('product_name', $script_name)
  1196. ->where('parent_id', 0)
  1197. ->where('is_deleted', 0)
  1198. ->first();
  1199. if (!$folder) {
  1200. // 创建文件夹
  1201. $folder_id = DB::table('mp_products')->insertGetId([
  1202. 'user_id' => $uid,
  1203. 'cpid' => $cpid,
  1204. 'type' => 2, // 文件夹
  1205. 'product' => $product_type, // 场景类型
  1206. 'parent_id' => 0,
  1207. 'level' => 1,
  1208. 'product_name' => $script_name,
  1209. 'sort_order' => time(),
  1210. 'is_deleted' => 0,
  1211. 'created_at' => date('Y-m-d H:i:s'),
  1212. 'updated_at' => date('Y-m-d H:i:s')
  1213. ]);
  1214. } else {
  1215. $folder_id = $folder->id;
  1216. }
  1217. // 查找该文件夹下是否已存在同名资产
  1218. $existing_product = DB::table('mp_products')
  1219. ->where('cpid', $cpid)
  1220. ->where('type', 1) // 资产类型
  1221. ->where('product', $product_type)
  1222. ->where('parent_id', $folder_id)
  1223. ->where('product_name', $product_name)
  1224. ->where('is_deleted', 0)
  1225. ->first();
  1226. if ($existing_product) {
  1227. // 更新已存在的资产
  1228. $updateData = [
  1229. 'pic_task_status' => '生成成功'
  1230. ];
  1231. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1232. if ($url) $updateData['url'] = $url;
  1233. // 处理versions字段
  1234. $versions = getProp($target_scenes, 'versions', []);
  1235. if ($versions && is_array($versions)) {
  1236. $updateData['versions'] = json_encode($versions, 256);
  1237. }
  1238. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1239. DB::table('mp_products')
  1240. ->where('id', $existing_product->id)
  1241. ->update($updateData);
  1242. $product_id = $existing_product->id;
  1243. } else {
  1244. // 创建新资产
  1245. $versions = getProp($target_scenes, 'versions', []);
  1246. $product_id = DB::table('mp_products')->insertGetId([
  1247. 'user_id' => $uid,
  1248. 'cpid' => $cpid,
  1249. 'type' => 1, // 资产
  1250. 'product' => $product_type, // 场景
  1251. 'parent_id' => $folder_id,
  1252. 'level' => 2,
  1253. 'product_name' => $product_name,
  1254. 'url' => $url,
  1255. 'pic_prompt' => $pic_prompt,
  1256. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1257. 'sort_order' => time(),
  1258. 'is_deleted' => 0,
  1259. 'pic_task_status' => '生成成功',
  1260. 'created_at' => date('Y-m-d H:i:s'),
  1261. 'updated_at' => date('Y-m-d H:i:s')
  1262. ]);
  1263. }
  1264. // 建立或更新绑定关系
  1265. $existing_mapping = DB::table('mp_script_product_mappings')
  1266. ->where('script_id', $script_id)
  1267. ->where('product_id', $product_id)
  1268. ->where('episode_number', $episode_number)
  1269. ->first();
  1270. if (!$existing_mapping) {
  1271. // 创建绑定关系
  1272. DB::table('mp_script_product_mappings')->insert([
  1273. 'script_id' => $script_id,
  1274. 'product_id' => $product_id,
  1275. 'episode_number' => $episode_number,
  1276. 'created_at' => date('Y-m-d H:i:s'),
  1277. 'updated_at' => date('Y-m-d H:i:s')
  1278. ]);
  1279. }
  1280. }
  1281. }
  1282. }
  1283. } catch (\Exception $e) {
  1284. dLog('anime')->error('更新剧集场景失败', [
  1285. 'anime_id' => $anime_id,
  1286. 'episode_id' => $episode_id,
  1287. 'error' => $e->getMessage()
  1288. ]);
  1289. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1290. }
  1291. return true;
  1292. }
  1293. public function changeEpisodeProps($data) {
  1294. $anime_id = getProp($data, 'anime_id');
  1295. $episode_id = getProp($data, 'episode_id');
  1296. $target_props = getProp($data, 'props');
  1297. $is_deleted = getProp($data, 'is_deleted', 0);
  1298. // 参数验证
  1299. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1300. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1301. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1302. // 验证剧集是否存在
  1303. $episode = DB::table('mp_anime_episodes')
  1304. ->where('anime_id', $anime_id)
  1305. ->where('id', $episode_id)
  1306. ->first();
  1307. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1308. $props = json_decode(getProp($episode, 'props'), true);
  1309. // 获取anime信息,检查是否有关联的script_id
  1310. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1311. if (!$anime) Utils::throwError('20003:动漫不存在');
  1312. $script_id = getProp($anime, 'script_id');
  1313. $episode_number = getProp($episode, 'episode_number', 1);
  1314. $uid = Site::getUid();
  1315. $cpid = Site::getCpid();
  1316. try {
  1317. $target_prop_name = getProp($target_props, 'prop');
  1318. if (empty($target_prop_name)) {
  1319. Utils::throwError('20003:道具名称不能为空');
  1320. }
  1321. // 如果是删除操作
  1322. if ($is_deleted == 1) {
  1323. // 从道具列表中移除该道具
  1324. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1325. return getProp($prop, 'prop') !== $target_prop_name;
  1326. }));
  1327. // 更新道具列表
  1328. $result = DB::table('mp_anime_episodes')
  1329. ->where('anime_id', $anime_id)
  1330. ->where('id', $episode_id)
  1331. ->update([
  1332. 'props' => json_encode($props, 256),
  1333. 'updated_at' => date('Y-m-d H:i:s')
  1334. ]);
  1335. if ($result === false) {
  1336. Utils::throwError('20003:删除道具失败');
  1337. }
  1338. } else {
  1339. // 新增或更新操作
  1340. $prop_found = false;
  1341. $is_new_prop = false;
  1342. // 查找并更新已存在的道具
  1343. foreach($props as &$prop) {
  1344. if (getProp($prop, 'prop') === $target_prop_name) {
  1345. $prop = $target_props;
  1346. $prop_found = true;
  1347. break;
  1348. }
  1349. }
  1350. // 如果道具不存在,则新增
  1351. if (!$prop_found) {
  1352. $props[] = $target_props;
  1353. $is_new_prop = true;
  1354. }
  1355. // 更新道具列表
  1356. $result = DB::table('mp_anime_episodes')
  1357. ->where('anime_id', $anime_id)
  1358. ->where('id', $episode_id)
  1359. ->update([
  1360. 'props' => json_encode($props, 256),
  1361. 'updated_at' => date('Y-m-d H:i:s')
  1362. ]);
  1363. if ($result === false) {
  1364. Utils::throwError('20003:更新道具列表失败');
  1365. }
  1366. // 如果有关联的script_id,则同步到mp_products表
  1367. if ($script_id) {
  1368. // 查询剧本信息
  1369. $script = DB::table('mp_scripts')
  1370. ->where('id', $script_id)
  1371. ->where('is_deleted', 0)
  1372. ->first();
  1373. if ($script) {
  1374. $script_name = $script->script_name ?? 'script_' . $script_id;
  1375. $product_name = getProp($target_props, 'prop');
  1376. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1377. $url = getProp($target_props, 'url', '');
  1378. $product_type = 3; // 3=道具
  1379. // 查找或创建以script_name命名的文件夹
  1380. $folder = DB::table('mp_products')
  1381. ->where('cpid', $cpid)
  1382. ->where('type', 2) // 文件夹类型
  1383. ->where('product', $product_type) // 道具类型
  1384. ->where('product_name', $script_name)
  1385. ->where('parent_id', 0)
  1386. ->where('is_deleted', 0)
  1387. ->first();
  1388. if (!$folder) {
  1389. // 创建文件夹
  1390. $folder_id = DB::table('mp_products')->insertGetId([
  1391. 'user_id' => $uid,
  1392. 'cpid' => $cpid,
  1393. 'type' => 2, // 文件夹
  1394. 'product' => $product_type, // 道具类型
  1395. 'parent_id' => 0,
  1396. 'level' => 1,
  1397. 'product_name' => $script_name,
  1398. 'sort_order' => time(),
  1399. 'is_deleted' => 0,
  1400. 'created_at' => date('Y-m-d H:i:s'),
  1401. 'updated_at' => date('Y-m-d H:i:s')
  1402. ]);
  1403. } else {
  1404. $folder_id = $folder->id;
  1405. }
  1406. // 查找该文件夹下是否已存在同名资产
  1407. $existing_product = DB::table('mp_products')
  1408. ->where('cpid', $cpid)
  1409. ->where('type', 1) // 资产类型
  1410. ->where('product', $product_type)
  1411. ->where('parent_id', $folder_id)
  1412. ->where('product_name', $product_name)
  1413. ->where('is_deleted', 0)
  1414. ->first();
  1415. if ($existing_product) {
  1416. // 更新已存在的资产
  1417. $updateData = [
  1418. 'pic_task_status' => '生成成功'
  1419. ];
  1420. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1421. if ($url) $updateData['url'] = $url;
  1422. // 处理versions字段
  1423. $versions = getProp($target_props, 'versions', []);
  1424. if ($versions && is_array($versions)) {
  1425. $updateData['versions'] = json_encode($versions, 256);
  1426. }
  1427. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1428. DB::table('mp_products')
  1429. ->where('id', $existing_product->id)
  1430. ->update($updateData);
  1431. $product_id = $existing_product->id;
  1432. } else {
  1433. // 创建新资产
  1434. $versions = getProp($target_props, 'versions', []);
  1435. $product_id = DB::table('mp_products')->insertGetId([
  1436. 'user_id' => $uid,
  1437. 'cpid' => $cpid,
  1438. 'type' => 1, // 资产
  1439. 'product' => $product_type, // 道具
  1440. 'parent_id' => $folder_id,
  1441. 'level' => 2,
  1442. 'product_name' => $product_name,
  1443. 'url' => $url,
  1444. 'pic_prompt' => $pic_prompt,
  1445. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1446. 'sort_order' => time(),
  1447. 'is_deleted' => 0,
  1448. 'pic_task_status' => '生成成功',
  1449. 'created_at' => date('Y-m-d H:i:s'),
  1450. 'updated_at' => date('Y-m-d H:i:s')
  1451. ]);
  1452. }
  1453. // 建立或更新绑定关系
  1454. $existing_mapping = DB::table('mp_script_product_mappings')
  1455. ->where('script_id', $script_id)
  1456. ->where('product_id', $product_id)
  1457. ->where('episode_number', $episode_number)
  1458. ->first();
  1459. if (!$existing_mapping) {
  1460. // 创建绑定关系
  1461. DB::table('mp_script_product_mappings')->insert([
  1462. 'script_id' => $script_id,
  1463. 'product_id' => $product_id,
  1464. 'episode_number' => $episode_number,
  1465. 'created_at' => date('Y-m-d H:i:s'),
  1466. 'updated_at' => date('Y-m-d H:i:s')
  1467. ]);
  1468. }
  1469. }
  1470. }
  1471. }
  1472. } catch (\Exception $e) {
  1473. dLog('anime')->error('更新剧集道具失败', [
  1474. 'anime_id' => $anime_id,
  1475. 'episode_id' => $episode_id,
  1476. 'error' => $e->getMessage()
  1477. ]);
  1478. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1479. }
  1480. return true;
  1481. }
  1482. public function editSegment($data) {
  1483. $segment_id = getProp($data, 'segment_id');
  1484. $segment_content = getProp($data, 'segment_content');
  1485. $image_url = getProp($data, 'image_url');
  1486. $video_url = getProp($data, 'video_url');
  1487. // 参数验证
  1488. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1489. // 验证分镜是否存在
  1490. $segment = DB::table('mp_episode_segments')
  1491. ->where('segment_id', $segment_id)
  1492. ->first();
  1493. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1494. $dubTaskId = 0;
  1495. try {
  1496. DB::beginTransaction();
  1497. // 准备更新数据
  1498. $update_data = [
  1499. 'updated_at' => date('Y-m-d H:i:s')
  1500. ];
  1501. if ($segment_content) {
  1502. // 先将segment_content赋值到update_data
  1503. $update_data['segment_content'] = $segment_content;
  1504. // 使用现有方法分析segment_content,提取各个字段
  1505. $this->handleSegmentContent($update_data);
  1506. // 如果有对话内容,创建视频配音合成任务
  1507. $dialogue = getProp($update_data, 'dialogue');
  1508. if (!empty($dialogue)) {
  1509. $now = date('Y-m-d H:i:s');
  1510. $generate_json = [
  1511. 'text' => $dialogue,
  1512. 'role' => getProp($update_data, 'voice_actor'),
  1513. 'voice_type' => getProp($update_data, 'voice_type'),
  1514. 'voice_name' => getProp($update_data, 'voice_name'),
  1515. 'emotion' => getProp($update_data, 'emotion'),
  1516. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1517. 'gender' => getProp($update_data, 'gender'),
  1518. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1519. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1520. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1521. 'pitch' => getProp($update_data, 'pitch', 0),
  1522. ];
  1523. // 插入视频配音合成任务
  1524. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1525. 'alias_segment_id' => $segment_id,
  1526. 'generate_status' => '执行中',
  1527. 'audio_url' => '',
  1528. 'generate_json' => json_encode($generate_json, 256),
  1529. 'created_at' => $now,
  1530. 'updated_at' => $now,
  1531. ]);
  1532. if (!$dubTaskId) {
  1533. Utils::throwError('20003:创建配音任务失败!');
  1534. }
  1535. $update_data['audio_url'] = '';
  1536. } else {
  1537. // dialogue为空时,直接写入默认音频信息
  1538. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1539. $update_data['audio_duration'] = 2.0;
  1540. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1541. }
  1542. }
  1543. if ($image_url) {
  1544. $update_data['img_url'] = $image_url;
  1545. // 同时写入一个简单的图片生成任务
  1546. $pic_task = [
  1547. 'alias_segment_id' => $segment_id,
  1548. 'ref_img_url' => json_encode([]),
  1549. 'status' => 'success',
  1550. 'result_url' => json_encode([$image_url], 256),
  1551. 'model' => '',
  1552. 'created_at' => date('Y-m-d H:i:s'),
  1553. 'updated_at' => date('Y-m-d H:i:s'),
  1554. ];
  1555. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1556. }
  1557. if ($video_url) {
  1558. $update_data['origin_video_url'] = $video_url;
  1559. $compressed_video_url = compressVideo($video_url);
  1560. $update_data['current_type'] = 2;
  1561. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1562. // 同时写入一个简单的视频生成任务
  1563. $video_task = [
  1564. 'alias_segment_id' => $segment_id,
  1565. 'status' => 'success',
  1566. 'result_url' => $update_data['origin_video_url'],
  1567. 'compressed_url' => $update_data['video_url'],
  1568. 'created_at' => date('Y-m-d H:i:s'),
  1569. 'updated_at' => date('Y-m-d H:i:s'),
  1570. ];
  1571. DB::table('mp_generate_video_tasks')->insert($video_task);
  1572. }
  1573. // 更新分镜信息
  1574. $result = DB::table('mp_episode_segments')
  1575. ->where('segment_id', $segment_id)
  1576. ->update($update_data);
  1577. if ($result === false) {
  1578. Utils::throwError('20003:更新分镜剧本失败');
  1579. }
  1580. DB::commit();
  1581. // 如果有创建音频生成任务则调用API
  1582. if ($dubTaskId) {
  1583. // 请求远程服务器执行生成
  1584. $client = new Client(['timeout' => 300, 'verify' => false]);
  1585. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1586. $response = $result->getBody()->getContents();
  1587. $response_arr = json_decode($response, true);
  1588. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1589. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1590. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1591. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1592. Utils::throwError('20003:火山生成音频失败');
  1593. }
  1594. }
  1595. return true;
  1596. } catch (\Exception $e) {
  1597. DB::rollBack();
  1598. dLog('anime')->error('更新分镜剧本失败', [
  1599. 'segment_id' => $segment_id,
  1600. 'error' => $e->getMessage()
  1601. ]);
  1602. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1603. }
  1604. }
  1605. public function batchSetSegmentPics($data) {
  1606. $anime_id = getProp($data, 'anime_id');
  1607. $episode_id = getProp($data, 'episode_id');
  1608. $ratio = getProp($data, 'ratio');
  1609. $dimensions = $this->getRatioDimensions($ratio);
  1610. $width = $dimensions['width'];
  1611. $height = $dimensions['height'];
  1612. if (!$anime_id || !$episode_id) {
  1613. Utils::throwError('1002:请选择剧集');
  1614. }
  1615. // 获取剧集信息
  1616. $episode = DB::table('mp_anime_episodes')
  1617. ->where('anime_id', $anime_id)
  1618. ->where('id', $episode_id)
  1619. ->where('is_default', 1)
  1620. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1621. ->first();
  1622. if (!$episode) {
  1623. Utils::throwError('20003:该剧集不存在');
  1624. }
  1625. $model = getProp($data, 'model');
  1626. if (!$model) {
  1627. $model = getProp($episode, 'image_model');
  1628. if (!$model) {
  1629. // episode表也没有,使用默认值
  1630. $model = 'doubao-seedream-5-0-lite-260128';
  1631. }
  1632. }
  1633. // 验证模型是否在可用模型表中
  1634. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1635. $model = 'doubao-seedream-5-0-lite-260128';
  1636. }
  1637. $roles = json_decode(getProp($episode, 'roles'), true);
  1638. if (!$roles) {
  1639. Utils::throwError('20003:角色信息格式错误');
  1640. }
  1641. // 构建角色名称到参考图的映射
  1642. $role_map = [];
  1643. foreach ($roles as $role) {
  1644. $role_name = getProp($role, 'role');
  1645. $role_url = getProp($role, 'url');
  1646. if (!empty($role_name) && !empty($role_url)) {
  1647. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1648. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1649. // $role_map[$base_name] = $role_url;
  1650. // 同时保存完整名称的映射
  1651. $role_map[$role_name] = $role_url;
  1652. }
  1653. }
  1654. $scenes = json_decode(getProp($episode, 'roles'), true);
  1655. if (!$scenes) {
  1656. Utils::throwError('20003:场景信息格式错误');
  1657. }
  1658. // 构建角色名称到参考图的映射
  1659. $scene_map = [];
  1660. foreach ($scenes as $scene) {
  1661. $scene_name = getProp($scene, 'scene');
  1662. $scene_url = getProp($scene, 'url');
  1663. if (!empty($scene_name) && !empty($scene_url)) {
  1664. $scene_map[$scene_name] = $scene_url;
  1665. }
  1666. }
  1667. // 获取所有分镜信息
  1668. $segments = DB::table('mp_episode_segments')
  1669. ->where('anime_id', $anime_id)
  1670. ->where('episode_id', $episode_id)
  1671. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1672. ->orderBy('segment_number')
  1673. ->get()
  1674. ->toArray();
  1675. if (empty($segments)) {
  1676. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1677. }
  1678. // 保存图片比例
  1679. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1680. $updated_segments = [];
  1681. $failed_segments = [];
  1682. // 批量为每个分镜生成图片任务
  1683. foreach ($segments as $segment) {
  1684. $segment_id = $segment->segment_id;
  1685. $segment_content = $segment->segment_content;
  1686. if (empty($segment_content)) {
  1687. $failed_segments[] = [
  1688. 'segment_id' => $segment_id,
  1689. 'error' => '分镜内容为空'
  1690. ];
  1691. continue;
  1692. }
  1693. try {
  1694. $dubTaskId = 0;
  1695. // 解析分镜内容,提取画面描述作为主要提示词
  1696. $prompt = $segment_content;
  1697. $ref_img_urls = [];
  1698. // 分镜场景
  1699. $scene = getProp($segment, 'scene');
  1700. $matched_scene = '';
  1701. if (isset($scene_map[$scene])) {
  1702. $img_index = count($ref_img_urls) + 1;
  1703. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1704. $ref_img_urls[] = $scene_map[$scene];
  1705. $matched_scene = $scene;
  1706. }
  1707. // 分镜角色
  1708. $characters = getProp($segment, 'characters');
  1709. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1710. $roles = explode(',', $characters);
  1711. // 从分镜内容中提取涉及的角色
  1712. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1713. // 获取匹配角色的参考图
  1714. foreach ($segment_characters as $character) {
  1715. if (isset($role_map[$character])) {
  1716. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1717. $img_index = count($ref_img_urls) + 1;
  1718. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1719. $ref_img_urls[] = $role_map[$character];
  1720. }
  1721. }
  1722. // 如果没有找到匹配的角色参考图,不使用参考图
  1723. if (empty($ref_img_urls)) {
  1724. $ref_img_urls = [];
  1725. }
  1726. // 准备生成任务参数
  1727. $params = [
  1728. 'model' => $model,
  1729. 'alias_segment_id' => $segment_id,
  1730. 'prompt' => $prompt,
  1731. 'ref_img_urls' => $ref_img_urls,
  1732. 'width' => $width,
  1733. 'height' => $height,
  1734. ];
  1735. // 优化提示词(不要生成字幕)
  1736. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1737. // $task_id = mt_rand(100000, 999999);
  1738. // 调用AI图片生成服务
  1739. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1740. $task_id = $task->id;
  1741. if (!$task_id) {
  1742. $failed_segments[] = [
  1743. 'segment_id' => $segment_id,
  1744. 'error' => '创建生成任务失败'
  1745. ];
  1746. continue;
  1747. }
  1748. $update_data = [
  1749. 'pic_task_id' => $task_id,
  1750. 'pic_task_status' => '生成中',
  1751. 'audio_url' => '',
  1752. 'updated_at' => date('Y-m-d H:i:s')
  1753. ];
  1754. // 如果有对话内容,创建视频配音合成任务
  1755. $dialogue = getProp($segment, 'dialogue');
  1756. if (!empty($dialogue)) {
  1757. $now = date('Y-m-d H:i:s');
  1758. $generate_json = [
  1759. 'text' => $dialogue,
  1760. 'role' => getProp($segment, 'voice_actor'),
  1761. 'voice_type' => getProp($segment, 'voice_type'),
  1762. 'voice_name' => getProp($segment, 'voice_name'),
  1763. 'emotion' => getProp($segment, 'emotion'),
  1764. 'emotion_type' => getProp($segment, 'emotion_type'),
  1765. 'gender' => getProp($segment, 'gender'),
  1766. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1767. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1768. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1769. 'pitch' => getProp($segment, 'pitch', 0),
  1770. ];
  1771. // 插入视频配音合成任务
  1772. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1773. 'alias_segment_id' => $segment_id,
  1774. 'generate_status' => '执行中',
  1775. 'audio_url' => '',
  1776. 'generate_json' => json_encode($generate_json, 256),
  1777. 'created_at' => $now,
  1778. 'updated_at' => $now,
  1779. ]);
  1780. if (!$dubTaskId) {
  1781. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1782. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1783. // Utils::throwError('20003:创建配音任务失败!');
  1784. }
  1785. } else {
  1786. // dialogue为空时,直接写入默认音频信息到分镜表
  1787. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1788. $update_data['audio_duration'] = 2.0;
  1789. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1790. }
  1791. // 更新分镜的任务信息
  1792. $update_result = DB::table('mp_episode_segments')
  1793. ->where('segment_id', $segment_id)
  1794. ->update($update_data);
  1795. // 如果是第一集的首帧图片,则存入待更新数组
  1796. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1797. Redis::sadd('anime_first_frame_urls', $segment_id);
  1798. }
  1799. if ($update_result) {
  1800. $updated_segments[] = [
  1801. 'segment_id' => $segment_id,
  1802. 'task_id' => $task_id,
  1803. 'status' => '生成中',
  1804. 'matched_scenes' => $matched_scene,
  1805. 'matched_roles' => $segment_characters,
  1806. 'ref_urls_count' => count($ref_img_urls)
  1807. ];
  1808. } else {
  1809. $failed_segments[] = [
  1810. 'segment_id' => $segment_id,
  1811. 'error' => '更新分镜任务状态失败'
  1812. ];
  1813. }
  1814. if ($dubTaskId) {
  1815. sleep(1);
  1816. // 请求远程服务器执行生成
  1817. $client = new Client(['timeout' => 300, 'verify' => false]);
  1818. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1819. $response = $result->getBody()->getContents();
  1820. $response_arr = json_decode($response, true);
  1821. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1822. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1823. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1824. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1825. }
  1826. }
  1827. } catch (\Exception $e) {
  1828. $failed_segments[] = [
  1829. 'segment_id' => $segment_id,
  1830. 'error' => $e->getMessage()
  1831. ];
  1832. }
  1833. }
  1834. // 更新剧集生成状态
  1835. if (!empty($updated_segments)) {
  1836. DB::table('mp_anime_episodes')
  1837. ->where('id', $episode_id)
  1838. ->update([
  1839. 'is_generated' => 1,
  1840. 'updated_at' => date('Y-m-d H:i:s')
  1841. ]);
  1842. }
  1843. return [
  1844. 'success_count' => count($updated_segments),
  1845. 'failed_count' => count($failed_segments),
  1846. 'success_segments' => $updated_segments,
  1847. 'failed_segments' => $failed_segments,
  1848. 'total_segments' => count($segments)
  1849. ];
  1850. }
  1851. public function reGenerateSegment($data) {
  1852. $segment_id = getProp($data, 'segment_id');
  1853. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1854. $anime_id = getProp($segment, 'anime_id');
  1855. $episode_id = getProp($segment, 'episode_id');
  1856. $episode_number = getProp($segment, 'episode_number');
  1857. $segment_content = getProp($data, 'segment_content');
  1858. $ratio = getProp($data, 'ratio');
  1859. if (!$ratio) {
  1860. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1861. if (!$ratio) $ratio = '9:16';
  1862. }
  1863. $dimensions = $this->getRatioDimensions($ratio);
  1864. $width = $dimensions['width'];
  1865. $height = $dimensions['height'];
  1866. if (!$anime_id || !$episode_id) {
  1867. Utils::throwError('1002:请选择分镜');
  1868. }
  1869. // 使用文生文模型重新解析segment_content
  1870. if (!empty($segment_content)) {
  1871. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1872. }
  1873. // 获取动漫的角色信息(包含参考图)
  1874. $anime = DB::table('mp_animes')
  1875. ->where('id', $anime_id)
  1876. ->select('roles', 'scenes')
  1877. ->first();
  1878. if (!$anime || !$anime->roles) {
  1879. Utils::throwError('20003:未找到角色信息');
  1880. }
  1881. $roles = json_decode($anime->roles, true);
  1882. if (!$roles) {
  1883. Utils::throwError('20003:角色信息格式错误');
  1884. }
  1885. // 构建角色名称到参考图的映射
  1886. $role_map = [];
  1887. foreach ($roles as $role) {
  1888. $role_name = getProp($role, 'role');
  1889. $role_url = getProp($role, 'url');
  1890. if (!empty($role_name) && !empty($role_url)) {
  1891. $role_map[$role_name] = $role_url;
  1892. }
  1893. }
  1894. $scenes = json_decode($anime->scenes, true);
  1895. if (!$scenes) {
  1896. Utils::throwError('20003:角色信息格式错误');
  1897. }
  1898. // 构建角色名称到参考图的映射
  1899. $scene_map = [];
  1900. foreach ($scenes as $scene) {
  1901. $scene_name = getProp($scene, 'scene');
  1902. $scene_url = getProp($scene, 'url');
  1903. if (!empty($scene_name) && !empty($scene_url)) {
  1904. $scene_map[$scene_name] = $scene_url;
  1905. }
  1906. }
  1907. $segment_id = $segment->segment_id;
  1908. $original_segment_content = $segment->segment_content;
  1909. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1910. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1911. if (empty($final_segment_content)) {
  1912. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1913. }
  1914. try {
  1915. $dubTaskId = 0;
  1916. // 分镜剧本数组
  1917. $update_data = [
  1918. 'segment_content' => $final_segment_content,
  1919. 'pic_task_status' => '生成中',
  1920. 'updated_at' => date('Y-m-d H:i:s')
  1921. ];
  1922. // 解析分镜内容,提取画面描述作为主要提示词
  1923. $prompt = $final_segment_content;
  1924. $ref_img_urls = [];
  1925. // 分镜场景
  1926. $scene = getProp($data, 'scene');
  1927. if ($scene) {
  1928. $matched_scene = '';
  1929. if (isset($scene_map[$scene])) {
  1930. $img_index = count($ref_img_urls) + 1;
  1931. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1932. $ref_img_urls[] = $scene_map[$scene];
  1933. $matched_scene = $scene;
  1934. }
  1935. $update_data['scene'] = $scene;
  1936. }
  1937. // 分镜角色
  1938. $characters = getProp($data, 'characters');
  1939. if ($characters) {
  1940. $update_data['characters'] = $characters;
  1941. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1942. $characters = explode(',', $characters);
  1943. // 从分镜内容中提取涉及的角色
  1944. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1945. // 获取匹配角色的参考图
  1946. foreach ($segment_characters as $character) {
  1947. if (isset($role_map[$character])) {
  1948. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1949. $img_index = count($ref_img_urls) + 1;
  1950. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1951. $ref_img_urls[] = $role_map[$character];
  1952. }
  1953. }
  1954. }
  1955. // 如果没有找到匹配的角色参考图,不使用参考图
  1956. if (empty($ref_img_urls)) {
  1957. $ref_img_urls = [];
  1958. }
  1959. // 准备生成任务参数
  1960. $params = [
  1961. 'alias_segment_id' => $segment_id,
  1962. 'prompt' => $prompt,
  1963. 'ref_img_urls' => $ref_img_urls,
  1964. 'width' => $width,
  1965. 'height' => $height,
  1966. ];
  1967. // 优化提示词(不要生成字幕)
  1968. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1969. // 调用AI图片生成服务
  1970. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1971. $task_id = $task->id;
  1972. if (!$task_id) {
  1973. Utils::throwError('20003:创建生成任务失败!');
  1974. }
  1975. $update_data['pic_task_id'] = $task_id;
  1976. // 更新分镜剧本信息
  1977. $this->handleSegmentContent($update_data);
  1978. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  1979. if ($segment_content) {
  1980. $dialogue = getProp($update_data, 'dialogue');
  1981. if (!empty($dialogue)) {
  1982. $now = date('Y-m-d H:i:s');
  1983. $generate_json = [
  1984. 'text' => $dialogue,
  1985. 'role' => getProp($update_data, 'voice_actor'),
  1986. 'voice_type' => getProp($update_data, 'voice_type'),
  1987. 'voice_name' => getProp($update_data, 'voice_name'),
  1988. 'emotion' => getProp($update_data, 'emotion'),
  1989. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1990. 'gender' => getProp($update_data, 'gender'),
  1991. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1992. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1993. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1994. 'pitch' => getProp($update_data, 'pitch', 0),
  1995. ];
  1996. // 插入视频配音合成任务
  1997. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1998. 'alias_segment_id' => $segment_id,
  1999. 'generate_status' => '执行中',
  2000. 'audio_url' => '',
  2001. 'generate_json' => json_encode($generate_json, 256),
  2002. 'created_at' => date('Y-m-d H:i:s'),
  2003. 'updated_at' => date('Y-m-d H:i:s'),
  2004. ]);
  2005. if (!$dubTaskId) {
  2006. Utils::throwError('20003:创建配音任务失败!');
  2007. }
  2008. $update_data['audio_url'] = '';
  2009. } else {
  2010. // dialogue为空时,直接写入默认音频信息
  2011. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2012. $update_data['audio_duration'] = 2.0;
  2013. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2014. }
  2015. }
  2016. $boolen = DB::table('mp_episode_segments')
  2017. ->where('segment_id', $segment_id)
  2018. ->update($update_data);
  2019. // 如果是第一集的首帧图片,则存入待更新数组
  2020. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2021. Redis::sadd('anime_first_frame_urls', $segment_id);
  2022. }
  2023. if ($dubTaskId) {
  2024. // 请求远程服务器执行生成
  2025. $client = new Client(['timeout' => 300, 'verify' => false]);
  2026. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2027. $response = $result->getBody()->getContents();
  2028. $response_arr = json_decode($response, true);
  2029. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2030. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2031. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2032. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2033. Utils::throwError('20003:火山生成音频失败');
  2034. }
  2035. }
  2036. } catch (\Exception $e) {
  2037. $failed_segments[] = [
  2038. 'segment_id' => $segment_id,
  2039. 'error' => $e->getMessage()
  2040. ];
  2041. }
  2042. // 创建任务之后先暂停10s等待异步任务完成
  2043. sleep(10);
  2044. $img_url = $this->loopGetPicTaskResult($task_id);
  2045. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2046. // 图片生成后新增对话记录
  2047. try {
  2048. $uid = Site::getUid();
  2049. $now = date('Y-m-d H:i:s');
  2050. // 使用AI反推图片提示词
  2051. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2052. // 保存对话记录
  2053. $records = [
  2054. [
  2055. 'uid' => $uid,
  2056. 'anime_id' => $anime_id,
  2057. 'sequence' => $episode_number,
  2058. 'role' => 'user',
  2059. 'content' => '重新生成',
  2060. 'segment_id' => $segment_id,
  2061. 'pic_task_id' => $task_id,
  2062. 'image_url' => '',
  2063. 'created_at' => $now,
  2064. 'updated_at' => $now
  2065. ],
  2066. [
  2067. 'uid' => $uid,
  2068. 'anime_id' => $anime_id,
  2069. 'sequence' => $episode_number,
  2070. 'role' => 'assistant',
  2071. 'content' => $pic_prompt,
  2072. 'segment_id' => $segment_id,
  2073. 'pic_task_id' => $task_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', 'video_task_id', 'pic_task_id', '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. // dd($videoParams);
  4029. // 根据模型选择不同的视频生成方法
  4030. if (strpos($model, 'jimeng') !== false) {
  4031. // 即梦模型参数调整
  4032. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4033. unset($videoParams['content']); // 即梦不使用content格式
  4034. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4035. } elseif (strpos($model, 'kling') !== false) {
  4036. // Keling模型参数调整
  4037. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4038. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4039. unset($videoParams['ratio']);
  4040. unset($videoParams['content']); // Keling不使用content格式
  4041. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4042. } elseif (strpos($model, 'zhizhen') !== false) {
  4043. // 智帧20等新模型使用统一API
  4044. // 构建统一API参数
  4045. $unifiedParams = [
  4046. 'model_code' => $model,
  4047. 'alias_segment_id' => $segment_id,
  4048. 'prompt' => trim($fullPrompt),
  4049. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4050. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4051. 'video_ratio' => $ratio,
  4052. 'seed' => -1,
  4053. ];
  4054. // 构建parameters参数
  4055. $parameters = [
  4056. 'seconds' => $unifiedParams['video_duration'],
  4057. 'resolution' => $unifiedParams['video_resolution'],
  4058. 'ratio' => $ratio,
  4059. // 'video_mode' => 'multi_image',
  4060. // 'mode' => 'multi_image',
  4061. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4062. ];
  4063. $hasImage = false;
  4064. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4065. if ($hasImage) {
  4066. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4067. if (isset($videoParams['tail_frame_url'])) {
  4068. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4069. }
  4070. // 只有在有图片的情况下才能添加参考音频
  4071. if ($audioUrl) {
  4072. // $parameters['reference_audios'] = [$audioUrl];
  4073. }
  4074. } else {
  4075. // 没有图片时,记录错误日志
  4076. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4077. 'segment_id' => $segment_id,
  4078. 'model' => $model
  4079. ]);
  4080. }
  4081. $unifiedParams['parameters'] = $parameters;
  4082. // 调用统一API创建任务
  4083. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4084. } else {
  4085. // Seedance模型(默认)
  4086. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4087. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  4088. // 添加配音音频到content中
  4089. $videoParams['content'][] = [
  4090. 'type' => 'audio_url',
  4091. 'audio_url' => [
  4092. 'url' => $audioUrl,
  4093. ],
  4094. 'role' => 'reference_audio',
  4095. ];
  4096. // 优化提示词,增加音频相关描述
  4097. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4098. $videoParams['prompt'] = $audioPrompt;
  4099. $videoParams['content'][0]['text'] = $audioPrompt;
  4100. } else if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4101. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4102. }
  4103. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4104. }
  4105. // 更新分镜表的视频任务信息
  4106. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4107. 'video_task_id' => $task->id,
  4108. 'video_task_status' => '生成中',
  4109. 'generate_audio' => $generate_audio,
  4110. 'updated_at' => date('Y-m-d H:i:s')
  4111. ]);
  4112. return [
  4113. 'task_id' => $task->id,
  4114. 'status' => $task->status,
  4115. 'segment_id' => $segment_id,
  4116. 'video_duration' => $videoDuration
  4117. ];
  4118. }
  4119. public function createActVideoTask($data) {
  4120. $act_id = getProp($data, 'act_id');
  4121. $first_frame_url = getProp($data, 'first_frame_url');
  4122. $tail_frame_url = getProp($data, 'tail_frame_url');
  4123. $generate_audio = getProp($data, 'generate_audio', 1);
  4124. $video_duration = getProp($data, 'video_duration');
  4125. $video_resolution = getProp($data, 'video_resolution');
  4126. $ratio = getProp($data, 'ratio');
  4127. $products = getProp($data, 'products', []);
  4128. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4129. if (!is_array($reference_images) || !is_array($products)) {
  4130. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4131. }
  4132. if (!$act_id) {
  4133. Utils::throwError('1002:片段ID不能为空');
  4134. }
  4135. // 获取片段信息
  4136. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4137. if (!$act) {
  4138. Utils::throwError('20003:片段不存在');
  4139. }
  4140. $act = (array)$act;
  4141. $anime_id = getProp($act, 'anime_id');
  4142. $episode_id = getProp($act, 'episode_id');
  4143. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4144. $ace_mode = getProp($anime, 'ace_mode');
  4145. $art_style_type = getProp($anime, 'art_style_type');
  4146. $art_style = getProp($anime, 'art_style');
  4147. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4148. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4149. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4150. // 将资产中新出现的资产放到extra_products中
  4151. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4152. if (!empty($products) && $episode) {
  4153. // 获取剧集中的角色、场景和道具列表
  4154. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4155. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4156. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4157. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4158. // 构建角色名称列表
  4159. $role_names = array_column($roles, 'role');
  4160. // 构建场景名称列表
  4161. $scene_names = array_column($scenes, 'scene');
  4162. // 构建道具名称列表
  4163. $prop_names = array_column($props, 'prop');
  4164. // 遍历传入的products
  4165. foreach ($products as $product) {
  4166. $product_name = getProp($product, 'product_name');
  4167. // 如果product_name不在roles、scenes和props中
  4168. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4169. // 查找是否在extra_products中存在同名的
  4170. $found = false;
  4171. foreach ($extra_products as $key => $extra_product) {
  4172. if (getProp($extra_product, 'product_name') === $product_name) {
  4173. // 有同名的则覆盖
  4174. $extra_products[$key] = $product;
  4175. $found = true;
  4176. break;
  4177. }
  4178. }
  4179. // 没有则新增
  4180. if (!$found) {
  4181. $extra_products[] = $product;
  4182. }
  4183. }
  4184. }
  4185. if ($extra_products) {
  4186. // 保存到数据库
  4187. DB::table('mp_anime_episodes')
  4188. ->where('id', $episode_id)
  4189. ->update([
  4190. 'extra_products' => json_encode($extra_products, 256),
  4191. 'updated_at' => date('Y-m-d H:i:s')
  4192. ]);
  4193. }
  4194. }
  4195. // 获取分镜内容
  4196. $actContent = getProp($act, 'act_show_content', '');
  4197. // 音效同出(默认使用)
  4198. $current_generate_audio = $generate_audio ? 1 : 0;
  4199. // 构建完整的提示词
  4200. $processResult = $this->processActContentWithProducts($actContent, $products);
  4201. $fullPrompt = $processResult['content'];
  4202. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4203. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4204. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4205. // 处理视频模型
  4206. $model = getProp($data, 'model');
  4207. if (!$model) {
  4208. $model = getProp($episode, 'video_model');
  4209. if (!$model) {
  4210. // episode表也没有,使用默认值
  4211. $model = 'zhizhen-20';
  4212. }
  4213. }
  4214. // 验证模型是否在可用模型表中
  4215. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4216. $model = 'zhizhen-20';
  4217. }
  4218. // 保存到episode表
  4219. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4220. 'video_model' => $model,
  4221. 'updated_at' => date('Y-m-d H:i:s')
  4222. ]);
  4223. // 构建视频生成参数
  4224. $videoParams = [
  4225. 'model' => $model,
  4226. 'alias_act_id' => $act_id,
  4227. 'prompt' => trim($fullPrompt),
  4228. 'video_duration' => $videoDuration,
  4229. 'video_resolution' => $video_resolution,
  4230. 'seed' => -1,
  4231. 'ratio' => $ratio,
  4232. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4233. 'draft' => false,
  4234. 'watermark' => false,
  4235. 'camera_fixed' => false,
  4236. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4237. ];
  4238. // 如果分镜有图片,作为首帧
  4239. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4240. $hasVideo = !empty(getProp($act, 'video_url'));
  4241. if ($hasImage) {
  4242. if ($first_frame_url) {
  4243. $videoParams['first_frame_url'] = $first_frame_url;
  4244. }else {
  4245. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4246. }
  4247. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4248. }
  4249. // 构建content数组
  4250. $videoParams['content'] = [
  4251. [
  4252. 'type' => 'text',
  4253. 'text' => $videoParams['prompt'],
  4254. ]
  4255. ];
  4256. // 如果有首帧图片,添加到content中
  4257. if ($hasImage) {
  4258. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0'])) {
  4259. $videoParams['content'][] = [
  4260. 'type' => 'image_url',
  4261. 'image_url' => [
  4262. 'url' => $videoParams['first_frame_url'],
  4263. ],
  4264. 'role' => 'reference_image',
  4265. ];
  4266. if (isset($videoParams['tail_frame_url'])) {
  4267. $videoParams['content'][] = [
  4268. 'type' => 'image_url',
  4269. 'image_url' => [
  4270. 'url' => $videoParams['tail_frame_url'],
  4271. ],
  4272. 'role' => 'reference_image',
  4273. ];
  4274. }
  4275. }else {
  4276. $videoParams['content'][] = [
  4277. 'type' => 'image_url',
  4278. 'image_url' => [
  4279. 'url' => $videoParams['first_frame_url'],
  4280. ],
  4281. 'role' => 'first_frame',
  4282. ];
  4283. if (isset($videoParams['tail_frame_url'])) {
  4284. $videoParams['content'][] = [
  4285. 'type' => 'image_url',
  4286. 'image_url' => [
  4287. 'url' => $videoParams['tail_frame_url'],
  4288. ],
  4289. 'role' => 'last_frame',
  4290. ];
  4291. }
  4292. }
  4293. }
  4294. // dd($videoParams);
  4295. // 根据模型选择不同的视频生成方法
  4296. if (strpos($model, 'jimeng') !== false) {
  4297. // 即梦模型参数调整
  4298. unset($videoParams['content']); // 即梦不使用content格式
  4299. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4300. } elseif (strpos($model, 'kling') !== false) {
  4301. // Keling模型参数调整
  4302. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4303. unset($videoParams['ratio']);
  4304. unset($videoParams['content']); // Keling不使用content格式
  4305. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4306. } elseif (strpos($model, 'zhizhen') !== false) {
  4307. // 智帧20等新模型使用统一API
  4308. // 构建统一API参数
  4309. $unifiedParams = [
  4310. 'model_code' => $model,
  4311. 'alias_act_id' => $act_id,
  4312. 'prompt' => trim($fullPrompt),
  4313. 'video_duration' => $videoDuration,
  4314. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4315. 'video_ratio' => $ratio,
  4316. 'seed' => -1,
  4317. ];
  4318. // 构建parameters参数
  4319. $parameters = [
  4320. 'seconds' => $unifiedParams['video_duration'],
  4321. 'resolution' => $unifiedParams['video_resolution'],
  4322. 'ratio' => $ratio,
  4323. // 'video_mode' => 'multi_image',
  4324. // 'mode' => 'multi_image',
  4325. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4326. ];
  4327. $hasImage = false;
  4328. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4329. if ($hasImage) {
  4330. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4331. if (isset($videoParams['tail_frame_url'])) {
  4332. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4333. }
  4334. } else {
  4335. // 没有图片时,记录错误日志
  4336. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4337. 'act_id' => $act_id,
  4338. 'model' => $model
  4339. ]);
  4340. }
  4341. if ($reference_images) {
  4342. // 限制只传入9张参考图
  4343. $reference_images = array_slice($reference_images, 0, 9);
  4344. // 在处理之前先保存原始reference_images到任务参数中
  4345. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4346. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4347. $parameters['reference_images'] = $reference_images;
  4348. $parameters['video_mode'] = 'multi_image';
  4349. $parameters['mode'] = 'multi_image';
  4350. }
  4351. $unifiedParams['parameters'] = $parameters;
  4352. // 调用统一API创建任务
  4353. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4354. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4355. // 豆包Seedance 2.0(百度AI网关):图片需要先上传为素材
  4356. // 保存原始参考图用于任务记录
  4357. $videoParams['reference_images'] = $reference_images;
  4358. if ($reference_images) {
  4359. // 限制只传入9张参考图
  4360. $reference_images = array_slice($reference_images, 0, 9);
  4361. // 参考图上传为百度网关素材,上传失败时同步清理提示词中的<图片N>标记
  4362. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt);
  4363. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4364. $videoParams['prompt'] = trim($fullPrompt);
  4365. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4366. $videoParams['reference_image_assets'] = $reference_image_assets;
  4367. }
  4368. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4369. } else {
  4370. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4371. }
  4372. // 更新分镜表的视频任务信息
  4373. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4374. 'video_task_id' => $task->id,
  4375. 'video_task_status' => '生成中',
  4376. 'generate_audio' => $generate_audio,
  4377. 'updated_at' => date('Y-m-d H:i:s')
  4378. ]);
  4379. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4380. $episode_number = getProp($act, 'episode_number');
  4381. $act_number = getProp($act, 'act_number');
  4382. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4383. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4384. }
  4385. return [
  4386. 'task_id' => $task->id,
  4387. 'status' => $task->status,
  4388. 'act_id' => $act_id,
  4389. 'video_duration' => $videoDuration
  4390. ];
  4391. }
  4392. /**
  4393. * 文生视频通用方法
  4394. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4395. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4396. *
  4397. * @param array $data 请求参数
  4398. * @return array
  4399. */
  4400. public function generateVideo($data) {
  4401. $prompt = getProp($data, 'prompt');
  4402. if (empty($prompt)) {
  4403. Utils::throwError('20003:提示词不能为空');
  4404. }
  4405. $model = getProp($data, 'model');
  4406. if (!$model) {
  4407. $model = 'zhizhen-20';
  4408. }
  4409. // 验证模型是否在可用模型表中
  4410. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4411. Utils::throwError('20003:该模型已不可用,请更换!');
  4412. }
  4413. $video_duration = getProp($data, 'video_duration', 5);
  4414. $video_resolution = getProp($data, 'video_resolution', '480p');
  4415. $ratio = getProp($data, 'ratio', '9:16');
  4416. $generate_audio = getProp($data, 'generate_audio', 1);
  4417. $seed = getProp($data, 'seed', -1);
  4418. $first_frame_url = getProp($data, 'first_frame_url');
  4419. $tail_frame_url = getProp($data, 'tail_frame_url');
  4420. // 参考图(支持数组或JSON字符串,最多9张)
  4421. $reference_images = getProp($data, 'reference_images', []);
  4422. if (is_string($reference_images)) {
  4423. $reference_images = json_decode($reference_images, true) ?: [];
  4424. }
  4425. if (!is_array($reference_images)) {
  4426. Utils::throwError('20003:参考图格式不正确');
  4427. }
  4428. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4429. $reference_images = array_slice($reference_images, 0, 9);
  4430. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4431. $videoParams = [
  4432. 'model' => $model,
  4433. 'prompt' => $prompt,
  4434. 'video_duration' => $video_duration,
  4435. 'video_resolution' => $video_resolution,
  4436. 'seed' => $seed,
  4437. 'ratio' => $ratio,
  4438. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4439. 'draft' => getProp($data, 'draft', false),
  4440. 'watermark' => getProp($data, 'watermark', false),
  4441. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4442. ];
  4443. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4444. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4445. // 构建content数组
  4446. $videoParams['content'] = [
  4447. [
  4448. 'type' => 'text',
  4449. 'text' => $prompt,
  4450. ]
  4451. ];
  4452. // 根据模型选择不同的视频生成方法
  4453. if (strpos($model, 'jimeng') !== false) {
  4454. // 即梦模型参数调整
  4455. unset($videoParams['content']); // 即梦不使用content格式
  4456. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4457. } elseif (strpos($model, 'kling') !== false) {
  4458. // 可灵模型参数调整
  4459. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4460. unset($videoParams['ratio']);
  4461. unset($videoParams['content']); // 可灵不使用content格式
  4462. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4463. } elseif (strpos($model, 'zhizhen') !== false) {
  4464. // 智帧等新模型使用统一API
  4465. $unifiedParams = [
  4466. 'model_code' => $model,
  4467. 'prompt' => $prompt,
  4468. 'video_duration' => $video_duration,
  4469. 'video_resolution' => strtolower($video_resolution),
  4470. 'video_ratio' => $ratio,
  4471. 'seed' => $seed,
  4472. ];
  4473. // 构建parameters参数
  4474. $parameters = [
  4475. 'seconds' => $unifiedParams['video_duration'],
  4476. 'resolution' => $unifiedParams['video_resolution'],
  4477. 'ratio' => $ratio,
  4478. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4479. ];
  4480. // 首帧和尾帧
  4481. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4482. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4483. // 参考图处理
  4484. if ($reference_images) {
  4485. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4486. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4487. $parameters['reference_images'] = $reference_images;
  4488. $parameters['video_mode'] = 'multi_image';
  4489. $parameters['mode'] = 'multi_image';
  4490. }
  4491. $unifiedParams['parameters'] = $parameters;
  4492. // 调用统一API创建任务
  4493. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4494. } elseif (strpos($model, 'doubao-seedance-2.0') !== false) {
  4495. // 豆包Seedance 2.0(百度AI网关):图片需要先上传为素材
  4496. $videoParams['reference_images'] = $reference_images;
  4497. if ($reference_images) {
  4498. // 参考图上传为百度网关素材
  4499. $reference_image_assets = $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']);
  4500. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4501. $videoParams['reference_image_assets'] = $reference_image_assets;
  4502. }
  4503. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4504. } else {
  4505. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4506. }
  4507. return [
  4508. 'task_id' => $task->id,
  4509. 'status' => $task->status,
  4510. 'model' => $model,
  4511. 'video_duration' => $video_duration,
  4512. 'video_resolution' => $video_resolution,
  4513. 'ratio' => $ratio
  4514. ];
  4515. }
  4516. /**
  4517. * 根据提示词内容智能计算最优视频时长
  4518. *
  4519. * @param string $segmentContent 分镜内容
  4520. * @param string $tailFrame 尾帧描述
  4521. * @return int 视频时长(2-12秒)
  4522. */
  4523. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4524. // 合并所有文本内容
  4525. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4526. // 如果没有内容,返回默认时长
  4527. if (empty($fullText)) {
  4528. return 5;
  4529. }
  4530. // 计算文本长度(中文字符按2个字符计算)
  4531. $textLength = mb_strlen($fullText, 'UTF-8');
  4532. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4533. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4534. // 分析内容复杂度
  4535. $complexityScore = $this->analyzeContentComplexity($fullText);
  4536. // 基础时长计算(根据文本长度)
  4537. $baseDuration = 3; // 默认2秒
  4538. // if ($adjustedLength <= 20) {
  4539. // $baseDuration = 3;
  4540. // } elseif ($adjustedLength <= 40) {
  4541. // $baseDuration = 4;
  4542. // } elseif ($adjustedLength <= 60) {
  4543. // $baseDuration = 5;
  4544. // } elseif ($adjustedLength <= 80) {
  4545. // $baseDuration = 6;
  4546. // } elseif ($adjustedLength <= 100) {
  4547. // $baseDuration = 7;
  4548. // } elseif ($adjustedLength <= 120) {
  4549. // $baseDuration = 8;
  4550. // } else {
  4551. // $baseDuration = 9;
  4552. // }
  4553. // 根据内容复杂度调整时长
  4554. $finalDuration = $baseDuration + $complexityScore;
  4555. // 确保时长在2-12秒范围内
  4556. return max(4, min(12, $finalDuration));
  4557. }
  4558. /**
  4559. * 分析内容复杂度,返回时长调整值
  4560. *
  4561. * @param string $text 文本内容
  4562. * @return int 调整值(-2到+3)
  4563. */
  4564. private function analyzeContentComplexity($text) {
  4565. $score = 0;
  4566. // 动作关键词(需要更长时间展现)
  4567. $actionKeywords = [
  4568. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4569. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4570. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4571. ];
  4572. // 静态关键词(可以用较短时间)
  4573. $staticKeywords = [
  4574. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4575. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4576. ];
  4577. // 复杂场景关键词(需要更长时间)
  4578. $complexSceneKeywords = [
  4579. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4580. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4581. ];
  4582. // 情感关键词(需要适中时间表现)
  4583. $emotionKeywords = [
  4584. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4585. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4586. ];
  4587. // 检查动作关键词
  4588. foreach ($actionKeywords as $keyword) {
  4589. if (strpos($text, $keyword) !== false) {
  4590. $score += 1;
  4591. break; // 避免重复加分
  4592. }
  4593. }
  4594. // 检查静态关键词
  4595. foreach ($staticKeywords as $keyword) {
  4596. if (strpos($text, $keyword) !== false) {
  4597. $score -= 1;
  4598. break;
  4599. }
  4600. }
  4601. // 检查复杂场景关键词
  4602. foreach ($complexSceneKeywords as $keyword) {
  4603. if (strpos($text, $keyword) !== false) {
  4604. $score += 1;
  4605. break;
  4606. }
  4607. }
  4608. // 检查情感关键词
  4609. foreach ($emotionKeywords as $keyword) {
  4610. if (strpos($text, $keyword) !== false) {
  4611. $score += 1;
  4612. break;
  4613. }
  4614. }
  4615. // 检查时间相关词汇
  4616. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4617. $score += 1;
  4618. }
  4619. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4620. $score -= 1;
  4621. }
  4622. // 检查转场词汇
  4623. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4624. $score += 1;
  4625. }
  4626. // 检查环境描述(复杂环境需要更多时间)
  4627. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4628. $score += 1;
  4629. }
  4630. // 检查对话内容(对话需要更多时间)
  4631. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4632. $score += 1;
  4633. }
  4634. // 限制调整范围
  4635. return max(-1, min(4, $score));
  4636. }
  4637. /**
  4638. * 创建完整视频合成任务
  4639. *
  4640. * @param array $data
  4641. * @return array
  4642. */
  4643. public function createCompleteVideoTask($data)
  4644. {
  4645. $animeId = getProp($data, 'anime_id');
  4646. $episodeId = getProp($data, 'episode_id');
  4647. // 验证参数
  4648. if (!$animeId || !$episodeId) {
  4649. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  4650. }
  4651. // 检查是否已存在处理中的任务
  4652. $existingTask = DB::table('mp_complete_video_tasks')
  4653. ->where('anime_id', $animeId)
  4654. ->where('episode_id', $episodeId)
  4655. ->whereIn('generate_status', ['执行中'])
  4656. ->first();
  4657. if ($existingTask) {
  4658. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  4659. }
  4660. // 获取全能模式状态
  4661. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  4662. if ((int)$ace_mode === 1) {
  4663. // 获取所有片段的配音视频,按 act_number 排序
  4664. $segments = DB::table('mp_episode_segments')
  4665. ->where('anime_id', $animeId)
  4666. ->where('episode_id', $episodeId)
  4667. ->orderBy('segment_number')
  4668. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4669. ->get();
  4670. // 检查是否所有片段都有视频
  4671. $missingVideos = $segments->filter(function($segment) {
  4672. return empty($segment->video_url);
  4673. });
  4674. if ($missingVideos->isNotEmpty()) {
  4675. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  4676. }
  4677. }else {
  4678. // 获取所有分镜的配音视频,按 segment_number 排序
  4679. $segments = DB::table('mp_episode_segments')
  4680. ->where('anime_id', $animeId)
  4681. ->where('episode_id', $episodeId)
  4682. ->orderBy('segment_number')
  4683. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  4684. ->get();
  4685. // 检查是否所有分镜都有配音和视频
  4686. $missingVideos = $segments->filter(function($segment) {
  4687. return empty($segment->audio_url) || empty($segment->video_url);
  4688. });
  4689. if ($missingVideos->isNotEmpty()) {
  4690. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  4691. }
  4692. }
  4693. if ($segments->isEmpty()) {
  4694. Utils::throwError('20003:未找到该剧集的分镜数据');
  4695. }
  4696. // 获取当前完整视频url
  4697. $completeVideoUrl = DB::table('mp_anime_episodes')
  4698. ->where('anime_id', $animeId)
  4699. ->where('id', $episodeId)
  4700. ->value('complete_video_url');
  4701. // 构建 generate_json
  4702. $generateJson = [];
  4703. $sequence = 1;
  4704. foreach ($segments as $segment) {
  4705. if ((int)$ace_mode === 1) {
  4706. $generateJson[] = [
  4707. 'sequence' => $sequence++,
  4708. 'video_url' => $segment->video_url,
  4709. 'video_time_point_start' => $segment->video_time_point_start,
  4710. 'video_time_point_end' => $segment->video_time_point_end
  4711. ];
  4712. }else {
  4713. $generateJson[] = [
  4714. 'sequence' => $sequence++,
  4715. 'video_url' => $segment->video_url,
  4716. 'audio_url' => $segment->audio_url,
  4717. 'video_time_point_start' => $segment->video_time_point_start,
  4718. 'video_time_point_end' => $segment->video_time_point_end
  4719. ];
  4720. }
  4721. }
  4722. // 创建任务
  4723. $now = date('Y-m-d H:i:s');
  4724. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  4725. 'anime_id' => $animeId,
  4726. 'episode_id' => $episodeId,
  4727. 'generate_json' => json_encode($generateJson, 256),
  4728. 'generate_status' => '执行中',
  4729. 'complete_video_url' => '',
  4730. 'created_at' => $now,
  4731. 'updated_at' => $now
  4732. ]);
  4733. if (!$taskId) {
  4734. Utils::throwError('20003:创建任务失败');
  4735. }
  4736. // 更新剧集表的任务ID和状态
  4737. $boolen = DB::table('mp_anime_episodes')
  4738. ->where('anime_id', $animeId)
  4739. ->where('id', $episodeId)
  4740. ->update([
  4741. 'complete_video_task_id' => $taskId,
  4742. 'complete_video_task_status' => '执行中',
  4743. 'updated_at' => $now
  4744. ]);
  4745. if (!$boolen) {
  4746. Utils::throwError('20003:更新剧集表失败');
  4747. }
  4748. dLog('anime')->info('创建完整视频合成任务', [
  4749. 'task_id' => $taskId,
  4750. 'anime_id' => $animeId,
  4751. 'episode_id' => $episodeId,
  4752. 'segment_count' => count($generateJson)
  4753. ]);
  4754. // 请求远程服务器执行生成
  4755. $client = new Client(['timeout' => 600, 'verify' => false]);
  4756. try {
  4757. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  4758. $response = $result->getBody()->getContents();
  4759. $response_arr = json_decode($response, true);
  4760. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4761. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4762. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  4763. // // 更新任务状态为失败
  4764. // DB::table('mp_complete_video_tasks')
  4765. // ->where('id', $taskId)
  4766. // ->update([
  4767. // 'generate_status' => '执行失败',
  4768. // 'error_message' => $error_msg,
  4769. // 'updated_at' => date('Y-m-d H:i:s')
  4770. // ]);
  4771. // // 同步更新剧集表状态
  4772. // DB::table('mp_anime_episodes')
  4773. // ->where('complete_video_task_id', $taskId)
  4774. // ->update([
  4775. // 'complete_video_task_status' => '执行失败',
  4776. // 'updated_at' => date('Y-m-d H:i:s')
  4777. // ]);
  4778. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  4779. }
  4780. } catch (\Exception $e) {
  4781. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  4782. // 更新任务状态为失败
  4783. DB::table('mp_complete_video_tasks')
  4784. ->where('id', $taskId)
  4785. ->update([
  4786. 'generate_status' => '执行失败',
  4787. 'error_message' => $e->getMessage(),
  4788. 'updated_at' => date('Y-m-d H:i:s')
  4789. ]);
  4790. // 同步更新剧集表状态
  4791. DB::table('mp_anime_episodes')
  4792. ->where('complete_video_task_id', $taskId)
  4793. ->update([
  4794. 'complete_video_task_status' => '执行失败',
  4795. 'updated_at' => date('Y-m-d H:i:s')
  4796. ]);
  4797. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  4798. }
  4799. // 开始轮询任务状态
  4800. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  4801. $pollInterval = 5; // 每5秒轮询一次
  4802. $attempt = 0;
  4803. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  4804. while ($attempt < $maxAttempts) {
  4805. sleep($pollInterval);
  4806. $attempt++;
  4807. // 查询任务状态
  4808. $task = DB::table('mp_complete_video_tasks')
  4809. ->where('id', $taskId)
  4810. ->first();
  4811. if (!$task) {
  4812. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  4813. Utils::throwError('20003:任务不存在');
  4814. }
  4815. dLog('anime')->info('轮询任务状态', [
  4816. 'task_id' => $taskId,
  4817. 'attempt' => $attempt,
  4818. 'status' => $task->generate_status
  4819. ]);
  4820. // 检查任务是否完成
  4821. if ($task->generate_status === '执行成功') {
  4822. // 同步更新剧集表状态
  4823. $boolen3 = DB::table('mp_anime_episodes')
  4824. ->where('anime_id', $animeId)
  4825. ->where('id', $episodeId)
  4826. ->update([
  4827. 'complete_video_url' => $task->complete_video_url,
  4828. 'complete_video_task_status' => '执行成功',
  4829. 'updated_at' => date('Y-m-d H:i:s')
  4830. ]);
  4831. dLog('anime')->info('视频合成任务完成', [
  4832. 'task_id' => $taskId,
  4833. 'video_url' => $task->complete_video_url,
  4834. 'attempts' => $attempt
  4835. ]);
  4836. // 如果更新成功则远程删除之前的文件
  4837. if ($boolen3 && $completeVideoUrl) {
  4838. $encode_url = urlencode($completeVideoUrl);
  4839. $client = new Client(['timeout' => 300, 'verify' => false]);
  4840. // 根据ID通过API通知合成音频
  4841. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  4842. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  4843. $response = $result->getBody()->getContents();
  4844. $response_arr = json_decode($response, true);
  4845. Log::info('火山删除音频返回: '.$response);
  4846. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  4847. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4848. Log::info('火山删除音频失败: '.$error_msg);
  4849. // Utils::throwError('20003:火山删除音频失败');
  4850. }
  4851. }
  4852. return [
  4853. 'task_id' => $taskId,
  4854. 'anime_id' => $animeId,
  4855. 'episode_id' => $episodeId,
  4856. 'segment_count' => count($generateJson),
  4857. 'generate_status' => '执行成功',
  4858. 'complete_video_url' => $task->complete_video_url,
  4859. ];
  4860. }
  4861. // 检查任务是否失败
  4862. if ($task->generate_status === '执行失败') {
  4863. // 同步更新剧集表状态
  4864. DB::table('mp_anime_episodes')
  4865. ->where('anime_id', $animeId)
  4866. ->where('id', $episodeId)
  4867. ->update([
  4868. 'complete_video_task_status' => '执行失败',
  4869. 'updated_at' => date('Y-m-d H:i:s')
  4870. ]);
  4871. $errorMessage = $task->error_message ?? '未知错误';
  4872. dLog('anime')->error('视频合成任务失败', [
  4873. 'task_id' => $taskId,
  4874. 'error' => $errorMessage,
  4875. 'attempts' => $attempt
  4876. ]);
  4877. return [
  4878. 'task_id' => $taskId,
  4879. 'anime_id' => $animeId,
  4880. 'episode_id' => $episodeId,
  4881. 'segment_count' => count($generateJson),
  4882. 'generate_status' => '执行失败',
  4883. 'error_message' => $errorMessage
  4884. ];
  4885. }
  4886. }
  4887. // 超时处理
  4888. dLog('anime')->warning('视频合成任务超时', [
  4889. 'task_id' => $taskId,
  4890. 'max_attempts' => $maxAttempts,
  4891. 'timeout_seconds' => $maxAttempts * $pollInterval
  4892. ]);
  4893. // 更新任务状态为超时
  4894. DB::table('mp_complete_video_tasks')
  4895. ->where('id', $taskId)
  4896. ->update([
  4897. 'generate_status' => '超时',
  4898. 'error_message' => '任务执行超时(5分钟)',
  4899. 'updated_at' => date('Y-m-d H:i:s')
  4900. ]);
  4901. return [
  4902. 'task_id' => $taskId,
  4903. 'anime_id' => $animeId,
  4904. 'episode_id' => $episodeId,
  4905. 'segment_count' => count($generateJson),
  4906. 'generate_status' => '超时',
  4907. 'error_message' => '任务执行超时,请稍后查询任务状态'
  4908. ];
  4909. }
  4910. /**
  4911. * 根据 inner_prompt_type 附加内置提示词
  4912. *
  4913. * @param string $prompt 用户提示词
  4914. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  4915. * @return string 合并后的提示词
  4916. */
  4917. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  4918. {
  4919. $innerPromptMap = [
  4920. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  4921. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  4922. ];
  4923. if (!isset($innerPromptMap[$innerPromptType])) {
  4924. return $prompt;
  4925. }
  4926. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  4927. }
  4928. /**
  4929. * 根据 inner_prompt_type 获取生成图片数量
  4930. *
  4931. * @param int $innerPromptType 内置提示词类型
  4932. * @param int $imageNum 传入的图片张数
  4933. * @return int 图片数量
  4934. */
  4935. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  4936. {
  4937. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  4938. }
  4939. /**
  4940. * 提取图片生成结果URL
  4941. *
  4942. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  4943. * @param int $innerPromptType 内置提示词类型
  4944. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  4945. */
  4946. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  4947. {
  4948. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  4949. if (is_array($resultUrls) && !empty($resultUrls)) {
  4950. $resultUrls = array_values($resultUrls);
  4951. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  4952. }
  4953. if (!empty($resultUrl)) {
  4954. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  4955. }
  4956. return (int)$innerPromptType === 2 ? [] : '';
  4957. }
  4958. public function generateImg($data) {
  4959. $prompt = getProp($data, 'prompt');
  4960. $episode_id = getProp($data, 'episode_id');
  4961. $ref_img_urls = getProp($data, 'ref_img_urls');
  4962. $ratio = getProp($data, 'ratio', '9:16');
  4963. $resolution = getProp($data, 'resolution', '2k');
  4964. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  4965. $imageNum = (int)getProp($data, 'image_num', 1);
  4966. // 定义分辨率和宽高比对应的尺寸映射表
  4967. $sizeMap = [
  4968. '2k' => [
  4969. '1:1' => ['width' => 2048, 'height' => 2048],
  4970. '4:3' => ['width' => 2304, 'height' => 1728],
  4971. '3:4' => ['width' => 1728, 'height' => 2304],
  4972. '16:9' => ['width' => 2848, 'height' => 1600],
  4973. '9:16' => ['width' => 1600, 'height' => 2848],
  4974. '3:2' => ['width' => 2496, 'height' => 1664],
  4975. '2:3' => ['width' => 1664, 'height' => 2496],
  4976. '21:9' => ['width' => 3136, 'height' => 1344],
  4977. ],
  4978. '3k' => [
  4979. '1:1' => ['width' => 3072, 'height' => 3072],
  4980. '4:3' => ['width' => 3456, 'height' => 2592],
  4981. '3:4' => ['width' => 2592, 'height' => 3456],
  4982. '16:9' => ['width' => 4096, 'height' => 2304],
  4983. '9:16' => ['width' => 2304, 'height' => 4096],
  4984. '2:3' => ['width' => 2496, 'height' => 3744],
  4985. '3:2' => ['width' => 3744, 'height' => 2496],
  4986. '21:9' => ['width' => 4704, 'height' => 2016],
  4987. ],
  4988. '4k' => [
  4989. '1:1' => ['width' => 4096, 'height' => 4096],
  4990. '3:4' => ['width' => 3520, 'height' => 4704],
  4991. '4:3' => ['width' => 4704, 'height' => 3520],
  4992. '16:9' => ['width' => 5504, 'height' => 3040],
  4993. '9:16' => ['width' => 3040, 'height' => 5504],
  4994. '2:3' => ['width' => 3328, 'height' => 4992],
  4995. '3:2' => ['width' => 4992, 'height' => 3328],
  4996. '21:9' => ['width' => 6240, 'height' => 2656],
  4997. ],
  4998. ];
  4999. // 参数验证
  5000. $resolution = strtolower($resolution);
  5001. if (!isset($sizeMap[$resolution])) {
  5002. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5003. }
  5004. if (!isset($sizeMap[$resolution][$ratio])) {
  5005. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5006. }
  5007. // 根据 ratio 和 resolution 确定宽高
  5008. $width = $sizeMap[$resolution][$ratio]['width'];
  5009. $height = $sizeMap[$resolution][$ratio]['height'];
  5010. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5011. if (is_json($ref_img_urls)) {
  5012. $ref_img_urls = json_decode($ref_img_urls, true);
  5013. }else {
  5014. $ref_img_urls = explode(',', $ref_img_urls);
  5015. }
  5016. }
  5017. // 处理图片模型
  5018. $model = getProp($data, 'model');
  5019. if (!$model) {
  5020. // 用户没有输入,从episode表获取
  5021. if ($episode_id) {
  5022. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5023. $model = getProp($episode, 'image_model');
  5024. }
  5025. if (!$model) {
  5026. // episode表也没有,使用默认值
  5027. $model = 'doubao-seedream-5-0-lite-260128';
  5028. }
  5029. }
  5030. // 验证模型是否在可用模型表中
  5031. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5032. // $model = 'doubao-seedream-5-0-lite-260128';
  5033. Utils::throwError('20003:该模型已不可用,请更换!');
  5034. }
  5035. // 保存到episode表
  5036. if ($episode_id) {
  5037. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5038. 'image_model' => $model,
  5039. 'updated_at' => date('Y-m-d H:i:s')
  5040. ]);
  5041. }
  5042. // 参数验证
  5043. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5044. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5045. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5046. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5047. try {
  5048. // 创建图片生成任务
  5049. $params = [
  5050. 'prompt' => $prompt,
  5051. 'model' => $model,
  5052. 'ref_img_urls' => '',
  5053. 'width' => $width,
  5054. 'height' => $height,
  5055. 'image_num' => $imageNum
  5056. ];
  5057. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5058. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5059. $task_id = $task->id;
  5060. if (!$task_id) {
  5061. Utils::throwError('20003:创建图片生成任务失败');
  5062. }
  5063. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5064. $model = getProp($task, 'model');
  5065. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5066. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5067. $isSyncModel = $isVolcModel || $isGptModel;
  5068. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5069. $start_time = time();
  5070. $timeout = 300; // 5分钟
  5071. $img_url = '';
  5072. $img_urls = [];
  5073. while (time() - $start_time < $timeout) {
  5074. sleep(3);
  5075. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5076. if ($isSyncModel) {
  5077. // 刷新任务状态
  5078. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5079. if ($task->status === 'success' && $task->result_url) {
  5080. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5081. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5082. if (!empty($resultUrls)) {
  5083. $img_urls = $resultUrls;
  5084. $img_url = $resultUrls[0];
  5085. } else {
  5086. $img_url = (string)$task->result_url;
  5087. }
  5088. break;
  5089. } elseif ($task->status === 'failed') {
  5090. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5091. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5092. }
  5093. // // 如果还在处理中,提示用户稍后查看
  5094. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5095. }else {
  5096. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5097. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5098. if ($statusInfo['status'] === 'success') {
  5099. $task->updateStatus('success', [
  5100. 'result_url' => $statusInfo['result_url'],
  5101. 'result_json' => $statusInfo['result_json'] ?? []
  5102. ]);
  5103. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5104. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5105. if (!empty($resultUrls)) {
  5106. $img_urls = $resultUrls;
  5107. $img_url = $resultUrls[0];
  5108. } else {
  5109. $img_url = (string)$statusInfo['result_url'];
  5110. }
  5111. break;
  5112. } elseif ($statusInfo['status'] === 'failed') {
  5113. $task->updateStatus('failed', [
  5114. 'error_message' => $statusInfo['error_message'],
  5115. 'result_json' => $statusInfo['result_json'] ?? []
  5116. ]);
  5117. dLog('anime')->error('图片生成失败,', [
  5118. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5119. ]);
  5120. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5121. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5122. }
  5123. }
  5124. }
  5125. if (empty($img_url)) {
  5126. Utils::throwError('20003:图片生成超时,请稍后重试');
  5127. }
  5128. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5129. if (count($img_urls) > 1) {
  5130. return [
  5131. 'img_url' => $img_url,
  5132. 'image_urls' => $img_urls
  5133. ];
  5134. }
  5135. return $img_url;
  5136. } catch (\Exception $e) {
  5137. dLog('anime')->error('更新角色或场景失败', [
  5138. 'error' => $e->getMessage()
  5139. ]);
  5140. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5141. Utils::throwError('20003:' . $e->getMessage());
  5142. }
  5143. }
  5144. /**
  5145. * 使用文生文模型解析分镜内容
  5146. */
  5147. private function parseSegmentContentWithAI($segment_content) {
  5148. try {
  5149. // 使用DeepSeek服务的公开方法解析分镜内容
  5150. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5151. } catch (\Exception $e) {
  5152. // 如果AI解析失败,记录日志并返回原内容
  5153. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5154. return $segment_content;
  5155. }
  5156. }
  5157. /**
  5158. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5159. *
  5160. * @param int $episode_id 分集ID
  5161. * @param int $anime_id 动漫ID
  5162. * @param array $roles 分集角色数组(引用传递)
  5163. * @param array $scenes 分集场景数组(引用传递)
  5164. * @param array $episode 分集数据
  5165. */
  5166. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5167. // 获取全局动漫的角色和场景数据
  5168. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5169. if (!$anime) return;
  5170. $art_style_type = getProp($anime, 'art_style_type');
  5171. $character_prefix = '';
  5172. $scene_prefix = '';
  5173. if ($art_style_type) {
  5174. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5175. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5176. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5177. }
  5178. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5179. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5180. $roles_updated = false;
  5181. $scenes_updated = false;
  5182. // 处理角色
  5183. foreach ($roles as &$role) {
  5184. $role_name = getProp($role, 'role');
  5185. $role_description = getProp($role, 'description');
  5186. $role_pic_prompt = getProp($role, 'pic_prompt');
  5187. $role_url = getProp($role, 'url');
  5188. $role_task_id = getProp($role, 'task_id');
  5189. // 如果已有URL或已有任务ID,跳过
  5190. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5191. continue;
  5192. }
  5193. $url_inherited = false;
  5194. // 尝试从全局数据中继承
  5195. foreach ($global_roles as $global_role) {
  5196. $global_role_name = getProp($global_role, 'role');
  5197. $global_role_description = getProp($global_role, 'description');
  5198. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5199. $global_role_url = getProp($global_role, 'url');
  5200. $global_role_task_id = getProp($global_role, 'task_id');
  5201. $global_role_task_status = getProp($global_role, 'task_status');
  5202. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5203. if ($role_name === $global_role_name
  5204. && $role_description === $global_role_description
  5205. && $role_pic_prompt === $global_role_pic_prompt
  5206. && !empty($global_role_url)) {
  5207. // 继承 task_id、task_status 和 url
  5208. $role['task_id'] = $global_role_task_id;
  5209. $role['task_status'] = $global_role_task_status;
  5210. $role['url'] = $global_role_url;
  5211. $roles_updated = true;
  5212. $url_inherited = true;
  5213. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5214. break;
  5215. }
  5216. }
  5217. // 如果无法继承且没有任务ID,创建新任务
  5218. if (!$url_inherited && empty($role_task_id)) {
  5219. try {
  5220. $art_style = getProp($episode, 'art_style');
  5221. // 优先使用 pic_prompt,如果没有则使用 description
  5222. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5223. // if ($art_style) {
  5224. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5225. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5226. // }
  5227. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5228. $params = [
  5229. 'prompt' => $description,
  5230. 'ref_img_urls' => []
  5231. ];
  5232. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5233. $task_id = $task->id;
  5234. if ($task_id) {
  5235. $role['task_id'] = $task_id;
  5236. $role['task_status'] = 'processing';
  5237. $roles_updated = true;
  5238. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5239. }
  5240. } catch (\Exception $e) {
  5241. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5242. }
  5243. }
  5244. }
  5245. // 处理场景
  5246. foreach ($scenes as &$scene) {
  5247. $scene_name = getProp($scene, 'scene');
  5248. $scene_description = getProp($scene, 'description');
  5249. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5250. $scene_url = getProp($scene, 'url');
  5251. $scene_task_id = getProp($scene, 'task_id');
  5252. // 如果已有URL或已有任务ID,跳过
  5253. if (!empty($scene_url) || !empty($scene_task_id)) {
  5254. continue;
  5255. }
  5256. $url_inherited = false;
  5257. // 尝试从全局数据中继承
  5258. foreach ($global_scenes as $global_scene) {
  5259. $global_scene_name = getProp($global_scene, 'scene');
  5260. $global_scene_description = getProp($global_scene, 'description');
  5261. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5262. $global_scene_url = getProp($global_scene, 'url');
  5263. $global_scene_task_id = getProp($global_scene, 'task_id');
  5264. $global_scene_task_status = getProp($global_scene, 'task_status');
  5265. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5266. if ($scene_name === $global_scene_name
  5267. && $scene_description === $global_scene_description
  5268. && $scene_pic_prompt === $global_scene_pic_prompt
  5269. && !empty($global_scene_url)) {
  5270. // 继承 task_id、task_status 和 url
  5271. $scene['task_id'] = $global_scene_task_id;
  5272. $scene['task_status'] = $global_scene_task_status;
  5273. $scene['url'] = $global_scene_url;
  5274. $scenes_updated = true;
  5275. $url_inherited = true;
  5276. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5277. break;
  5278. }
  5279. }
  5280. // 如果无法继承且没有任务ID,创建新任务
  5281. if (!$url_inherited && empty($scene_task_id)) {
  5282. try {
  5283. $art_style = getProp($episode, 'art_style');
  5284. // 优先使用 pic_prompt,如果没有则使用 description
  5285. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5286. // if ($art_style) {
  5287. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5288. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5289. // }
  5290. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5291. $params = [
  5292. 'prompt' => $description,
  5293. 'ref_img_urls' => []
  5294. ];
  5295. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5296. $task_id = $task->id;
  5297. if ($task_id) {
  5298. $scene['task_id'] = $task_id;
  5299. $scene['task_status'] = 'processing';
  5300. $scenes_updated = true;
  5301. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5302. }
  5303. } catch (\Exception $e) {
  5304. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5305. }
  5306. }
  5307. }
  5308. // 如果有更新,保存到数据库
  5309. if ($roles_updated || $scenes_updated) {
  5310. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5311. if ($roles_updated) {
  5312. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5313. }
  5314. if ($scenes_updated) {
  5315. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5316. }
  5317. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5318. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5319. }
  5320. }
  5321. /**
  5322. * 根据图片URL使用AI反推图片提示词
  5323. *
  5324. * @param string $img_url 图片URL
  5325. * @return string 反推的提示词
  5326. */
  5327. private function generateImagePromptFromUrl($img_url) {
  5328. try {
  5329. // 获取默认模型
  5330. $model = 'doubao-seed-2-0-mini-260215';
  5331. // 构建messages参数
  5332. $messages = [
  5333. [
  5334. 'role' => 'user',
  5335. 'content' => [
  5336. [
  5337. 'type' => 'text',
  5338. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5339. ],
  5340. [
  5341. 'type' => 'image_url',
  5342. 'image_url' => [
  5343. 'url' => $img_url
  5344. ]
  5345. ]
  5346. ]
  5347. ]
  5348. ];
  5349. // 构建请求参数
  5350. $params = [
  5351. 'model' => $model,
  5352. 'messages' => $messages,
  5353. 'stream' => false,
  5354. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5355. ];
  5356. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5357. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5358. // 返回生成的内容
  5359. return getProp($result, 'fullContent', '图片描述生成失败');
  5360. } catch (\Exception $e) {
  5361. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5362. 'img_url' => $img_url
  5363. ]);
  5364. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5365. 'error' => $e->getMessage(),
  5366. 'img_url' => $img_url
  5367. ]);
  5368. return '图片描述生成失败: ' . $e->getMessage();
  5369. }
  5370. }
  5371. /**
  5372. * 音频试听接口
  5373. * 创建音频任务并轮询获取结果
  5374. *
  5375. * @param array $data 参数数组
  5376. * @return array 返回音频URL或错误信息
  5377. */
  5378. public function previewAudio($data) {
  5379. $dialogue = getProp($data, 'dialogue');
  5380. // 必填参数验证
  5381. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5382. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5383. $voice_type = getProp($data, 'voice_type');
  5384. $voice_name = getProp($data, 'voice_name');
  5385. $voice_actor = getProp($data, 'voice_actor');
  5386. $emotion_type = getProp($data, 'emotion_type');
  5387. $gender = getProp($data, 'gender', 0);
  5388. $emotion = getProp($data, 'emotion');
  5389. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5390. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5391. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5392. $pitch = getProp($data, 'pitch', 0);
  5393. try {
  5394. $now = date('Y-m-d H:i:s');
  5395. // 构建生成参数
  5396. $generate_json = json_encode([
  5397. 'text' => $dialogue,
  5398. 'role' => $voice_actor,
  5399. 'voice_type' => $voice_type,
  5400. 'voice_name' => $voice_name,
  5401. 'emotion' => $emotion,
  5402. 'emotion_type' => $emotion_type,
  5403. 'gender' => $gender,
  5404. 'speed_ratio' => $speed_ratio,
  5405. 'loudness_ratio' => $loudness_ratio,
  5406. 'emotion_scale' => $emotion_scale,
  5407. 'pitch' => $pitch,
  5408. ], 256);
  5409. // 请求远程服务器执行生成
  5410. $client = new Client(['timeout' => 600, 'verify' => false]);
  5411. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5412. $response = $result->getBody()->getContents();
  5413. $response_arr = json_decode($response, true);
  5414. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5415. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5416. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5417. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5418. }
  5419. $arr = $response_arr['data'];
  5420. $subtitle_info = $arr['subtitle_info'];
  5421. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5422. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5423. return [
  5424. 'audio_url' => $arr['url'],
  5425. 'subtitle_info' => $subtitle_info,
  5426. 'audio_duration' => round($audio_duration, 2)
  5427. ];
  5428. } catch (\Exception $e) {
  5429. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5430. Utils::throwError('20003:' . $e->getMessage());
  5431. }
  5432. }
  5433. /**
  5434. * 获取角色库列表(支持文件夹递归查询)
  5435. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5436. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5437. */
  5438. public function globalProducts($data) {
  5439. $uid = Site::getUid();
  5440. $cpid = Site::getCpid();
  5441. $role = Site::getRole();
  5442. $id = getProp($data, 'id', 0);
  5443. $parent_id = getProp($data, 'parent_id', 0);
  5444. $product_name = getProp($data, 'product_name');
  5445. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5446. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5447. if (!$product) {
  5448. Utils::throwError('20003:请选择产品类型');
  5449. }
  5450. // 根据角色和is_public参数确定查询范围
  5451. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5452. // user角色:根据is_public参数筛选
  5453. $query_user_ids = [];
  5454. if ($role === 'admin') {
  5455. // admin获取所有个人库和公共库
  5456. $query_user_ids = [$uid, 0];
  5457. } else {
  5458. // user角色根据is_public参数筛选
  5459. if ($is_public == 2) {
  5460. // 个人库+公共库
  5461. $query_user_ids = [$uid, 0];
  5462. } elseif ($is_public == 0) {
  5463. // 仅个人库
  5464. $query_user_ids = [$uid];
  5465. } elseif ($is_public == 1) {
  5466. // 仅公共库
  5467. $query_user_ids = [0];
  5468. }
  5469. }
  5470. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5471. if ($id || $product_name) {
  5472. $query = DB::table('mp_products')
  5473. ->where('cpid', $cpid)
  5474. ->whereIn('user_id', $query_user_ids)
  5475. ->where('is_deleted', 0);
  5476. // 如果指定了 id,按 id 精确查询
  5477. if ($id) {
  5478. $query->where('id', $id);
  5479. }
  5480. // 如果指定了 product_name,按名称模糊查询
  5481. if ($product_name) {
  5482. $query->where('product_name', 'like', "%{$product_name}%");
  5483. }
  5484. // 如果指定了 product,添加筛选条件
  5485. if ($product) {
  5486. $query->where('product', $product);
  5487. }
  5488. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5489. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5490. ->get()
  5491. ->map(function($value) {
  5492. $value = (array)$value;
  5493. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5494. $value['type'] = (int)$value['type'];
  5495. $value['parent_id'] = (int)$value['parent_id'];
  5496. $value['level'] = (int)$value['level'];
  5497. $value['product'] = (int)($value['product'] ?? 1);
  5498. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5499. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5500. unset($value['user_id']);
  5501. return $value;
  5502. })
  5503. ->toArray();
  5504. return $result;
  5505. }
  5506. // 递归获取所有子目录和角色
  5507. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5508. }
  5509. /**
  5510. * 递归获取指定目录下的所有子目录和角色
  5511. * @param int $cpid 公司ID
  5512. * @param int $parent_id 父目录ID
  5513. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5514. * @param array $query_user_ids 用户ID数组(支持多个)
  5515. * @param int $current_uid 当前用户ID(用于排序)
  5516. * @return array
  5517. */
  5518. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5519. // 查询当前层级的所有项(文件夹和角色)
  5520. $query = DB::table('mp_products')
  5521. ->where('cpid', $cpid)
  5522. ->where('is_deleted', 0)
  5523. ->where('parent_id', $parent_id);
  5524. // 添加用户ID验证(支持多个user_id)
  5525. if (!empty($query_user_ids)) {
  5526. $query->whereIn('user_id', $query_user_ids);
  5527. }
  5528. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5529. if ($product) {
  5530. $query->where('product', $product);
  5531. }
  5532. // 排序规则:
  5533. // 1. 文件夹在前(type DESC)
  5534. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5535. // 3. 其他排序规则
  5536. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5537. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5538. ->get();
  5539. $result = [];
  5540. foreach ($items as $item) {
  5541. $itemArray = [
  5542. 'id' => $item->id,
  5543. 'type' => (int)$item->type,
  5544. 'parent_id' => (int)$item->parent_id,
  5545. 'level' => (int)$item->level,
  5546. 'product_name' => $item->product_name,
  5547. 'url' => $item->url,
  5548. 'pic_prompt' => $item->pic_prompt ?? '',
  5549. 'three_view_image_url' => $item->three_view_image_url,
  5550. 'product' => (int)($item->product ?? 1),
  5551. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5552. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5553. ];
  5554. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5555. // 如果是文件夹,递归获取其子项
  5556. if ($item->type == 2) {
  5557. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5558. if (!empty($children)) {
  5559. $itemArray['children'] = $children;
  5560. }
  5561. }
  5562. $result[] = $itemArray;
  5563. }
  5564. return $result;
  5565. }
  5566. /**
  5567. * 创建文件夹
  5568. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5569. * @return int 返回新建文件夹ID
  5570. */
  5571. public function createFolder($data) {
  5572. $uid = Site::getUid();
  5573. $cpid = Site::getCpid();
  5574. $role = Site::getRole();
  5575. $parent_id = getProp($data, 'parent_id', 0);
  5576. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5577. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5578. // 如果是公共库操作,需要admin权限
  5579. if ($is_public && $role !== 'admin') {
  5580. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5581. }
  5582. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5583. $store_uid = $is_public ? 0 : $uid;
  5584. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5585. $product = getProp($data, 'product');
  5586. if (!in_array($product, [1, 2, 3])) {
  5587. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  5588. }
  5589. // 验证父文件夹
  5590. $parent_level = 0;
  5591. if ($parent_id > 0) {
  5592. $parent = DB::table('mp_products')
  5593. ->where('id', $parent_id)
  5594. ->where('cpid', $cpid)
  5595. ->where('user_id', $store_uid)
  5596. ->where('type', 2)
  5597. ->where('is_deleted', 0)
  5598. ->first();
  5599. if (!$parent) {
  5600. Utils::throwError('20003:父文件夹不存在');
  5601. }
  5602. // 检查父文件夹的 product 类型是否一致
  5603. if ($parent->product != $product) {
  5604. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  5605. }
  5606. $parent_level = $parent->level;
  5607. // 检查层级限制(最多3层)
  5608. if ($parent_level >= 3) {
  5609. Utils::throwError('20003:文件夹层级不能超过3层');
  5610. }
  5611. }
  5612. // 检查当前目录下是否已存在空白文件夹
  5613. $empty_folder_exists = DB::table('mp_products')
  5614. ->where('parent_id', $parent_id)
  5615. ->where('cpid', $cpid)
  5616. ->where('user_id', $store_uid)
  5617. ->where('type', 2)
  5618. ->where('product', $product)
  5619. ->where('product_name', '新建文件夹')
  5620. ->where('is_deleted', 0)
  5621. ->exists();
  5622. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  5623. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  5624. }
  5625. // 创建文件夹
  5626. $folder_id = DB::table('mp_products')->insertGetId([
  5627. 'user_id' => $store_uid,
  5628. 'cpid' => $cpid,
  5629. 'type' => 2,
  5630. 'parent_id' => $parent_id,
  5631. 'level' => $parent_level + 1,
  5632. 'product_name' => $folder_name,
  5633. 'product' => $product,
  5634. 'sort_order' => time(), // 使用时间戳作为排序权重
  5635. 'is_deleted' => 0,
  5636. 'created_at' => date('Y-m-d H:i:s'),
  5637. 'updated_at' => date('Y-m-d H:i:s')
  5638. ]);
  5639. return [
  5640. 'id' => $folder_id,
  5641. 'type' => 2,
  5642. 'parent_id' => $parent_id,
  5643. 'level' => $parent_level + 1,
  5644. 'product_name' => $folder_name,
  5645. 'product' => $product,
  5646. ];
  5647. }
  5648. /**
  5649. * 重命名文件夹或角色
  5650. * @param array $data 包含 id、product_name(新名称)
  5651. * @return bool
  5652. */
  5653. public function renameFolder($data) {
  5654. $uid = Site::getUid();
  5655. $cpid = Site::getCpid();
  5656. $role = Site::getRole();
  5657. $id = getProp($data, 'id');
  5658. $new_name = getProp($data, 'product_name');
  5659. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5660. if (!$id || !$new_name) {
  5661. Utils::throwError('20003:参数不完整');
  5662. }
  5663. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5664. $query_uid = $is_public ? 0 : $uid;
  5665. // 如果是公共库操作,需要admin权限
  5666. if ($is_public && $role !== 'admin') {
  5667. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5668. }
  5669. // 检查是否存在
  5670. $item = DB::table('mp_products')
  5671. ->where('id', $id)
  5672. ->where('cpid', $cpid)
  5673. ->where('user_id', $query_uid)
  5674. ->where('is_deleted', 0)
  5675. ->first();
  5676. if (!$item) {
  5677. Utils::throwError('20003:项目不存在');
  5678. }
  5679. return DB::table('mp_products')
  5680. ->where('id', $id)
  5681. ->where('cpid', $cpid)
  5682. ->where('user_id', $query_uid)
  5683. ->update([
  5684. 'product_name' => $new_name,
  5685. 'updated_at' => date('Y-m-d H:i:s')
  5686. ]);
  5687. }
  5688. /**
  5689. * 移动角色或文件夹到指定文件夹
  5690. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  5691. * @return bool
  5692. */
  5693. public function moveProductOrFolder($data) {
  5694. $uid = Site::getUid();
  5695. $cpid = Site::getCpid();
  5696. $role = Site::getRole();
  5697. $id = getProp($data, 'id');
  5698. $target_parent_id = getProp($data, 'target_parent_id', 0);
  5699. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5700. if (!$id) {
  5701. Utils::throwError('20003:请选择要移动的项目');
  5702. }
  5703. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5704. $query_uid = $is_public ? 0 : $uid;
  5705. // 如果是公共库操作,需要admin权限
  5706. if ($is_public && $role !== 'admin') {
  5707. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5708. }
  5709. // 检查要移动的项目
  5710. $item = DB::table('mp_products')
  5711. ->where('id', $id)
  5712. ->where('cpid', $cpid)
  5713. ->where('user_id', $query_uid)
  5714. ->where('is_deleted', 0)
  5715. ->first();
  5716. if (!$item) {
  5717. Utils::throwError('20003:项目不存在');
  5718. }
  5719. // 验证目标文件夹
  5720. $target_level = 0;
  5721. $target_product = $item->product; // 默认使用当前项目的 product
  5722. if ($target_parent_id > 0) {
  5723. $target_parent = DB::table('mp_products')
  5724. ->where('id', $target_parent_id)
  5725. ->where('cpid', $cpid)
  5726. ->where('user_id', $query_uid)
  5727. ->where('type', 2)
  5728. ->where('is_deleted', 0)
  5729. ->first();
  5730. if (!$target_parent) {
  5731. Utils::throwError('20003:目标文件夹不存在');
  5732. }
  5733. // 检查 product 类型是否一致
  5734. if ($target_parent->product != $item->product) {
  5735. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  5736. }
  5737. $target_level = $target_parent->level;
  5738. $target_product = $target_parent->product;
  5739. // 如果移动的是文件夹,需要检查层级
  5740. if ($item->type == 2) {
  5741. // 计算移动后的最大层级
  5742. $max_child_level = $this->getMaxChildLevel($id);
  5743. $depth = $max_child_level - $item->level;
  5744. if ($target_level + 1 + $depth > 3) {
  5745. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  5746. }
  5747. // 不能移动到自己或自己的子文件夹下
  5748. if ($this->isDescendant($target_parent_id, $id)) {
  5749. Utils::throwError('20003:不能移动到自己或子文件夹下');
  5750. }
  5751. }
  5752. }
  5753. // 更新父文件夹和层级
  5754. $new_level = $target_level + 1;
  5755. DB::table('mp_products')
  5756. ->where('id', $id)
  5757. ->update([
  5758. 'parent_id' => $target_parent_id,
  5759. 'level' => $new_level,
  5760. 'updated_at' => date('Y-m-d H:i:s')
  5761. ]);
  5762. // 如果是文件夹,需要递归更新所有子项的层级
  5763. if ($item->type == 2) {
  5764. $this->updateChildrenLevel($id, $new_level);
  5765. }
  5766. return true;
  5767. }
  5768. /**
  5769. * 获取文件夹下最大子层级
  5770. * @param int $folder_id
  5771. * @return int
  5772. */
  5773. private function getMaxChildLevel($folder_id) {
  5774. $max_level = DB::table('mp_products')
  5775. ->where('parent_id', $folder_id)
  5776. ->where('is_deleted', 0)
  5777. ->max('level');
  5778. if (!$max_level) {
  5779. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  5780. }
  5781. // 递归查找子文件夹
  5782. $children = DB::table('mp_products')
  5783. ->where('parent_id', $folder_id)
  5784. ->where('type', 2)
  5785. ->where('is_deleted', 0)
  5786. ->pluck('id');
  5787. foreach ($children as $child_id) {
  5788. $child_max = $this->getMaxChildLevel($child_id);
  5789. if ($child_max > $max_level) {
  5790. $max_level = $child_max;
  5791. }
  5792. }
  5793. return $max_level;
  5794. }
  5795. /**
  5796. * 检查 target_id 是否是 folder_id 的后代
  5797. * @param int $target_id
  5798. * @param int $folder_id
  5799. * @return bool
  5800. */
  5801. private function isDescendant($target_id, $folder_id) {
  5802. if ($target_id == $folder_id) {
  5803. return true;
  5804. }
  5805. $parent = DB::table('mp_products')
  5806. ->where('id', $target_id)
  5807. ->where('is_deleted', 0)
  5808. ->first();
  5809. if (!$parent || $parent->parent_id == 0) {
  5810. return false;
  5811. }
  5812. return $this->isDescendant($parent->parent_id, $folder_id);
  5813. }
  5814. /**
  5815. * 递归更新子项层级
  5816. * @param int $parent_id
  5817. * @param int $parent_level
  5818. */
  5819. private function updateChildrenLevel($parent_id, $parent_level) {
  5820. $children = DB::table('mp_products')
  5821. ->where('parent_id', $parent_id)
  5822. ->where('is_deleted', 0)
  5823. ->get();
  5824. foreach ($children as $child) {
  5825. $new_level = $parent_level + 1;
  5826. DB::table('mp_products')
  5827. ->where('id', $child->id)
  5828. ->update([
  5829. 'level' => $new_level,
  5830. 'updated_at' => date('Y-m-d H:i:s')
  5831. ]);
  5832. // 如果是文件夹,继续递归
  5833. if ($child->type == 2) {
  5834. $this->updateChildrenLevel($child->id, $new_level);
  5835. }
  5836. }
  5837. }
  5838. /**
  5839. * 获取文件夹路径(面包屑导航)
  5840. * @param array $data 包含 folder_id
  5841. * @return array 返回路径数组
  5842. */
  5843. public function getFolderPath($data) {
  5844. $uid = Site::getUid();
  5845. $cpid = Site::getCpid();
  5846. $folder_id = getProp($data, 'id', 0);
  5847. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5848. if ($folder_id == 0) {
  5849. return [
  5850. ['id' => 0, 'name' => '根目录']
  5851. ];
  5852. }
  5853. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5854. $query_uid = $is_public ? 0 : $uid;
  5855. $path = [];
  5856. $current_id = $folder_id;
  5857. while ($current_id > 0) {
  5858. $folder = DB::table('mp_products')
  5859. ->where('id', $current_id)
  5860. ->where('cpid', $cpid)
  5861. ->where('user_id', $query_uid)
  5862. ->where('type', 2)
  5863. ->where('is_deleted', 0)
  5864. ->first();
  5865. if (!$folder) {
  5866. break;
  5867. }
  5868. array_unshift($path, [
  5869. 'id' => $folder->id,
  5870. 'name' => $folder->product_name
  5871. ]);
  5872. $current_id = $folder->parent_id;
  5873. }
  5874. // 添加根目录
  5875. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  5876. return $path;
  5877. }
  5878. public function createProduct($data) {
  5879. $uid = Site::getUid();
  5880. $cpid = Site::getCpid();
  5881. $role = Site::getRole();
  5882. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5883. // 如果是公共库操作,需要admin权限
  5884. if ($is_public && $role !== 'admin') {
  5885. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5886. }
  5887. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  5888. $store_uid = $is_public ? 0 : $uid;
  5889. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  5890. $script_id = (int)getProp($data, 'script_id', 0);
  5891. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  5892. if ($script_id && empty($episode_numbers)) {
  5893. Utils::throwError('20003:剧集序号不能为空');
  5894. }
  5895. if (!$script_id && !empty($episode_numbers)) {
  5896. Utils::throwError('20003:请提供剧本ID');
  5897. }
  5898. $product_name = trim(getProp($data, 'product_name'));
  5899. if (!$product_name) Utils::throwError('20003:名称不能为空');
  5900. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5901. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  5902. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  5903. $url = trim(getProp($data, 'url'));
  5904. if (!$url) Utils::throwError('20003:图片地址不能为空');
  5905. $versions = getProp($data, 'versions');
  5906. // 检查是否是正确的图片格式
  5907. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  5908. $urlPath = parse_url($url, PHP_URL_PATH);
  5909. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  5910. if (!in_array($extension, $allowedExtensions)) {
  5911. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  5912. }
  5913. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  5914. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  5915. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  5916. $product = getProp($data, 'product');
  5917. if (!in_array($product, [1, 2, 3])) {
  5918. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  5919. }
  5920. // 获取父文件夹ID和层级
  5921. $parent_id = getProp($data, 'parent_id', 0);
  5922. $parent_level = 0;
  5923. if ($parent_id > 0) {
  5924. $parent = DB::table('mp_products')
  5925. ->where('id', $parent_id)
  5926. ->where('cpid', $cpid)
  5927. ->where('user_id', $store_uid)
  5928. ->where('type', 2)
  5929. ->where('is_deleted', 0)
  5930. ->first();
  5931. if (!$parent) {
  5932. Utils::throwError('20003:父文件夹不存在');
  5933. }
  5934. $parent_level = $parent->level;
  5935. }
  5936. // 创建资产并保存剧本资产关联关系(同一事务)
  5937. DB::beginTransaction();
  5938. try {
  5939. $id = DB::table('mp_products')->insertGetId([
  5940. 'user_id' => $store_uid,
  5941. 'cpid' => $cpid,
  5942. 'type' => 1, // 1=角色图片
  5943. 'parent_id' => $parent_id,
  5944. 'level' => $parent_level + 1,
  5945. 'product_name' => $product_name,
  5946. 'url' => $url,
  5947. 'pic_prompt' => $pic_prompt,
  5948. 'product' => $product,
  5949. 'versions' => json_encode($versions, 256),
  5950. 'sort_order' => time(), // 使用时间戳作为排序权重
  5951. 'created_at' => date('Y-m-d H:i:s'),
  5952. 'updated_at' => date('Y-m-d H:i:s')
  5953. ]);
  5954. if (!$id) Utils::throwError('20003:创建失败');
  5955. // 保存剧本资产关联关系
  5956. if ($script_id) {
  5957. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  5958. }
  5959. DB::commit();
  5960. } catch (\Exception $e) {
  5961. DB::rollback();
  5962. throw $e;
  5963. }
  5964. return [
  5965. 'id' => $id,
  5966. 'type' => 1,
  5967. 'parent_id' => $parent_id,
  5968. 'level' => $parent_level + 1,
  5969. 'product_name' => $product_name,
  5970. 'url' => $url,
  5971. 'pic_prompt' => $pic_prompt,
  5972. 'product' => $product,
  5973. 'versions' => $versions
  5974. ];
  5975. }
  5976. public function editProduct($data) {
  5977. $uid = Site::getUid();
  5978. $cpid = Site::getCpid();
  5979. $role = Site::getRole();
  5980. $id = getProp($data, 'id');
  5981. if (!$id) Utils::throwError('20003:ID不能为空');
  5982. $versions = getProp($data, 'versions');
  5983. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5984. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  5985. $script_id = (int)getProp($data, 'script_id', 0);
  5986. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  5987. if ($script_id && empty($episode_numbers)) {
  5988. Utils::throwError('20003:剧集序号不能为空');
  5989. }
  5990. if (!$script_id && !empty($episode_numbers)) {
  5991. Utils::throwError('20003:请提供剧本ID');
  5992. }
  5993. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  5994. $query_uid = $is_public ? 0 : $uid;
  5995. // 如果是公共库操作,需要admin权限
  5996. if ($is_public && $role !== 'admin') {
  5997. Utils::throwError('20003:只有管理员才能操作公共资产库');
  5998. }
  5999. // 检查是否存在且属于当前用户或公共库
  6000. $role = DB::table('mp_products')
  6001. ->where('id', $id)
  6002. ->where('cpid', $cpid)
  6003. ->where('user_id', $query_uid)
  6004. ->where('type', 1)->first();
  6005. if (!$role) Utils::throwError('20003:记录不存在');
  6006. $updateData = [];
  6007. // $needVersionRecord = false; // 是否需要记录版本
  6008. // 名称
  6009. $product_name = trim(getProp($data, 'product_name'));
  6010. if ($product_name) {
  6011. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6012. $updateData['product_name'] = $product_name;
  6013. }
  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 && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6016. // 图片地址
  6017. $url = trim(getProp($data, 'url'));
  6018. if ($url) {
  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. // // 如果 url 有变更,记录版本
  6027. // if ($url !== $role->url) {
  6028. // $needVersionRecord = true;
  6029. // }
  6030. $updateData['url'] = $url;
  6031. }
  6032. // 提示词
  6033. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6034. if ($pic_prompt) {
  6035. // // 如果 pic_prompt 有变更,记录版本
  6036. // if ($pic_prompt !== $role->pic_prompt) {
  6037. // $needVersionRecord = true;
  6038. // }
  6039. $updateData['pic_prompt'] = $pic_prompt;
  6040. }
  6041. if (empty($updateData) && !$script_id) {
  6042. Utils::throwError('20003:没有需要更新的数据');
  6043. }
  6044. // // 如果需要记录版本,将数据添加到 versions 数组
  6045. // if ($needVersionRecord) {
  6046. // // 获取现有的 versions 数据
  6047. // $versions = json_decode($role->versions, true) ?: [];
  6048. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6049. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6050. // if ($isFirstVersion) {
  6051. // $oldVersion = [
  6052. // 'url' => $role->url,
  6053. // 'description' => $role->pic_prompt,
  6054. // ];
  6055. // // 旧版本添加到数组末尾
  6056. // $versions[] = $oldVersion;
  6057. // }
  6058. // // 构建新版本(变更后)
  6059. // $newVersion = [
  6060. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6061. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6062. // ];
  6063. // // 检查新版本是否已存在于历史版本中
  6064. // $existingIndex = -1;
  6065. // foreach ($versions as $index => $version) {
  6066. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6067. // $existingIndex = $index;
  6068. // break;
  6069. // }
  6070. // }
  6071. // if ($existingIndex !== -1) {
  6072. // // 如果已存在,移除旧的位置
  6073. // array_splice($versions, $existingIndex, 1);
  6074. // }
  6075. // // 新版本添加到数组开头(最新的在前)
  6076. // array_unshift($versions, $newVersion);
  6077. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6078. // // if (count($versions) > 10) {
  6079. // // $versions = array_slice($versions, 0, 10);
  6080. // // }
  6081. // $updateData['versions'] = json_encode($versions, 256);
  6082. // }
  6083. if ($versions) {
  6084. $updateData['versions'] = json_encode($versions, 256);
  6085. }
  6086. if (!empty($updateData)) {
  6087. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6088. }
  6089. // 更新资产并保存剧本资产关联关系(同一事务)
  6090. DB::beginTransaction();
  6091. try {
  6092. $updated = true;
  6093. if (!empty($updateData)) {
  6094. $updated = DB::table('mp_products')
  6095. ->where('cpid', $cpid)
  6096. ->where('id', $id)
  6097. ->update($updateData);
  6098. }
  6099. // 保存剧本资产关联关系
  6100. if ($script_id) {
  6101. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6102. }
  6103. DB::commit();
  6104. } catch (\Exception $e) {
  6105. DB::rollback();
  6106. throw $e;
  6107. }
  6108. return $updated;
  6109. }
  6110. /**
  6111. * 保存单一资产与剧本剧集的关联关系
  6112. *
  6113. * @param int $product_id 资产ID
  6114. * @param int $script_id 剧本ID
  6115. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6116. * @return int 新增关联数量
  6117. */
  6118. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6119. $uid = Site::getUid();
  6120. // 验证剧本是否存在
  6121. $script = DB::table('mp_scripts')
  6122. ->where('id', $script_id)
  6123. ->where('is_deleted', 0)
  6124. ->first();
  6125. if (!$script) {
  6126. Utils::throwError('20003:剧本不存在');
  6127. }
  6128. // 验证剧本归属:只能关联自己的剧本
  6129. if ((int)$script->user_id !== (int)$uid) {
  6130. Utils::throwError('20003:只能添加到自己的剧本');
  6131. }
  6132. // 使用 splitContent 拆分剧本内容获取总集数
  6133. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6134. // 解析剧集序号(数组)
  6135. $episodes = [];
  6136. foreach ($episode_numbers as $item) {
  6137. if (is_array($item)) {
  6138. continue;
  6139. }
  6140. $item = trim((string)$item);
  6141. if ($item === '' || !is_numeric($item)) {
  6142. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6143. }
  6144. $episodes[] = (int)$item;
  6145. }
  6146. // 去重并校验序号范围(序号从1开始)
  6147. $episodes = array_values(array_unique($episodes));
  6148. if (empty($episodes)) {
  6149. Utils::throwError('20003:剧集序号不能为空');
  6150. }
  6151. foreach ($episodes as $episode) {
  6152. if ($episode < 1 || $episode > $totalEpisodes) {
  6153. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6154. }
  6155. }
  6156. $now = now();
  6157. // 过滤已存在的关联,避免重复
  6158. $existingEpisodes = DB::table('mp_script_product_mappings')
  6159. ->where('script_id', $script_id)
  6160. ->where('product_id', $product_id)
  6161. ->whereIn('episode_number', $episodes)
  6162. ->pluck('episode_number')
  6163. ->all();
  6164. $mappingRecords = [];
  6165. foreach ($episodes as $episode) {
  6166. if (in_array($episode, $existingEpisodes)) {
  6167. continue;
  6168. }
  6169. $mappingRecords[] = [
  6170. 'script_id' => $script_id,
  6171. 'product_id' => $product_id,
  6172. 'episode_number' => $episode,
  6173. 'created_at' => $now,
  6174. 'updated_at' => $now,
  6175. ];
  6176. }
  6177. $insertedCount = 0;
  6178. if (!empty($mappingRecords)) {
  6179. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6180. }
  6181. return $insertedCount;
  6182. }
  6183. /**
  6184. * 规范化剧集序号参数,统一为数组
  6185. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6186. *
  6187. * @param mixed $episode_number 剧集序号参数
  6188. * @return array
  6189. */
  6190. private function normalizeEpisodeNumbers($episode_number) {
  6191. if (!is_array($episode_number)) {
  6192. $episode_number = explode(',', (string)$episode_number);
  6193. }
  6194. $items = [];
  6195. foreach ($episode_number as $item) {
  6196. if (is_array($item)) {
  6197. continue;
  6198. }
  6199. foreach (explode(',', (string)$item) as $part) {
  6200. $part = trim($part);
  6201. if ($part !== '') {
  6202. $items[] = $part;
  6203. }
  6204. }
  6205. }
  6206. return $items;
  6207. }
  6208. /**
  6209. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6210. *
  6211. * @param object $script 剧本记录
  6212. * @return int 总集数
  6213. */
  6214. private function getScriptTotalEpisodeCount($script) {
  6215. if (empty($script->content)) {
  6216. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6217. }
  6218. $totalEpisodes = count(splitContent($script->content));
  6219. if ($totalEpisodes < 1) {
  6220. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6221. }
  6222. return $totalEpisodes;
  6223. }
  6224. /**
  6225. * 获取剧本总集数
  6226. *
  6227. * @param array $data 包含 script_id(剧本ID)
  6228. * @return array
  6229. */
  6230. public function getScriptTotalEpisodes($data) {
  6231. $script_id = (int)getProp($data, 'script_id', 0);
  6232. if (!$script_id) {
  6233. Utils::throwError('20003:请提供剧本ID');
  6234. }
  6235. // 验证剧本是否存在
  6236. $script = DB::table('mp_scripts')
  6237. ->where('id', $script_id)
  6238. ->where('is_deleted', 0)
  6239. ->first();
  6240. if (!$script) {
  6241. Utils::throwError('20003:剧本不存在');
  6242. }
  6243. return [
  6244. 'script_id' => $script_id,
  6245. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6246. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6247. ];
  6248. }
  6249. /**
  6250. * 获取角色版本历史
  6251. * @param array $data 包含 id(角色ID)
  6252. * @return array 返回版本历史列表
  6253. */
  6254. public function getProductVersions($data) {
  6255. $cpid = Site::getCpid();
  6256. $id = getProp($data, 'id');
  6257. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6258. $role = DB::table('mp_products')
  6259. ->where('id', $id)
  6260. ->where('cpid', $cpid)
  6261. ->where('type', 1)
  6262. ->first();
  6263. if (!$role) Utils::throwError('20003:角色不存在');
  6264. // 获取版本历史
  6265. $versions = json_decode($role->versions, true) ?: [];
  6266. // 添加当前版本作为最新版本
  6267. $currentVersion = [
  6268. 'version' => 0, // 0 表示当前版本
  6269. 'url' => $role->url,
  6270. 'pic_prompt' => $role->pic_prompt,
  6271. 'updated_at' => $role->updated_at,
  6272. 'is_current' => true
  6273. ];
  6274. array_unshift($versions, $currentVersion);
  6275. return $versions;
  6276. }
  6277. /**
  6278. * 恢复到指定版本
  6279. * @param array $data 包含 id(角色ID)、version(版本号)
  6280. * @return bool
  6281. */
  6282. public function restoreProductVersion($data) {
  6283. $uid = Site::getUid();
  6284. $cpid = Site::getCpid();
  6285. $id = getProp($data, 'id');
  6286. $version = getProp($data, 'version');
  6287. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6288. if (!$version) Utils::throwError('20003:版本号不能为空');
  6289. $role = DB::table('mp_products')
  6290. ->where('id', $id)
  6291. ->where('cpid', $cpid)
  6292. ->where('type', 1)
  6293. ->first();
  6294. if (!$role) Utils::throwError('20003:角色不存在');
  6295. // 获取版本历史
  6296. $versions = json_decode($role->versions, true) ?: [];
  6297. // 查找指定版本
  6298. $targetVersion = null;
  6299. foreach ($versions as $v) {
  6300. if ($v['version'] == $version) {
  6301. $targetVersion = $v;
  6302. break;
  6303. }
  6304. }
  6305. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6306. // 先将当前版本保存到历史
  6307. $newVersion = [
  6308. 'version' => count($versions) + 1,
  6309. 'url' => $role->url,
  6310. 'pic_prompt' => $role->pic_prompt,
  6311. 'updated_at' => date('Y-m-d H:i:s'),
  6312. 'updated_by' => $uid
  6313. ];
  6314. array_unshift($versions, $newVersion);
  6315. // 限制版本数量
  6316. if (count($versions) > 10) {
  6317. $versions = array_slice($versions, 0, 10);
  6318. }
  6319. // 恢复到指定版本
  6320. return DB::table('mp_products')
  6321. ->where('id', $id)
  6322. ->where('cpid', $cpid)
  6323. ->update([
  6324. 'url' => $targetVersion['url'],
  6325. 'pic_prompt' => $targetVersion['pic_prompt'],
  6326. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6327. 'updated_at' => date('Y-m-d H:i:s')
  6328. ]);
  6329. }
  6330. public function deleteProduct($data) {
  6331. $uid = Site::getUid();
  6332. $cpid = Site::getCpid();
  6333. $role = Site::getRole();
  6334. $id = getProp($data, 'id');
  6335. if (!$id) Utils::throwError('20003:ID不能为空');
  6336. $ids = explode(',', $id);
  6337. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6338. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6339. $query_uid = $is_public ? 0 : $uid;
  6340. // 如果是公共库操作,需要admin权限
  6341. if ($is_public && $role !== 'admin') {
  6342. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6343. }
  6344. // 检查是否存在且属于当前用户或公共库
  6345. $role = DB::table('mp_products')
  6346. ->whereIn('id', $ids)
  6347. ->where('cpid', $cpid)
  6348. ->where('user_id', $query_uid)
  6349. ->get();
  6350. if (!$role) Utils::throwError('20003:记录不存在');
  6351. return DB::table('mp_products')
  6352. ->where('cpid', $cpid)
  6353. ->where('user_id', $query_uid)
  6354. ->whereIn('id', $ids)
  6355. ->update([
  6356. 'is_deleted' => 1,
  6357. 'updated_at' => date('Y-m-d H:i:s')
  6358. ]);
  6359. }
  6360. public function generateThreeView($data) {
  6361. $uid = Site::getUid();
  6362. $cpid = Site::getCpid();
  6363. $role = Site::getRole();
  6364. $id = getProp($data, 'id');
  6365. if (!$id) Utils::throwError('20003:ID不能为空');
  6366. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6367. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6368. $query_uid = $is_public ? 0 : $uid;
  6369. // 如果是公共库操作,需要admin权限
  6370. if ($is_public && $role !== 'admin') {
  6371. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6372. }
  6373. // 检查是否存在且属于当前用户或公共库
  6374. $product = DB::table('mp_products')
  6375. ->where('id', $id)
  6376. ->where('cpid', $cpid)
  6377. ->where('user_id', $query_uid)
  6378. ->where('type', 1)->first();
  6379. if (!$product) Utils::throwError('20003:资产不存在');
  6380. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6381. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6382. if (!$ref_img_url) {
  6383. // 如果没有传入参考图,使用角色表中的图片
  6384. $ref_img_url = $product->url ?? '';
  6385. if (!$ref_img_url) {
  6386. Utils::throwError('20003:参考图不能为空');
  6387. }
  6388. }
  6389. $pic_prompt = getProp($product, 'pic_prompt');
  6390. if ($pic_prompt) {
  6391. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6392. }
  6393. // 检查参考图是否是正确的图片格式
  6394. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6395. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6396. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6397. if (!in_array($extension, $allowedExtensions)) {
  6398. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6399. }
  6400. // 处理图片模型
  6401. $model = getProp($data, 'model');
  6402. if (!$model) {
  6403. // 使用默认模型
  6404. $model = 'doubao-seedream-5-0-lite-260128';
  6405. }
  6406. // 验证模型是否在可用模型表中
  6407. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6408. Utils::throwError('20003:该模型已不可用,请更换!');
  6409. }
  6410. $ratio = getProp($data, 'ratio', '16:9');
  6411. $resolution = getProp($data, 'resolution', '2k');
  6412. // 定义分辨率和宽高比对应的尺寸映射表
  6413. $sizeMap = [
  6414. '2k' => [
  6415. '1:1' => ['width' => 2048, 'height' => 2048],
  6416. '4:3' => ['width' => 2304, 'height' => 1728],
  6417. '3:4' => ['width' => 1728, 'height' => 2304],
  6418. '16:9' => ['width' => 2848, 'height' => 1600],
  6419. '9:16' => ['width' => 1600, 'height' => 2848],
  6420. '3:2' => ['width' => 2496, 'height' => 1664],
  6421. '2:3' => ['width' => 1664, 'height' => 2496],
  6422. '21:9' => ['width' => 3136, 'height' => 1344],
  6423. ],
  6424. '3k' => [
  6425. '1:1' => ['width' => 3072, 'height' => 3072],
  6426. '4:3' => ['width' => 3456, 'height' => 2592],
  6427. '3:4' => ['width' => 2592, 'height' => 3456],
  6428. '16:9' => ['width' => 4096, 'height' => 2304],
  6429. '9:16' => ['width' => 2304, 'height' => 4096],
  6430. '2:3' => ['width' => 2496, 'height' => 3744],
  6431. '3:2' => ['width' => 3744, 'height' => 2496],
  6432. '21:9' => ['width' => 4704, 'height' => 2016],
  6433. ],
  6434. '4k' => [
  6435. '1:1' => ['width' => 4096, 'height' => 4096],
  6436. '3:4' => ['width' => 3520, 'height' => 4704],
  6437. '4:3' => ['width' => 4704, 'height' => 3520],
  6438. '16:9' => ['width' => 5504, 'height' => 3040],
  6439. '9:16' => ['width' => 3040, 'height' => 5504],
  6440. '2:3' => ['width' => 3328, 'height' => 4992],
  6441. '3:2' => ['width' => 4992, 'height' => 3328],
  6442. '21:9' => ['width' => 6240, 'height' => 2656],
  6443. ],
  6444. ];
  6445. // 参数验证
  6446. $resolution = strtolower($resolution);
  6447. if (!isset($sizeMap[$resolution])) {
  6448. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6449. }
  6450. if (!isset($sizeMap[$resolution][$ratio])) {
  6451. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6452. }
  6453. // 根据 ratio 和 resolution 确定宽高
  6454. $width = $sizeMap[$resolution][$ratio]['width'];
  6455. $height = $sizeMap[$resolution][$ratio]['height'];
  6456. try {
  6457. // 创建图片生成任务
  6458. $params = [
  6459. 'prompt' => $prompt,
  6460. 'model' => $model,
  6461. 'ref_img_urls' => [$ref_img_url],
  6462. 'width' => $width,
  6463. 'height' => $height
  6464. ];
  6465. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6466. $task_id = $task->id;
  6467. if (!$task_id) {
  6468. Utils::throwError('20003:创建图片生成任务失败');
  6469. }
  6470. // 轮询获取结果
  6471. // 只查询数据库,不调用API,不更新任务表
  6472. $start_time = time();
  6473. $timeout = 1800;
  6474. $img_url = '';
  6475. while (time() - $start_time < $timeout) {
  6476. sleep(5);
  6477. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6478. $task = DB::table('mp_generate_pic_tasks')
  6479. ->where('id', $task_id)
  6480. ->first();
  6481. if (!$task) {
  6482. Utils::throwError('20003:任务不存在');
  6483. }
  6484. if ($task->status === 'success' && $task->result_url) {
  6485. $result_urls = is_string($task->result_url)
  6486. ? json_decode($task->result_url, true)
  6487. : $task->result_url;
  6488. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6489. break;
  6490. } elseif ($task->status === 'failed') {
  6491. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6492. }
  6493. // 其他状态继续轮询
  6494. }
  6495. if (empty($img_url)) {
  6496. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6497. }
  6498. // 更新 mp_products 表(不是任务表)
  6499. DB::table('mp_products')
  6500. ->where('id', $id)
  6501. ->where('cpid', $cpid)
  6502. ->update([
  6503. 'three_view_image_url' => $img_url,
  6504. 'updated_at' => date('Y-m-d H:i:s')
  6505. ]);
  6506. return ['three_view_image_url' => $img_url];
  6507. } catch (\Exception $e) {
  6508. dLog('anime')->error('生成三视图失败', [
  6509. 'error' => $e->getMessage()
  6510. ]);
  6511. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6512. Utils::throwError('20003:' . $e->getMessage());
  6513. }
  6514. }
  6515. /**
  6516. * 推送(复制)资产或文件夹到目标位置
  6517. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6518. * @return array 返回推送结果
  6519. */
  6520. public function pushProductOrFolder($data) {
  6521. $uid = Site::getUid();
  6522. $cpid = Site::getCpid();
  6523. $role = Site::getRole();
  6524. $product_id = getProp($data, 'product_id');
  6525. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6526. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6527. if (!$product_id) {
  6528. Utils::throwError('20003:请选择要推送的项目');
  6529. }
  6530. // 查询源项目(只通过cpid查询,不限制user_id)
  6531. $sourceItem = DB::table('mp_products')
  6532. ->where('id', $product_id)
  6533. ->where('cpid', $cpid)
  6534. ->where('is_deleted', 0)
  6535. ->first();
  6536. if (!$sourceItem) {
  6537. Utils::throwError('20003:要推送的项目不存在');
  6538. }
  6539. // 通过user_id判断源是公共库还是个人库
  6540. $source_uid = $sourceItem->user_id;
  6541. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6542. // 验证目标文件夹并确定目标是公共库还是个人库
  6543. $target_level = 0;
  6544. $target_uid = $uid; // 默认推送到个人库
  6545. $target_is_public = 0;
  6546. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6547. if ($target_parent_id > 0) {
  6548. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6549. $targetParent = DB::table('mp_products')
  6550. ->where('id', $target_parent_id)
  6551. ->where('cpid', $cpid)
  6552. ->where('type', 2)
  6553. ->where('is_deleted', 0)
  6554. ->first();
  6555. if (!$targetParent) {
  6556. Utils::throwError('20003:目标文件夹不存在');
  6557. }
  6558. // 通过user_id判断目标是公共库还是个人库
  6559. $target_level = $targetParent->level;
  6560. $target_uid = $targetParent->user_id;
  6561. $target_is_public = ($target_uid == 0) ? 1 : 0;
  6562. // 使用目标文件夹的 product 类型
  6563. $final_product_type = $targetParent->product;
  6564. }
  6565. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  6566. else {
  6567. $push_to_public = getProp($data, 'push_to_public');
  6568. if ($push_to_public === '') {
  6569. Utils::throwError('20003:请选择是否推送到公共库');
  6570. }
  6571. if ($push_to_public) {
  6572. $target_uid = 0;
  6573. $target_is_public = 1;
  6574. }
  6575. // 推送到根目录时,必须指定 product 类型
  6576. if ($target_product === null || $target_product === '') {
  6577. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  6578. }
  6579. $final_product_type = $target_product;
  6580. }
  6581. // 如果目标是公共库,需要admin权限
  6582. if ($target_is_public && $role !== 'admin') {
  6583. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  6584. }
  6585. // 权限验证:验证是否符合允许的推送规则
  6586. $this->validatePushPermission($source_uid, $target_uid, $uid);
  6587. try {
  6588. DB::beginTransaction();
  6589. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  6590. if ($sourceItem->type == 1) {
  6591. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  6592. DB::commit();
  6593. return [
  6594. 'product_id' => $newId,
  6595. ];
  6596. }
  6597. // 如果是文件夹,递归复制(支持跨类型推送)
  6598. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  6599. DB::commit();
  6600. return [
  6601. 'product_id' => $newFolderId,
  6602. ];
  6603. } catch (\Exception $e) {
  6604. DB::rollBack();
  6605. dLog('anime')->error('推送失败', [
  6606. 'error' => $e->getMessage(),
  6607. 'product_id' => $product_id
  6608. ]);
  6609. Utils::throwError('20003:' . $e->getMessage());
  6610. }
  6611. }
  6612. /**
  6613. * 验证推送权限
  6614. * 允许的推送规则:
  6615. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6616. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  6617. * 3. 公共库推送给公共库(公共库 → 公共库)
  6618. *
  6619. * @param int $source_uid 源的user_id
  6620. * @param int $target_uid 目标的user_id
  6621. * @param int $current_uid 当前用户ID
  6622. * @throws \Exception
  6623. */
  6624. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  6625. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  6626. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  6627. return; // 允许
  6628. }
  6629. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  6630. if ($source_uid == 0 && $target_uid == $current_uid) {
  6631. return; // 允许
  6632. }
  6633. // 规则3:公共库推送给公共库(公共库 → 公共库)
  6634. if ($source_uid == 0 && $target_uid == 0) {
  6635. return; // 允许
  6636. }
  6637. // 其他情况都不允许
  6638. if ($source_uid != 0 && $source_uid != $current_uid) {
  6639. // 源是别人的个人库
  6640. Utils::throwError('20003:无权限访问该资产');
  6641. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  6642. // 个人库推送给公共库(不允许)
  6643. Utils::throwError('20003:不允许将个人资产推送到公共库');
  6644. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  6645. // 不同用户的个人库之间推送(不允许)
  6646. Utils::throwError('20003:不允许推送到其他用户的个人库');
  6647. } else {
  6648. // 其他未知情况
  6649. Utils::throwError('20003:不允许的推送操作');
  6650. }
  6651. }
  6652. /**
  6653. * 复制单个资产
  6654. * @param object $sourceProduct 源资产对象
  6655. * @param int $targetParentId 目标父文件夹ID
  6656. * @param int $targetLevel 目标层级
  6657. * @param int $cpid 公司ID
  6658. * @param int $targetUid 目标用户ID
  6659. * @return int 返回新资产ID
  6660. */
  6661. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  6662. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6663. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  6664. $newProductData = [
  6665. 'user_id' => $targetUid,
  6666. 'cpid' => $cpid,
  6667. 'type' => 1,
  6668. 'parent_id' => $targetParentId,
  6669. 'level' => $targetLevel,
  6670. 'product_name' => $sourceProduct->product_name,
  6671. 'url' => $sourceProduct->url,
  6672. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  6673. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  6674. 'product' => $finalProductType,
  6675. 'versions' => $sourceProduct->versions ?? '',
  6676. 'sort_order' => time(),
  6677. 'is_deleted' => 0,
  6678. 'created_at' => date('Y-m-d H:i:s'),
  6679. 'updated_at' => date('Y-m-d H:i:s')
  6680. ];
  6681. return DB::table('mp_products')->insertGetId($newProductData);
  6682. }
  6683. /**
  6684. * 递归复制文件夹及其子项
  6685. * @param object $sourceFolder 源文件夹对象
  6686. * @param int $targetParentId 目标父文件夹ID
  6687. * @param int $targetLevel 目标层级
  6688. * @param int $cpid 公司ID
  6689. * @param int $targetUid 目标用户ID
  6690. * @param int $sourceUid 源用户ID
  6691. * @return int 返回新文件夹ID
  6692. */
  6693. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  6694. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  6695. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  6696. // 创建新文件夹
  6697. $newFolderData = [
  6698. 'user_id' => $targetUid,
  6699. 'cpid' => $cpid,
  6700. 'type' => 2,
  6701. 'parent_id' => $targetParentId,
  6702. 'level' => $targetLevel,
  6703. 'product_name' => $sourceFolder->product_name,
  6704. 'product' => $finalProductType,
  6705. 'sort_order' => time(),
  6706. 'is_deleted' => 0,
  6707. 'created_at' => date('Y-m-d H:i:s'),
  6708. 'updated_at' => date('Y-m-d H:i:s')
  6709. ];
  6710. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  6711. // 获取源文件夹下的所有子项
  6712. $children = DB::table('mp_products')
  6713. ->where('parent_id', $sourceFolder->id)
  6714. ->where('cpid', $cpid)
  6715. ->where('user_id', $sourceUid)
  6716. ->where('is_deleted', 0)
  6717. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  6718. ->get();
  6719. // 递归复制子项(子项继承目标文件夹的 product 类型)
  6720. foreach ($children as $child) {
  6721. if ($child->type == 1) {
  6722. // 资产
  6723. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  6724. } else {
  6725. // 文件夹
  6726. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  6727. }
  6728. }
  6729. return $newFolderId;
  6730. }
  6731. /**
  6732. * 保存剧本资产关联关系
  6733. * @param array $data 请求参数
  6734. * @return bool
  6735. */
  6736. public function saveScriptProducts($data) {
  6737. $uid = Site::getUid();
  6738. $cpid = Site::getCpid();
  6739. $script_id = getProp($data, 'script_id');
  6740. $products = getProp($data, 'products', []);
  6741. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  6742. if (!$script_id) {
  6743. Utils::throwError('20003:请提供剧本ID');
  6744. }
  6745. // 验证剧本是否存在
  6746. $script = DB::table('mp_scripts')
  6747. ->where('id', $script_id)
  6748. ->where('is_deleted', 0)
  6749. ->first();
  6750. if (!$script) {
  6751. Utils::throwError('20003:剧本不存在');
  6752. }
  6753. // 处理图片模型
  6754. $model = getProp($data, 'model');
  6755. if (!$model) {
  6756. // 使用默认模型
  6757. $model = 'doubao-seedream-5-0-lite-260128';
  6758. }
  6759. // 验证模型是否在可用模型表中
  6760. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6761. Utils::throwError('20003:该模型已不可用,请更换!');
  6762. }
  6763. $ratio = getProp($data, 'ratio', '9:16');
  6764. $resolution = getProp($data, 'resolution', '2k');
  6765. // 定义分辨率和宽高比对应的尺寸映射表
  6766. $sizeMap = [
  6767. '2k' => [
  6768. '1:1' => ['width' => 2048, 'height' => 2048],
  6769. '4:3' => ['width' => 2304, 'height' => 1728],
  6770. '3:4' => ['width' => 1728, 'height' => 2304],
  6771. '16:9' => ['width' => 2848, 'height' => 1600],
  6772. '9:16' => ['width' => 1600, 'height' => 2848],
  6773. '3:2' => ['width' => 2496, 'height' => 1664],
  6774. '2:3' => ['width' => 1664, 'height' => 2496],
  6775. '21:9' => ['width' => 3136, 'height' => 1344],
  6776. ],
  6777. '3k' => [
  6778. '1:1' => ['width' => 3072, 'height' => 3072],
  6779. '4:3' => ['width' => 3456, 'height' => 2592],
  6780. '3:4' => ['width' => 2592, 'height' => 3456],
  6781. '16:9' => ['width' => 4096, 'height' => 2304],
  6782. '9:16' => ['width' => 2304, 'height' => 4096],
  6783. '2:3' => ['width' => 2496, 'height' => 3744],
  6784. '3:2' => ['width' => 3744, 'height' => 2496],
  6785. '21:9' => ['width' => 4704, 'height' => 2016],
  6786. ],
  6787. '4k' => [
  6788. '1:1' => ['width' => 4096, 'height' => 4096],
  6789. '3:4' => ['width' => 3520, 'height' => 4704],
  6790. '4:3' => ['width' => 4704, 'height' => 3520],
  6791. '16:9' => ['width' => 5504, 'height' => 3040],
  6792. '9:16' => ['width' => 3040, 'height' => 5504],
  6793. '2:3' => ['width' => 3328, 'height' => 4992],
  6794. '3:2' => ['width' => 4992, 'height' => 3328],
  6795. '21:9' => ['width' => 6240, 'height' => 2656],
  6796. ],
  6797. ];
  6798. // 参数验证
  6799. $resolution = strtolower($resolution);
  6800. if (!isset($sizeMap[$resolution])) {
  6801. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6802. }
  6803. if (!isset($sizeMap[$resolution][$ratio])) {
  6804. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6805. }
  6806. // 根据 ratio 和 resolution 确定宽高
  6807. $width = $sizeMap[$resolution][$ratio]['width'];
  6808. $height = $sizeMap[$resolution][$ratio]['height'];
  6809. $script_name = $script->script_name ?? 'script_' . $script_id;
  6810. // 检查是否已经有该剧本的资产数据
  6811. $existingMappings = DB::table('mp_script_product_mappings')
  6812. ->where('script_id', $script_id)
  6813. ->get();
  6814. if ($existingMappings->isNotEmpty()) {
  6815. // 已存在资产映射,检查是否所有资产都有图片生成任务
  6816. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  6817. // 查询这些资产的图片生成任务状态
  6818. $productsWithTasks = DB::table('mp_products')
  6819. ->whereIn('id', $productIds)
  6820. ->where('is_deleted', 0)
  6821. ->get();
  6822. $productTaskMap = [];
  6823. $typeFolderIds = [];
  6824. $hasAllTasks = true;
  6825. foreach ($productsWithTasks as $product) {
  6826. // 收集类型文件夹ID
  6827. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  6828. $parentFolder = DB::table('mp_products')
  6829. ->where('id', $product->parent_id)
  6830. ->where('type', 2)
  6831. ->first();
  6832. if ($parentFolder) {
  6833. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  6834. }
  6835. }
  6836. // 检查是否有图片生成任务
  6837. if (!empty($product->pic_task_id)) {
  6838. $productTaskMap[$product->id] = $product->pic_task_id;
  6839. } else if($product->url && $product->pic_task_status == '生成成功') {
  6840. continue;
  6841. } else {
  6842. // 有资产没有图片任务
  6843. $hasAllTasks = false;
  6844. }
  6845. }
  6846. // 如果所有资产都有任务ID,直接轮询返回结果
  6847. if ($hasAllTasks && !empty($productTaskMap)) {
  6848. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  6849. 'script_id' => $script_id,
  6850. 'script_name' => $script_name,
  6851. 'product_count' => count($productTaskMap)
  6852. ]);
  6853. // 直接返回 SSE 流轮询结果
  6854. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6855. }
  6856. // 如果部分资产没有任务ID,只为这些资产创建任务
  6857. if (!$hasAllTasks && $auto_generate_images) {
  6858. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  6859. 'script_id' => $script_id,
  6860. 'script_name' => $script_name
  6861. ]);
  6862. // 开启事务
  6863. DB::beginTransaction();
  6864. try {
  6865. foreach ($productsWithTasks as $product) {
  6866. // 跳过已有任务的资产
  6867. if (!empty($product->pic_task_id)) {
  6868. continue;
  6869. }
  6870. // 跳过没有提示词的资产
  6871. if (empty($product->pic_prompt)) {
  6872. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  6873. 'product_id' => $product->id,
  6874. 'product_name' => $product->product_name
  6875. ]);
  6876. continue;
  6877. }
  6878. try {
  6879. // 创建图片生成任务
  6880. $params = [
  6881. 'prompt' => $product->pic_prompt,
  6882. 'model' => $model,
  6883. 'ref_img_urls' => [],
  6884. 'width' => $width,
  6885. 'height' => $height
  6886. ];
  6887. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6888. $task_id = $task->id;
  6889. if ($task_id) {
  6890. $productTaskMap[$product->id] = $task_id;
  6891. // 在事务中更新资产表的任务ID和状态
  6892. DB::table('mp_products')
  6893. ->where('id', $product->id)
  6894. ->update([
  6895. 'pic_task_id' => $task_id,
  6896. 'pic_task_status' => '生成中',
  6897. 'updated_at' => now()
  6898. ]);
  6899. dLog('anime')->info('为已存在资产创建图片生成任务', [
  6900. 'product_id' => $product->id,
  6901. 'task_id' => $task_id
  6902. ]);
  6903. }
  6904. } catch (\Exception $e) {
  6905. dLog('anime')->error('创建资产图片生成任务失败', [
  6906. 'product_id' => $product->id,
  6907. 'error' => $e->getMessage()
  6908. ]);
  6909. // 标记为失败(仍在事务中)
  6910. DB::table('mp_products')
  6911. ->where('id', $product->id)
  6912. ->update([
  6913. 'pic_task_status' => '生成失败',
  6914. 'updated_at' => now()
  6915. ]);
  6916. }
  6917. }
  6918. // 提交事务
  6919. DB::commit();
  6920. // 如果有新创建的任务,返回 SSE 流
  6921. if (!empty($productTaskMap)) {
  6922. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  6923. }
  6924. } catch (\Exception $e) {
  6925. // 回滚事务
  6926. DB::rollback();
  6927. dLog('anime')->error('为已存在资产创建图片任务失败', [
  6928. 'script_id' => $script_id,
  6929. 'error' => $e->getMessage()
  6930. ]);
  6931. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  6932. }
  6933. }
  6934. // 如果不需要生成图片,返回已存在的信息
  6935. return [
  6936. 'success' => true,
  6937. 'message' => '剧本资产已存在',
  6938. 'script_id' => $script_id,
  6939. 'script_name' => $script_name,
  6940. 'type_folder_ids' => $typeFolderIds,
  6941. 'existing_products' => count($productIds),
  6942. 'tasks_count' => count($productTaskMap)
  6943. ];
  6944. }
  6945. // 解析 products(可能是 JSON 字符串或数组)
  6946. if (is_string($products)) {
  6947. $products = json_decode($products, true);
  6948. if (json_last_error() !== JSON_ERROR_NONE) {
  6949. Utils::throwError('20003:产品数据格式错误');
  6950. }
  6951. }
  6952. if (!is_array($products) || empty($products)) {
  6953. Utils::throwError('20003:产品数据不能为空');
  6954. }
  6955. // 以下是原有的创建逻辑...
  6956. // 开启事务
  6957. DB::beginTransaction();
  6958. try {
  6959. $now = now();
  6960. $mappingRecords = [];
  6961. $createdProductIds = []; // 记录所有创建的资产ID
  6962. // 获取剧本名称
  6963. $script_name = $script->script_name ?? 'script_' . $script_id;
  6964. // 存储每个类型的根文件夹ID
  6965. $typeFolderIds = [];
  6966. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  6967. foreach ($products as $productGroup) {
  6968. $type = getProp($productGroup, 'type');
  6969. $title = getProp($productGroup, 'title', '');
  6970. $content = getProp($productGroup, 'content', []);
  6971. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  6972. continue;
  6973. }
  6974. // 为当前类型创建根文件夹(如果还未创建)
  6975. if (!isset($typeFolderIds[$type])) {
  6976. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  6977. 'user_id' => $uid,
  6978. 'cpid' => $cpid,
  6979. 'type' => 2, // 1.资产 2文件夹
  6980. 'product' => $type, // 1.主体 2.场景 3.道具
  6981. 'parent_id' => 0, // 根文件夹,parent_id=0
  6982. 'level' => 1, // 第一层级
  6983. 'product_name' => $script_name,
  6984. 'sort_order' => time() + $type,
  6985. 'is_deleted' => 0,
  6986. 'created_at' => $now,
  6987. 'updated_at' => $now
  6988. ]);
  6989. }
  6990. $folder_id = $typeFolderIds[$type];
  6991. // 获取表头(第一行)并查找关键列的位置
  6992. $headers = $content[0];
  6993. $nameColumnIndex = -1; // 资产名称列索引
  6994. $sequenceColumnIndex = -1; // 使用范围列索引
  6995. $promptColumnIndex = -1; // 参考提示词列索引
  6996. foreach ($headers as $index => $header) {
  6997. // 查找"资产名称"列
  6998. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  6999. $nameColumnIndex = $index;
  7000. }
  7001. // 查找"使用范围"列
  7002. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  7003. $sequenceColumnIndex = $index;
  7004. }
  7005. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  7006. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  7007. $promptColumnIndex = $index;
  7008. }
  7009. }
  7010. // 验证必要的列是否都找到了
  7011. if ($nameColumnIndex === -1) {
  7012. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  7013. continue;
  7014. }
  7015. if ($sequenceColumnIndex === -1) {
  7016. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  7017. continue;
  7018. }
  7019. // 跳过表头,解析每一行数据
  7020. for ($i = 1; $i < count($content); $i++) {
  7021. $row = $content[$i];
  7022. // 确保行数据有效
  7023. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  7024. continue;
  7025. }
  7026. // 根据动态查找的列索引提取数据
  7027. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  7028. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  7029. $pic_prompt = '';
  7030. // 提取参考提示词(如果找到了该列)
  7031. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  7032. $pic_prompt = trim($row[$promptColumnIndex]);
  7033. }
  7034. // 解析使用范围(逗号分隔的序号)
  7035. $sequences = [];
  7036. if (!empty($sequence_str)) {
  7037. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  7038. foreach ($sequenceParts as $part) {
  7039. if (is_numeric($part)) {
  7040. $sequences[] = (int)$part;
  7041. }
  7042. }
  7043. }
  7044. if (empty($product_name)) {
  7045. continue;
  7046. }
  7047. // 处理product_name两边的符号
  7048. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7049. // 如果名称不存在或仅剩占位符号,则跳过
  7050. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  7051. dLog('anime')->warning('资产名称无效,跳过保存', [
  7052. 'script_id' => $script_id,
  7053. 'type' => $type,
  7054. 'product_name' => $product_name
  7055. ]);
  7056. continue;
  7057. }
  7058. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  7059. $product_id = DB::table('mp_products')->insertGetId([
  7060. 'product_name' => $product_name,
  7061. 'type' => 1, // 1=资产 2.文件夹
  7062. 'product' => $type, // 1=角色, 2=场景, 3=道具
  7063. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  7064. 'level' => 2, // 第二层级
  7065. 'pic_prompt' => $pic_prompt,
  7066. 'user_id' => $uid,
  7067. 'cpid' => $cpid,
  7068. 'sort_order' => time(),
  7069. 'is_deleted' => 0,
  7070. 'created_at' => $now,
  7071. 'updated_at' => $now,
  7072. ]);
  7073. // 记录创建的资产ID
  7074. $createdProductIds[] = $product_id;
  7075. // 为每个序号创建映射记录
  7076. if (!empty($sequences)) {
  7077. foreach ($sequences as $sequence) {
  7078. $mappingRecords[] = [
  7079. 'script_id' => $script_id,
  7080. 'product_id' => $product_id,
  7081. 'episode_number' => $sequence,
  7082. 'created_at' => $now,
  7083. 'updated_at' => $now,
  7084. ];
  7085. }
  7086. } else {
  7087. // 如果没有指定序号,创建一个默认映射(序号为0)
  7088. $mappingRecords[] = [
  7089. 'script_id' => $script_id,
  7090. 'product_id' => $product_id,
  7091. 'episode_number' => 0,
  7092. 'created_at' => $now,
  7093. 'updated_at' => $now,
  7094. ];
  7095. }
  7096. }
  7097. }
  7098. if (empty($mappingRecords)) {
  7099. Utils::throwError('20003:没有有效的产品数据');
  7100. }
  7101. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7102. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7103. // 剧本已有资产,同步更新is_products标记
  7104. DB::table('mp_scripts')->where('id', $script_id)->update([
  7105. 'is_products' => 1,
  7106. 'updated_at' => $now
  7107. ]);
  7108. // 如果需要自动生成图片,在事务中创建图片生成任务
  7109. $productTaskMap = [];
  7110. if ($auto_generate_images && !empty($createdProductIds)) {
  7111. // 查询所有创建的资产
  7112. $productsToGenerate = DB::table('mp_products')
  7113. ->whereIn('id', $createdProductIds)
  7114. ->where('is_deleted', 0)
  7115. ->get();
  7116. foreach ($productsToGenerate as $product) {
  7117. if (empty($product->pic_prompt)) {
  7118. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7119. 'product_id' => $product->id,
  7120. 'product_name' => $product->product_name
  7121. ]);
  7122. continue;
  7123. }
  7124. try {
  7125. // 创建图片生成任务
  7126. $params = [
  7127. 'prompt' => $product->pic_prompt,
  7128. 'model' => $model,
  7129. 'ref_img_urls' => [],
  7130. 'width' => $width,
  7131. 'height' => $height
  7132. ];
  7133. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7134. $task_id = $task->id;
  7135. if ($task_id) {
  7136. $productTaskMap[$product->id] = $task_id;
  7137. // 在事务中更新资产表的任务ID和状态
  7138. DB::table('mp_products')
  7139. ->where('id', $product->id)
  7140. ->update([
  7141. 'pic_task_id' => $task_id,
  7142. 'pic_task_status' => '生成中',
  7143. 'updated_at' => now()
  7144. ]);
  7145. dLog('anime')->info('创建资产图片生成任务', [
  7146. 'product_id' => $product->id,
  7147. 'task_id' => $task_id
  7148. ]);
  7149. }
  7150. } catch (\Exception $e) {
  7151. dLog('anime')->error('创建资产图片生成任务失败', [
  7152. 'product_id' => $product->id,
  7153. 'error' => $e->getMessage()
  7154. ]);
  7155. // 标记为失败(仍在事务中)
  7156. DB::table('mp_products')
  7157. ->where('id', $product->id)
  7158. ->update([
  7159. 'pic_task_status' => '生成失败',
  7160. 'updated_at' => now()
  7161. ]);
  7162. }
  7163. }
  7164. }
  7165. // 提交事务
  7166. DB::commit();
  7167. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  7168. if ($auto_generate_images && !empty($productTaskMap)) {
  7169. // 返回 SSE 流(事务外轮询)
  7170. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds);
  7171. }
  7172. // 如果不需要生成图片,返回普通结果
  7173. return [
  7174. 'success' => true,
  7175. 'type_folder_ids' => $typeFolderIds,
  7176. 'inserted_count' => $insertedCount,
  7177. 'total_records' => count($mappingRecords),
  7178. 'created_products' => count($createdProductIds),
  7179. 'image_tasks_created' => count($productTaskMap)
  7180. ];
  7181. } catch (\Exception $e) {
  7182. // 回滚事务
  7183. DB::rollback();
  7184. // 记录错误日志
  7185. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  7186. 'script_id' => $script_id,
  7187. 'error' => $e->getMessage(),
  7188. 'trace' => $e->getTraceAsString()
  7189. ]);
  7190. // 统一使用 Utils::throwError 抛出错误
  7191. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  7192. }
  7193. }
  7194. /**
  7195. * 批量为剧本资产生成图片
  7196. *
  7197. * @param array $data 请求参数
  7198. * @return \Generator 返回 SSE 流
  7199. */
  7200. public function batchGenerateProductImages($data) {
  7201. $script_id = getProp($data, 'script_id');
  7202. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  7203. if (!$script_id) {
  7204. Utils::throwError('20003:请提供剧本ID');
  7205. }
  7206. // 验证剧本是否存在
  7207. $script = DB::table('mp_scripts')
  7208. ->where('id', $script_id)
  7209. ->where('is_deleted', 0)
  7210. ->first();
  7211. if (!$script) {
  7212. Utils::throwError('20003:剧本不存在');
  7213. }
  7214. $script_name = $script->script_name ?? 'script_' . $script_id;
  7215. // 获取需要生成图片的所有资产
  7216. $products = DB::table('mp_products')
  7217. ->whereIn('parent_id', array_values($type_folder_ids))
  7218. ->where('is_deleted', 0)
  7219. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  7220. ->get();
  7221. if ($products->isEmpty()) {
  7222. Utils::throwError('20003:没有找到需要生成图片的资产');
  7223. }
  7224. // 默认参数
  7225. $model = 'doubao-seedream-5-0-lite-260128';
  7226. $width = 1600;
  7227. $height = 2848;
  7228. // 开始为每个资产创建图片生成任务
  7229. $taskIds = [];
  7230. $productTaskMap = []; // 资产ID到任务ID的映射
  7231. foreach ($products as $product) {
  7232. if (empty($product->pic_prompt)) {
  7233. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  7234. continue;
  7235. }
  7236. try {
  7237. // 创建图片生成任务
  7238. $params = [
  7239. 'prompt' => $product->pic_prompt,
  7240. 'model' => $model,
  7241. 'ref_img_urls' => [],
  7242. 'width' => $width,
  7243. 'height' => $height
  7244. ];
  7245. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7246. $task_id = $task->id;
  7247. if ($task_id) {
  7248. $taskIds[] = $task_id;
  7249. $productTaskMap[$product->id] = $task_id;
  7250. // 更新资产表的任务ID和状态
  7251. DB::table('mp_products')
  7252. ->where('id', $product->id)
  7253. ->update([
  7254. 'pic_task_id' => $task_id,
  7255. 'pic_task_status' => '生成中',
  7256. 'updated_at' => now()
  7257. ]);
  7258. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  7259. }
  7260. } catch (\Exception $e) {
  7261. dLog('anime')->error('创建资产图片生成任务失败', [
  7262. 'product_id' => $product->id,
  7263. 'error' => $e->getMessage()
  7264. ]);
  7265. // 标记为失败
  7266. DB::table('mp_products')
  7267. ->where('id', $product->id)
  7268. ->update([
  7269. 'pic_task_status' => '生成失败',
  7270. 'updated_at' => now()
  7271. ]);
  7272. }
  7273. }
  7274. if (empty($taskIds)) {
  7275. Utils::throwError('20003:没有成功创建任何图片生成任务');
  7276. }
  7277. // 返回 SSE 流
  7278. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  7279. }
  7280. /**
  7281. * 轮询资产图片生成任务状态(SSE流式返回)
  7282. * 只通过查询数据库获取任务状态,不主动调用API
  7283. *
  7284. * @param int $script_id 剧本ID
  7285. * @param string $script_name 剧本名称
  7286. * @param array $productTaskMap 资产ID到任务ID的映射
  7287. * @param array $type_folder_ids 类型文件夹ID映射
  7288. * @return \Generator
  7289. */
  7290. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids) {
  7291. $startTime = time();
  7292. $timeout = 1800; // 30分钟超时
  7293. $pollInterval = 10; // 10秒轮询一次
  7294. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  7295. // 定义类型名称映射
  7296. $typeNames = [
  7297. 1 => 'roles', // 角色
  7298. 2 => 'scenes', // 场景
  7299. 3 => 'props' // 道具
  7300. ];
  7301. while (time() - $startTime < $timeout) {
  7302. sleep($pollInterval);
  7303. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  7304. $mappings = DB::table('mp_script_product_mappings')
  7305. ->where('script_id', $script_id)
  7306. ->pluck('product_id')
  7307. ->unique()
  7308. ->toArray();
  7309. if (empty($mappings)) {
  7310. dLog('anime')->warning('该剧本没有关联的资产', [
  7311. 'script_id' => $script_id,
  7312. 'script_name' => $script_name
  7313. ]);
  7314. break;
  7315. }
  7316. // 查询所有资产的当前状态
  7317. $products = DB::table('mp_products')
  7318. ->whereIn('id', $mappings)
  7319. ->where('is_deleted', 0)
  7320. ->get();
  7321. // 统计各类型的状态(使用类型名称作为键名)
  7322. $stats = [
  7323. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  7324. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  7325. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  7326. ];
  7327. $allCompleted = true;
  7328. $hasStatusChange = false;
  7329. foreach ($products as $product) {
  7330. $type = $product->product;
  7331. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  7332. // 如果类型名称不在 stats 中,初始化
  7333. if (!isset($stats[$typeName])) {
  7334. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  7335. }
  7336. $stats[$typeName]['total']++;
  7337. $task_id = $product->pic_task_id;
  7338. $currentStatus = $product->pic_task_status;
  7339. // 检查状态是否有变化
  7340. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  7341. $hasStatusChange = true;
  7342. $lastStatus[$product->id] = $currentStatus;
  7343. }
  7344. // 如果是生成中,查询任务表状态
  7345. if ($currentStatus === '生成中' && $task_id) {
  7346. // 只查询数据库,不调用API
  7347. $task = DB::table('mp_generate_pic_tasks')
  7348. ->where('id', $task_id)
  7349. ->first();
  7350. if ($task) {
  7351. // 检查任务状态
  7352. if ($task->status === 'success' && $task->result_url) {
  7353. // 解析图片URL
  7354. $result_urls = $task->result_url;
  7355. if (is_string($result_urls)) {
  7356. $result_urls = json_decode($result_urls, true);
  7357. }
  7358. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7359. // 更新资产表状态
  7360. DB::table('mp_products')
  7361. ->where('id', $product->id)
  7362. ->update([
  7363. 'pic_task_status' => '生成成功',
  7364. 'url' => $img_url,
  7365. 'updated_at' => now()
  7366. ]);
  7367. $stats[$typeName]['success']++;
  7368. $stats[$typeName]['completed']++;
  7369. $hasStatusChange = true;
  7370. dLog('anime')->info('资产图片生成成功', [
  7371. 'product_id' => $product->id,
  7372. 'task_id' => $task_id,
  7373. 'img_url' => $img_url
  7374. ]);
  7375. } elseif ($task->status === 'failed') {
  7376. // 更新资产表状态
  7377. DB::table('mp_products')
  7378. ->where('id', $product->id)
  7379. ->update([
  7380. 'pic_task_status' => '生成失败',
  7381. 'updated_at' => now()
  7382. ]);
  7383. $stats[$typeName]['completed']++;
  7384. $hasStatusChange = true;
  7385. dLog('anime')->warning('资产图片生成失败', [
  7386. 'product_id' => $product->id,
  7387. 'task_id' => $task_id,
  7388. 'error' => $task->error_message ?? '未知错误'
  7389. ]);
  7390. } else {
  7391. // 任务还在处理中
  7392. $allCompleted = false;
  7393. }
  7394. } else {
  7395. // 任务不存在,标记为失败
  7396. DB::table('mp_products')
  7397. ->where('id', $product->id)
  7398. ->update([
  7399. 'pic_task_status' => '生成失败',
  7400. 'updated_at' => now()
  7401. ]);
  7402. $stats[$type]['completed']++;
  7403. $hasStatusChange = true;
  7404. dLog('anime')->error('图片生成任务不存在', [
  7405. 'product_id' => $product->id,
  7406. 'task_id' => $task_id
  7407. ]);
  7408. }
  7409. } elseif ($currentStatus === '生成成功') {
  7410. $stats[$typeName]['success']++;
  7411. $stats[$typeName]['completed']++;
  7412. } elseif ($currentStatus === '生成失败') {
  7413. $stats[$typeName]['completed']++;
  7414. } else {
  7415. // 其他状态也认为未完成
  7416. $allCompleted = false;
  7417. }
  7418. }
  7419. // 移除没有数据的类型(total=0)
  7420. foreach ($stats as $typeName => $stat) {
  7421. if ($stat['total'] === 0) {
  7422. unset($stats[$typeName]);
  7423. }
  7424. }
  7425. // 如果有状态变化,发送 SSE 更新
  7426. if ($hasStatusChange) {
  7427. $eventType = $allCompleted ? 'complete' : 'update';
  7428. $response = [
  7429. 'type' => $eventType,
  7430. 'script_id' => $script_id,
  7431. 'script_name' => $script_name,
  7432. 'stats' => $stats,
  7433. 'timestamp' => date('Y-m-d H:i:s')
  7434. ];
  7435. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7436. dLog('anime')->info('SSE更新', [
  7437. 'event_type' => $eventType,
  7438. 'script_id' => $script_id,
  7439. 'script_name' => $script_name,
  7440. 'stats' => $stats
  7441. ]);
  7442. if ($allCompleted) {
  7443. dLog('anime')->info('所有资产图片生成任务已完成', [
  7444. 'script_id' => $script_id,
  7445. 'script_name' => $script_name,
  7446. 'stats' => $stats
  7447. ]);
  7448. break;
  7449. }
  7450. }
  7451. }
  7452. // 超时处理
  7453. if (time() - $startTime >= $timeout && !$allCompleted) {
  7454. $response = [
  7455. 'type' => 'timeout',
  7456. 'message' => '部分任务超时,请稍后查看结果',
  7457. 'script_id' => $script_id,
  7458. 'script_name' => $script_name,
  7459. 'timestamp' => date('Y-m-d H:i:s')
  7460. ];
  7461. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  7462. dLog('anime')->warning('资产图片生成任务超时', [
  7463. 'script_id' => $script_id,
  7464. 'script_name' => $script_name,
  7465. 'timeout' => $timeout
  7466. ]);
  7467. }
  7468. }
  7469. /**
  7470. * 获取剧本关联的资产列表
  7471. * @param array $data 请求参数
  7472. * @return array
  7473. */
  7474. public function getScriptProducts($data) {
  7475. $uid = Site::getUid();
  7476. $cpid = Site::getCpid();
  7477. $script_id = getProp($data, 'script_id');
  7478. $episode_number = getProp($data, 'episode_number');
  7479. if (!$script_id) {
  7480. Utils::throwError('20003:请提供剧本ID');
  7481. }
  7482. // 验证剧本是否存在
  7483. $script = DB::table('mp_scripts')
  7484. ->where('id', $script_id)
  7485. ->where('is_deleted', 0)
  7486. ->first();
  7487. if (!$script) {
  7488. Utils::throwError('20003:剧本不存在');
  7489. }
  7490. // 联表查询资产信息
  7491. $query = DB::table('mp_script_product_mappings as mapping')
  7492. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7493. ->where('mapping.script_id', $script_id)
  7494. ->where('product.cpid', $cpid)
  7495. ->where('product.is_deleted', 0);
  7496. // 如果提供了 episode_number,则过滤指定集数
  7497. if ($episode_number !== null && $episode_number !== '') {
  7498. $query->where('mapping.episode_number', $episode_number);
  7499. }
  7500. $mappings = $query->select(
  7501. 'mapping.script_id',
  7502. 'mapping.product_id',
  7503. 'mapping.episode_number',
  7504. 'product.product_name',
  7505. 'product.type',
  7506. 'product.product',
  7507. 'product.pic_prompt',
  7508. 'product.url',
  7509. 'product.pic_task_id',
  7510. 'product.pic_task_status',
  7511. 'product.three_view_image_url',
  7512. 'mapping.created_at'
  7513. )
  7514. ->orderBy('mapping.product_id', 'asc')
  7515. ->orderBy('mapping.episode_number', 'asc')
  7516. ->get();
  7517. // 按 product_id 分组,合并 episode_number
  7518. $productMap = [];
  7519. foreach ($mappings as $item) {
  7520. $product_id = $item->product_id;
  7521. if (!isset($productMap[$product_id])) {
  7522. $productMap[$product_id] = [
  7523. 'product_id' => $product_id,
  7524. 'product_name' => $item->product_name,
  7525. 'type' => (int)$item->type,
  7526. 'product' => (int)$item->product,
  7527. 'pic_prompt' => $item->pic_prompt,
  7528. 'url' => $item->url,
  7529. 'pic_task_id' => $item->pic_task_id,
  7530. 'pic_task_status' => $item->pic_task_status,
  7531. 'episode_numbers' => [],
  7532. 'created_at' => $item->created_at,
  7533. ];
  7534. }
  7535. // 添加 episode_number(去重)
  7536. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7537. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7538. }
  7539. }
  7540. // 按类型分组
  7541. $roles = []; // type=1 角色/主体
  7542. $scenes = []; // type=2 场景
  7543. $props = []; // type=3 道具
  7544. foreach ($productMap as $product) {
  7545. // 将 episode_numbers 数组转换为逗号分隔的字符串
  7546. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  7547. // 构造返回数据
  7548. $productData = [
  7549. 'product_id' => $product['product_id'],
  7550. 'product_name' => $product['product_name'],
  7551. 'product' => $product['product'],
  7552. 'pic_prompt' => $product['pic_prompt'],
  7553. 'url' => $product['url'],
  7554. 'pic_task_id' => $product['pic_task_id'],
  7555. 'pic_task_status' => $product['pic_task_status'],
  7556. 'episode_numbers' => $episodeNumbersStr,
  7557. 'created_at' => $product['created_at'],
  7558. ];
  7559. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  7560. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  7561. switch ($product['product']) {
  7562. case 1:
  7563. $roles[] = $productData;
  7564. break;
  7565. case 2:
  7566. $scenes[] = $productData;
  7567. break;
  7568. case 3:
  7569. $props[] = $productData;
  7570. break;
  7571. }
  7572. }
  7573. return [
  7574. 'script_id' => $script_id,
  7575. 'script_name' => $script->script_name ?? '',
  7576. 'roles' => $roles, // 主体
  7577. 'scenes' => $scenes, // 场景
  7578. 'props' => $props, // 道具
  7579. ];
  7580. }
  7581. /**
  7582. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  7583. * @param string $actContent 原始内容
  7584. * @param array $products 产品数组(包含product_name和url)
  7585. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  7586. */
  7587. public function processActContentWithProducts($actContent, $products) {
  7588. if (empty($actContent) || empty($products)) {
  7589. return [
  7590. 'content' => $actContent,
  7591. 'reference_images' => []
  7592. ];
  7593. }
  7594. // 构建产品名称到产品信息的映射
  7595. $product_dict = [];
  7596. foreach ($products as $product) {
  7597. $product_name = getProp($product, 'product_name');
  7598. if ($product_name) {
  7599. $product_dict[$product_name] = [
  7600. 'url' => getProp($product, 'url'),
  7601. 'voice_prompt' => getProp($product, 'voice_prompt')
  7602. ];
  7603. }
  7604. }
  7605. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  7606. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  7607. $reference_images = [];
  7608. $product_index_map = []; // 产品名称 => 图片序号的映射
  7609. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  7610. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  7611. $current_index = 1;
  7612. if (!empty($matches[1])) {
  7613. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  7614. $seen_products = []; // 用于去重
  7615. foreach ($matches[1] as $product_name) {
  7616. // 跳过已处理的产品
  7617. if (isset($seen_products[$product_name])) {
  7618. continue;
  7619. }
  7620. $seen_products[$product_name] = true;
  7621. // 检查产品是否在字典中
  7622. if (isset($product_dict[$product_name])) {
  7623. $url = $product_dict[$product_name]['url'];
  7624. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  7625. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  7626. if (!empty($voice_prompt) && $product_name !== '旁白') {
  7627. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  7628. }
  7629. // 只有URL非空才分配序号和添加到参考图片
  7630. if (!empty($url)) {
  7631. // 检查URL是否已经在reference_images中(去重)
  7632. if (!in_array($url, $reference_images)) {
  7633. $reference_images[] = $url;
  7634. $product_index_map[$product_name] = $current_index;
  7635. $current_index++;
  7636. } else {
  7637. // URL重复,找到已有的序号
  7638. $existing_index = array_search($url, $reference_images) + 1;
  7639. $product_index_map[$product_name] = $existing_index;
  7640. }
  7641. } else {
  7642. // URL为空,不分配序号(后续直接去掉{})
  7643. $product_index_map[$product_name] = 0;
  7644. }
  7645. } else {
  7646. // 产品不在字典中,不分配序号
  7647. $product_index_map[$product_name] = 0;
  7648. }
  7649. }
  7650. }
  7651. // 第二步:替换内容中的 {产品名称}
  7652. $processedContent = $actContent;
  7653. foreach ($product_index_map as $product_name => $index) {
  7654. $escaped_name = preg_quote($product_name, '/');
  7655. if ($index > 0) {
  7656. // 有图片,替换为:产品名称(图X)
  7657. $replacement = $product_name . '<图片' . $index . '>';
  7658. } else {
  7659. // 无图片,只保留产品名称
  7660. $replacement = $product_name;
  7661. }
  7662. // 替换所有 {产品名称} 为处理后的格式
  7663. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  7664. }
  7665. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  7666. foreach ($products as $product) {
  7667. $product_name = getProp($product, 'product_name');
  7668. $voice_prompt = getProp($product, 'voice_prompt');
  7669. if ($product_name === '旁白' && !empty($voice_prompt)) {
  7670. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  7671. break; // 找到旁白后退出循环
  7672. }
  7673. }
  7674. // 第四步:将voice_prompt信息添加到内容最前面
  7675. $voice_prompt_prefix = '';
  7676. if (!empty($voice_prompts)) {
  7677. $voice_prompt_prefix .= implode('', $voice_prompts);
  7678. }
  7679. // 旁白的voice_prompt放在最后
  7680. if (!empty($narrator_voice_prompt)) {
  7681. $voice_prompt_prefix .= $narrator_voice_prompt;
  7682. }
  7683. // 如果有voice_prompt信息,添加到内容开头
  7684. if (!empty($voice_prompt_prefix)) {
  7685. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  7686. }
  7687. return [
  7688. 'content' => $processedContent,
  7689. 'reference_images' => $reference_images
  7690. ];
  7691. }
  7692. public function saveActVideoGenerateParams($data) {
  7693. $episode_id = getProp($data, 'episode_id');
  7694. $model = getProp($data, 'video_model');
  7695. if (!in_array($model, ['zhizhen-20', 'zhizhen-20-fas', 'zhizhen-20-mini'])) {
  7696. Utils::throwError('20003:该模型不可用');
  7697. }
  7698. if (!$model) {
  7699. // 使用默认模型
  7700. $model = 'zhizhen-20';
  7701. }
  7702. // 验证模型是否在可用模型表中
  7703. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7704. Utils::throwError('20003:该模型已不可用,请更换!');
  7705. }
  7706. $video_resolution = getProp($data, 'video_resolution', '720p');
  7707. $ratio = getProp($data, 'ratio');
  7708. if (!$ratio) $ratio = '9:16';
  7709. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  7710. if (!$episode) {
  7711. Utils::throwError('20003:分集不存在');
  7712. }
  7713. try {
  7714. DB::beginTransaction();
  7715. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7716. 'video_model' => $model,
  7717. 'video_resolution' => $video_resolution,
  7718. 'ratio' => $ratio,
  7719. 'updated_at' => date('Y-m-d H:i:s')
  7720. ]);
  7721. if ($result === false) {
  7722. Utils::throwError('20003:分集视频参数保存失败');
  7723. }
  7724. // 同步更新mp_animes表
  7725. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  7726. 'video_model' => $model,
  7727. 'video_resolution' => $video_resolution,
  7728. 'video_ratio' => $ratio,
  7729. 'updated_at' => date('Y-m-d H:i:s')
  7730. ]);
  7731. if ($anime_result === false) {
  7732. Utils::throwError('20003:动漫视频参数保存失败');
  7733. }
  7734. } catch (\Exception $e) {
  7735. DB::rollBack();
  7736. Utils::throwError('20003:'.$e->getMessage());
  7737. }
  7738. DB::commit();
  7739. return $result;
  7740. }
  7741. public function confirmActs($data) {
  7742. $episode_id = getProp($data, 'episode_id');
  7743. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  7744. if (!$episode) {
  7745. Utils::throwError('20003:分集不存在');
  7746. }
  7747. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  7748. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  7749. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  7750. // 获取所有片段数据
  7751. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7752. // 收集所有资产名称(角色、场景、道具)
  7753. $product_names = [];
  7754. // 收集角色名称
  7755. foreach ($roles as $role) {
  7756. $role_name = getProp($role, 'role');
  7757. if ($role_name && $role_name != '旁白') {
  7758. $product_names[] = $role_name;
  7759. }
  7760. }
  7761. // 收集场景名称
  7762. foreach ($scenes as $scene) {
  7763. $scene_name = getProp($scene, 'scene');
  7764. if ($scene_name) {
  7765. $product_names[] = $scene_name;
  7766. }
  7767. }
  7768. // 收集道具名称
  7769. foreach ($props as $prop) {
  7770. $prop_name = getProp($prop, 'prop');
  7771. if ($prop_name) {
  7772. $product_names[] = $prop_name;
  7773. }
  7774. }
  7775. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  7776. $product_names = array_unique($product_names);
  7777. usort($product_names, function($a, $b) {
  7778. return mb_strlen($b) - mb_strlen($a);
  7779. });
  7780. try {
  7781. DB::beginTransaction();
  7782. // 处理每个片段
  7783. foreach ($acts as $act) {
  7784. $act_content = getProp($act, 'act_content');
  7785. if (!$act_content) continue;
  7786. $processed_content = $act_content;
  7787. // 统一替换所有资产名称为 {资产名} 格式
  7788. // 使用占位符避免嵌套替换问题
  7789. $placeholder_map = [];
  7790. $placeholder_index = 0;
  7791. foreach ($product_names as $product_name) {
  7792. // 转义特殊字符
  7793. $escaped_product = preg_quote($product_name, '/');
  7794. // 检查是否匹配且未被 {} 包裹
  7795. $processed_content = preg_replace_callback(
  7796. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  7797. function($matches) use (&$placeholder_map, &$placeholder_index) {
  7798. // 使用唯一占位符
  7799. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  7800. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  7801. $placeholder_index++;
  7802. return $placeholder;
  7803. },
  7804. $processed_content
  7805. );
  7806. }
  7807. // 将所有占位符替换回实际内容
  7808. foreach ($placeholder_map as $placeholder => $replacement) {
  7809. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  7810. }
  7811. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  7812. $shot_counter = 0;
  7813. $processed_content = preg_replace_callback(
  7814. '/【(?:镜头|分镜)(\d+)】/u',
  7815. function($matches) use (&$shot_counter) {
  7816. $shot_counter++;
  7817. return '【镜头' . $shot_counter . '】';
  7818. },
  7819. $processed_content
  7820. );
  7821. // 更新数据库
  7822. $boolen = DB::table('mp_episode_segments')
  7823. ->where('id', $act->id)
  7824. ->update([
  7825. 'act_show_content' => $processed_content,
  7826. 'updated_at' => date('Y-m-d H:i:s')
  7827. ]);
  7828. if (!$boolen) {
  7829. Utils::throwError('20003:片段处理失败');
  7830. }
  7831. }
  7832. }catch (\Exception $e) {
  7833. DB::rollBack();
  7834. Utils::throwError('20003:'.$e->getMessage());
  7835. }
  7836. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  7837. 'is_generated' => 1,
  7838. 'updated_at' => date('Y-m-d H:i:s')
  7839. ]);
  7840. if (!$boolen1) {
  7841. DB::rollBack();
  7842. Utils::throwError('20003:分集处理失败!');
  7843. }
  7844. DB::commit();
  7845. // 重新查询更新后的片段数据
  7846. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  7847. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  7848. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  7849. $products = [];
  7850. // 先处理角色数组
  7851. foreach ($roles as $role) {
  7852. $product = $role;
  7853. // 将role字段重命名为product_name
  7854. if (isset($product['role'])) {
  7855. $product['product_name'] = $product['role'];
  7856. unset($product['role']);
  7857. $product['product'] = 1; // 标记类型为角色
  7858. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7859. }
  7860. }
  7861. // 处理场景数组
  7862. foreach ($scenes as $scene) {
  7863. $product = $scene;
  7864. // 将scene字段重命名为product_name
  7865. if (isset($product['scene'])) {
  7866. $product['product_name'] = $product['scene'];
  7867. unset($product['scene']);
  7868. $product['product'] = 2; // 标记类型为场景
  7869. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7870. }
  7871. }
  7872. // 处理道具数组(逻辑与场景一致)
  7873. foreach ($props as $prop) {
  7874. $product = $prop;
  7875. // 将prop字段重命名为product_name
  7876. if (isset($product['prop'])) {
  7877. $product['product_name'] = $product['prop'];
  7878. unset($product['prop']);
  7879. $product['product'] = 3; // 标记类型为道具
  7880. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  7881. }
  7882. }
  7883. // extra_products优先级更高,直接覆盖同名的roles和scenes
  7884. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  7885. foreach ($extra_products as $extra_product) {
  7886. $product_name = getProp($extra_product, 'product_name');
  7887. if ($product_name) {
  7888. $products[$product_name] = $extra_product; // 覆盖同名数据
  7889. }
  7890. }
  7891. // 重新索引数组(去除key)
  7892. $products = array_values($products);
  7893. // 构建返回的acts数组
  7894. $return_acts = [];
  7895. foreach ($acts as $act) {
  7896. $return_acts[] = [
  7897. 'act_id' => getProp($act, 'id'),
  7898. 'act_number' => getProp($act, 'act_number'),
  7899. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  7900. 'act_show_content' => getProp($act, 'act_show_content'),
  7901. 'video_url' => getProp($act, 'video_url'),
  7902. 'video_duration' => getProp($act, 'video_duration'),
  7903. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  7904. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  7905. ];
  7906. }
  7907. return [
  7908. 'anime_id' => getProp($episode, 'anime_id'),
  7909. 'episode_id' => $episode_id,
  7910. 'title' => getProp($episode, 'title'),
  7911. 'episode_number' => getProp($episode, 'episode_number'),
  7912. 'is_generated' => getProp($episode, 'is_generated'),
  7913. 'video_params' => [
  7914. 'video_model' => getProp($episode, 'video_model'),
  7915. 'video_resolution' => getProp($episode, 'video_resolution'),
  7916. 'ratio' => getProp($episode, 'ratio'),
  7917. ],
  7918. 'products' => $products,
  7919. 'acts' => $return_acts
  7920. ];
  7921. }
  7922. }