AnimeService.php 462 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754
  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\Models\MpTaskCenter;
  9. use App\Services\AIGeneration\AIImageGenerationService;
  10. use App\Services\AIGeneration\AIVideoGenerationService;
  11. use App\Services\DeepSeek\DeepSeekService;
  12. use App\Services\PointsService;
  13. use App\Services\TaskCenterService;
  14. use Dflydev\DotAccessData\Util;
  15. use GuzzleHttp\Client;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\Log;
  18. use Illuminate\Support\Facades\Redis;
  19. use OSS\Core\OssException;
  20. use OSS\OssClient;
  21. class AnimeService
  22. {
  23. protected $aiImageGenerationService;
  24. protected $aiVideoGenerationService;
  25. protected $DeepSeekService;
  26. protected $pointsService;
  27. protected $taskCenterService;
  28. private $url;
  29. private $api_key;
  30. private $headers;
  31. public function __construct(
  32. AIImageGenerationService $aiImageGenerationService,
  33. AIVideoGenerationService $aiVideoGenerationService,
  34. DeepSeekService $DeepSeekService,
  35. PointsService $pointsService,
  36. TaskCenterService $taskCenterService
  37. ) {
  38. $this->aiImageGenerationService = $aiImageGenerationService;
  39. $this->aiVideoGenerationService = $aiVideoGenerationService;
  40. $this->DeepSeekService = $DeepSeekService;
  41. $this->pointsService = $pointsService;
  42. $this->taskCenterService = $taskCenterService;
  43. $this->url = 'https://api.deepseek.com/chat/completions';
  44. $this->api_key = env('DEEPSEEK_API_KEY');
  45. $this->headers = [
  46. 'Authorization' => 'Bearer '.$this->api_key,
  47. 'Content-Type' => 'application/json; charset=UTF-8'
  48. ];
  49. }
  50. /**
  51. * 构建统一的分镜数据结构(episodeInfo格式)
  52. * @param array $segments 分镜数据数组
  53. * @return array 返回包含acts和total_duration的数组
  54. */
  55. public function buildEpisodeSegmentsStructure($segments) {
  56. $acts = [];
  57. $totalDuration = 0; // 初始化总时长
  58. foreach($segments as $segment) {
  59. // 计算分镜时长,优先级:video_duration > audio_duration > 默认5秒
  60. $videoDuration = getProp($segment, 'video_duration');
  61. $audioDuration = getProp($segment, 'audio_duration');
  62. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  63. $totalDuration += floatval($videoDuration);
  64. } elseif (!empty($audioDuration) && is_numeric($audioDuration)) {
  65. $totalDuration += floatval($audioDuration);
  66. } else {
  67. $totalDuration += 5; // 默认5秒
  68. }
  69. $segment_content = getProp($segment, 'segment_content');
  70. // 判断是否有尾帧描述,如果有则去掉这部分内容
  71. if (strpos($segment_content, '尾帧') !== false) {
  72. // 使用正则表达式匹配"尾帧"及其后面的内容并移除(s修饰符让.匹配换行符)
  73. $segment_content = preg_replace('/尾帧.*$/s', '', $segment_content);
  74. }
  75. // 构建分镜信息
  76. $segmentInfo = [
  77. 'segment_id' => getProp($segment, 'segment_id'),
  78. 'segment_number' => getProp($segment, 'segment_number'),
  79. 'segment_content' => $segment_content,
  80. 'description' => getProp($segment, 'description'),
  81. 'composition' => getProp($segment, 'composition'),
  82. 'camera_movement' => getProp($segment, 'camera_movement'),
  83. 'voice_actor' => getProp($segment, 'voice_actor'),
  84. 'dialogue' => getProp($segment, 'dialogue'),
  85. 'frame_type' => getProp($segment, 'frame_type'),
  86. 'scene' => getProp($segment, 'scene'),
  87. 'characters' => getProp($segment, 'characters'),
  88. 'tail_frame' => getProp($segment, 'tail_frame'),
  89. 'emotion' => getProp($segment, 'emotion'),
  90. 'emotion_type' => getProp($segment, 'emotion_type'),
  91. 'gender' => getProp($segment, 'gender'),
  92. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  93. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  94. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  95. 'pitch' => getProp($segment, 'pitch'),
  96. 'voice_name' => getProp($segment, 'voice_name'),
  97. 'voice_type' => getProp($segment, 'voice_type'),
  98. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  99. 'img_url' => getProp($segment, 'img_url'),
  100. 'audio_url' => getProp($segment, 'audio_url'),
  101. 'audio_duration' => getProp($segment, 'audio_duration', 0),
  102. 'video_url' => getProp($segment, 'video_url'),
  103. 'video_duration' => getProp($segment, 'video_duration', 0),
  104. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  105. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  106. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  107. 'current_type' => getProp($segment, 'current_type'),
  108. ];
  109. $actNumber = getProp($segment, 'act_number');
  110. if (isset($acts[$actNumber])) {
  111. $acts[$actNumber]['segments'][] = $segmentInfo;
  112. } else {
  113. $acts[$actNumber] = [
  114. 'act_number' => $actNumber,
  115. 'act_title' => getProp($segment, 'act_title'),
  116. 'act_duration' => getProp($segment, 'act_duration'),
  117. 'segments' => [$segmentInfo]
  118. ];
  119. }
  120. }
  121. return [
  122. 'acts' => array_values($acts),
  123. 'total_duration' => intval(round($totalDuration))
  124. ];
  125. }
  126. /**
  127. * 构建统一的分段数据结构(episodeInfoForAce格式)
  128. * @param array $segments 分段数据数组
  129. * @return array 返回包含acts和total_duration的数组
  130. */
  131. public function buildEpisodeActsStructureForAce($segments) {
  132. $acts = [];
  133. $totalDuration = 0; // 初始化总时长
  134. foreach($segments as $segment) {
  135. // 计算分镜时长,优先级:video_duration > act_duration > 默认5秒
  136. $videoDuration = getProp($segment, 'video_duration');
  137. $actDuration = getProp($segment, 'act_duration');
  138. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  139. $totalDuration += floatval($videoDuration);
  140. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  141. $totalDuration += floatval($actDuration);
  142. } else {
  143. $totalDuration += 5; // 默认5秒
  144. }
  145. // 构建分镜信息
  146. $segmentInfo = [
  147. 'act_id' => getProp($segment, 'id'),
  148. 'act_number' => getProp($segment, 'act_number'),
  149. 'act_title' => getProp($segment, 'act_title'),
  150. 'act_duration' => getProp($segment, 'act_duration'),
  151. 'act_content' => getProp($segment, 'act_content'),
  152. 'video_url' => getProp($segment, 'video_url'),
  153. 'video_duration' => getProp($segment, 'video_duration', 0),
  154. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  155. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  156. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  157. 'current_type' => getProp($segment, 'current_type'),
  158. ];
  159. $acts[] = $segmentInfo;
  160. }
  161. return [
  162. 'acts' => array_values($acts),
  163. 'total_duration' => intval(round($totalDuration))
  164. ];
  165. }
  166. /**
  167. * 验证画面比例是否有效
  168. * @param string $ratio 画面比例
  169. * @return bool
  170. */
  171. public function validateRatio($ratio) {
  172. return isset(BaseConst::IMAGE_RATIOS[$ratio]);
  173. }
  174. /**
  175. * 获取画面比例对应的宽高
  176. * @param string $ratio 画面比例
  177. * @return array ['width' => int, 'height' => int]
  178. * @throws \Exception
  179. */
  180. private function getRatioDimensions($ratio) {
  181. if ($ratio && !$this->validateRatio($ratio)) {
  182. $validRatios = implode('、', array_keys(BaseConst::IMAGE_RATIOS));
  183. Utils::throwError("1002:画面比例选择不正确,只支持{$validRatios}");
  184. }
  185. return isset(BaseConst::IMAGE_RATIOS[$ratio]) ? BaseConst::IMAGE_RATIOS[$ratio] : ['width' => 1600, 'height' => 2848];
  186. }
  187. public function createAnime($data) {
  188. $uid = Site::getUid();
  189. $cpid = Site::getCpid();
  190. $input_art_style = getProp($data, 'art_style');
  191. $file = getProp($data, 'file');
  192. $content = getProp($data, 'content', '');
  193. $bid = getProp($data, 'bid', 0);
  194. $script_id = getProp($data, 'script_id', 0);
  195. $ace_mode = getProp($data, 'ace_mode', 0);
  196. $extra_products = getProp($data, 'products', []);
  197. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  198. if (!is_array($extra_products)) {
  199. Utils::throwError('20003:传入的资产格式不正确');
  200. }
  201. // 替换美术风格
  202. $mappedArtStyle = $this->DeepSeekService->getArtStylePromptByInput($input_art_style);
  203. // 提取文件内容
  204. if ($file) {
  205. $content = $this->DeepSeekService->extractFileContent($file);
  206. if (!$content) {
  207. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  208. }
  209. } elseif ($script_id) {
  210. $content = $this->DeepSeekService->getContentByScriptId($script_id);
  211. if (!$content) {
  212. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  213. }
  214. } elseif ($bid) {
  215. $content = $this->DeepSeekService->getContentByBid($bid);
  216. if (!$content) {
  217. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  218. }
  219. } elseif ($content) {
  220. $content = filterContent($content);
  221. }else {
  222. $content = '';
  223. }
  224. $anime_data = [
  225. 'user_id' => $uid,
  226. 'cpid' => $cpid,
  227. 'anime_name' => '新剧本策划',
  228. 'is_multi' => getProp($data, 'is_multi', 1),
  229. 'content' => $content,
  230. 'art_style_type' => $input_art_style,
  231. 'ace_mode' => $ace_mode,
  232. 'script_id' => $script_id,
  233. 'extra_products' => json_encode($extra_products, 256),
  234. 'created_at' => date('Y-m-d H:i:s'),
  235. 'updated_at' => date('Y-m-d H:i:s'),
  236. ];
  237. // 处理文本模型
  238. $model = getProp($data, 'model');
  239. if (!$model) {
  240. // 用户没有输入,使用默认值
  241. $model = 'deepseek-v4-pro';
  242. }
  243. // 验证模型是否在可用模型表中
  244. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  245. $model = 'deepseek-v4-pro';
  246. }
  247. $anime_data['model'] = $model;
  248. if ($mappedArtStyle) $anime_data['art_style'] = $mappedArtStyle;
  249. return DB::table('mp_animes')->insertGetId($anime_data);
  250. }
  251. public function chatList($data) {
  252. $uid = Site::getUid();
  253. $anime_name = getProp($data, 'anime_name');
  254. $query = DB::table('mp_animes')->where('is_deleted', 0)->where('user_id', $uid);
  255. if ($anime_name) {
  256. $query->where('anime_name', 'like', "%$anime_name%");
  257. }
  258. return $query->orderBy('id', 'desc')->paginate();
  259. }
  260. public function chatHistory($data) {
  261. $anime_id = getProp($data, 'anime_id');
  262. $sequence = getProp($data, 'sequence', 0);
  263. if (!$anime_id) Utils::throwError('20003:请选择对话!');
  264. $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)
  265. ->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');
  266. return $query->orderBy('ar.id')->get()->map(function ($value) {
  267. $value = (array)$value;
  268. if ($value['role'] == 'assistant') $value['content'] = filterScriptContent($value['content']);
  269. $value['created_at'] = transDate($value['created_at']);
  270. $value['episode_created_at'] = transDate($value['episode_created_at']);
  271. return $value;
  272. })->toArray();
  273. }
  274. public function batchSetRoleImg($data) {
  275. $episode_id = getProp($data, 'episode_id');
  276. if (!$episode_id) Utils::throwError('1002:请选择分集');
  277. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  278. $roles = json_decode(getProp($data, 'roles'), true) ?: [];
  279. $art_style = getProp($episode, 'art_style');
  280. $anime_id = getProp($episode, 'anime_id');
  281. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  282. $art_style_type = getProp($anime, 'art_style_type');
  283. $character_prefix = '';
  284. $scene_prefix = '';
  285. if ($art_style_type) {
  286. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  287. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  288. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  289. }
  290. foreach ($roles as &$role) {
  291. $role_name = getProp($role, 'role');
  292. if ($role_name == '旁白') continue;
  293. // 优先使用 pic_prompt,如果没有则使用 description
  294. $pic_prompt = getProp($role, 'pic_prompt');
  295. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  296. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  297. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  298. // 参考图地址
  299. $ref_img_url = getProp($role, 'url');
  300. if ($ref_img_url) continue; // 已有图片则跳过
  301. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  302. try {
  303. $params = [
  304. 'prompt' => $description,
  305. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  306. ];
  307. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  308. $task_id = $task->id;
  309. if (!$task_id) {
  310. Utils::throwError("20003:角色({$role_name})生成图片失败");
  311. }
  312. $role['task_id'] = $task_id;
  313. $role['task_status'] = 'processing';
  314. } catch (\Exception $e) {
  315. logDB('anime', 'error', "角色({$role_name})生成图片失败", ['error' => $e->getMessage()]);
  316. Utils::throwError("20003:" . $e->getMessage());
  317. }
  318. }
  319. // 保存角色信息
  320. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  321. 'roles' => json_encode($roles, 256),
  322. 'generate_status' => '执行中',
  323. 'generate_at' => date('Y-m-d H:i:s'),
  324. 'updated_at' => date('Y-m-d H:i:s')
  325. ]);
  326. if (!$boolen) {
  327. Utils::throwError('20003:保存角色信息失败');
  328. }
  329. return $boolen;
  330. }
  331. public function batchSetSceneImg($data) {
  332. $episode_id = getProp($data, 'episode_id');
  333. if (!$episode_id) Utils::throwError('1002:请选择分集');
  334. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  335. $scenes = json_decode(getProp($episode, 'scenes'), true);
  336. $art_style = getProp($episode, 'art_style');
  337. $target_scene = getProp($data, 'target_scene');
  338. $anime_id = getProp($episode, 'anime_id');
  339. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  340. $art_style_type = getProp($anime, 'art_style_type');
  341. $character_prefix = '';
  342. $scene_prefix = '';
  343. if ($art_style_type) {
  344. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  345. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  346. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  347. }
  348. foreach ($scenes as &$scene) {
  349. $scene_name = getProp($scene, 'scene');
  350. if ($scene_name != $target_scene) continue;
  351. // 优先使用 pic_prompt,如果没有则使用 description
  352. $pic_prompt = getProp($scene, 'pic_prompt');
  353. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  354. // if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  355. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  356. // 参考图地址
  357. $ref_img_url = getProp($scene, 'url');
  358. if ($ref_img_url) continue; // 已有图片则跳过
  359. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  360. try {
  361. $params = [
  362. 'prompt' => $description,
  363. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  364. ];
  365. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  366. $task_id = $task->id;
  367. if (!$task_id) {
  368. Utils::throwError("20003:场景({$scene_name})生成图片失败");
  369. }
  370. $scene['task_id'] = $task_id;
  371. $scene['task_status'] = 'processing';
  372. } catch (\Exception $e) {
  373. logDB('anime', 'error', "场景({$scene_name})生成图片失败", ['error' => $e->getMessage()]);
  374. Utils::throwError("20003:" . $e->getMessage());
  375. }
  376. }
  377. // 保存场景信息
  378. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  379. 'scenes' => json_encode($scenes, 256),
  380. 'generate_status' => '执行中',
  381. 'generate_at' => date('Y-m-d H:i:s'),
  382. 'updated_at' => date('Y-m-d H:i:s')
  383. ]);
  384. if (!$boolen) {
  385. Utils::throwError('20003:保存角色信息失败');
  386. }
  387. return $boolen;
  388. }
  389. public function editAnime($data) {
  390. $anime_id = getProp($data, 'anime_id');
  391. $anime_name = trim(getProp($data, 'anime_name'));
  392. // 确认对话名称唯一性
  393. if ($id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  394. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  395. }
  396. if (!$anime_id || !$anime_name) {
  397. Utils::throwError('20003:参数异常');
  398. }
  399. return DB::table('mp_animes')->where('id', $anime_id)->update([
  400. 'anime_name' => $anime_name,
  401. 'updated_at' => date('Y-m-d H:i:s')
  402. ]);
  403. // $script_arr =getProp($data, 'script', []);
  404. // if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  405. // $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  406. // $anime_id = getProp($data, 'anime_id');
  407. // try {
  408. // DB::beginTransaction();
  409. // $table_data = [
  410. // 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  411. // 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  412. // 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  413. // 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  414. // 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  415. // 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  416. // 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  417. // 'status' => 3,
  418. // 'start_episode_sequence' => $start_episode_sequence,
  419. // 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  420. // 'episode_num' => count($script_arr['episodes']),
  421. // 'updated_at' => date('Y-m-d H:i:s')
  422. // ];
  423. // // 保存剧本内容
  424. // if (!empty($anime_id)) {
  425. // $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  426. // if (!$boolen) {
  427. // dLog('anime')->info('对话保存失败', $table_data);
  428. // Utils::throwError('20003:对话保存失败');
  429. // }
  430. // }else {
  431. // $table['created_at'] = $table_data['updated_at'];
  432. // $anime_id = DB::table('mp_animes')->insertGetId($table_data);
  433. // if (!$anime_id) {
  434. // dLog('anime')->info('对话保存失败', $table_data);
  435. // Utils::throwError('20003:对话保存失败');
  436. // }
  437. // }
  438. // // 保存分集内容
  439. // // 删除历史分集内容
  440. // $boolen1 = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->delete();
  441. // $episodes = [];
  442. // $sequence = 1;
  443. // foreach ($script_arr['episodes'] as $episode) {
  444. // $segment_number = 1;
  445. // foreach($episode['segments'] as $segment) {
  446. // $episodes[] = [
  447. // 'anime_id' => $anime_id,
  448. // 'episode_number' => $episode['episode_number'],
  449. // 'title' => $episode['title'],
  450. // // 'content' => $episode['content'],
  451. // 'content' => '',
  452. // 'segment_number' => $segment_number,
  453. // 'segment_content' => $segment['segment_content'],
  454. // 'sequence' => $sequence,
  455. // 'created_at' => date('Y-m-d H:i:s'),
  456. // 'updated_at' => date('Y-m-d H:i:s')
  457. // ];
  458. // $sequence++;
  459. // $segment_number++;
  460. // }
  461. // }
  462. // $boolen2 = DB::table('mp_anime_episodes')->insert($episodes);
  463. // if (!$boolen2) {
  464. // dLog('deepseek')->info('分集内容保存失败', $episodes);
  465. // logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  466. // Utils::throwError('20003:分集内容保存失败');
  467. // }
  468. // } catch (\Exception $e) {
  469. // DB::rollBack();
  470. // Utils::throwError('20003:'.$e->getMessage());
  471. // }
  472. // DB::commit();
  473. // return true;
  474. }
  475. public function delAnime($data) {
  476. $anime_id = getProp($data, 'anime_id');
  477. if (!$anime_id) {
  478. Utils::throwError('20003:请选择剧本');
  479. }
  480. return DB::table('mp_animes')->where('id', $anime_id)->update([
  481. 'is_deleted' => 1,
  482. 'updated_at' => date('Y-m-d H:i:s')
  483. ]);
  484. }
  485. public function animeDetail($data) {
  486. $uid = Site::getUid();
  487. $anime_id = getProp($data, 'anime_id');
  488. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->where('user_id', $uid)
  489. ->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();
  490. if (!$anime) Utils::throwError('20003:权限不足');
  491. $anime = (array)$anime;
  492. $anime['roles'] = json_decode($anime['roles']);
  493. $anime['scenes'] = json_decode($anime['scenes']);
  494. // 获取分集信息
  495. $episodes = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('is_default', 1)
  496. ->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"))
  497. ->orderBy('episode_number')->get()->map(function ($value) {
  498. return (array)$value;
  499. })->toArray();
  500. $anime['episodes'] = $episodes;
  501. // 获取当前仍在批量生成中的剧集任务(只展示 episodes 中尚未出现的剧集序号)
  502. $episodeNumbers = array_map('intval', array_column($episodes, 'episode_number'));
  503. $episodeTasks = DB::table('mp_batch_episode_generation_details')
  504. ->where('anime_id', $anime_id)
  505. ->whereIn('status', ['pending', 'processing']) // 只获取待生成/生成中任务,已完成或失败的不显示
  506. ->orderBy('episode_number')
  507. ->get()
  508. ->map(function ($task) use ($episodeNumbers) {
  509. if (in_array((int)$task->episode_number, $episodeNumbers, true)) {
  510. return null;
  511. }
  512. return [
  513. 'episode_number' => (int)$task->episode_number,
  514. 'status' => $task->status,
  515. 'error_message' => '',
  516. ];
  517. })
  518. ->filter()
  519. ->values()
  520. ->toArray();
  521. $anime['episode_tasks'] = $episodeTasks;
  522. return $anime;
  523. }
  524. public function episodeInfo($data) {
  525. $uid = Site::getUid();
  526. $anime_id = getProp($data, 'anime_id');
  527. $episode_id = getProp($data, 'episode_id');
  528. if (!$anime_id || !$episode_id) {
  529. Utils::throwError('1002:请选择剧集');
  530. }
  531. // 验证用户权限
  532. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('user_id', $uid)->where('is_deleted', 0)->first();
  533. if (!$anime) Utils::throwError('20003:权限不足');
  534. $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();
  535. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  536. $episode = (array)$episode;
  537. $episode['roles'] = json_decode($episode['roles'], true);
  538. // foreach($episode['roles'] as &$item) {
  539. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  540. // }
  541. $episode['scenes'] = json_decode($episode['scenes'], true);
  542. // foreach($episode['scenes'] as &$item) {
  543. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  544. // }
  545. // 获取分镜信息
  546. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  547. ->select('*')->get()->map(function ($value) {
  548. return (array)$value;
  549. })->toArray();
  550. // 使用公共方法构建分镜结构
  551. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  552. $episode['acts'] = $segmentsStructure['acts'];
  553. $episode['total_duration'] = $segmentsStructure['total_duration'];
  554. return $episode;
  555. }
  556. public function episodeInfoForAce($data) {
  557. $anime_id = getProp($data, 'anime_id');
  558. $episode_id = getProp($data, 'episode_id');
  559. if (!$anime_id || !$episode_id) {
  560. Utils::throwError('1002:请选择剧集');
  561. }
  562. $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();
  563. if (!$episode) Utils::throwError('20003:该剧集不存在!');
  564. $episode = (array)$episode;
  565. $episode['roles'] = json_decode($episode['roles'], true);
  566. // foreach($episode['roles'] as &$item) {
  567. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 11) != '写实。全景,正面拍摄。') $item['pic_prompt'] = '写实。全景,正面拍摄。'.$item['pic_prompt'];
  568. // }
  569. $episode['scenes'] = json_decode($episode['scenes'], true);
  570. // foreach($episode['scenes'] as &$item) {
  571. // if (isset($item['pic_prompt']) && mb_substr($item['pic_prompt'], 0, 3) != '写实。') $item['pic_prompt'] = '写实。'.$item['pic_prompt'];
  572. // }
  573. $episode['props'] = $episode['props'] ? json_decode($episode['props'], true) : [];
  574. // 获取分镜信息
  575. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('act_number')
  576. ->select('*')->get()->map(function ($value) {
  577. return (array)$value;
  578. })->toArray();
  579. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  580. $episode['acts'] = $segmentsStructure['acts'];
  581. $episode['total_duration'] = $segmentsStructure['total_duration'];
  582. // 获取mp_animes表中的视频参数
  583. $anime = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  584. $episode['video_params'] = [
  585. 'video_model' => getProp($anime, 'video_model'),
  586. 'video_resolution' => getProp($anime, 'video_resolution'),
  587. 'ratio' => getProp($anime, 'video_ratio'),
  588. ];
  589. return $episode;
  590. }
  591. public function segmentInfo($data) {
  592. $uid = Site::getUid();
  593. $segment_id = getProp($data, 'segment_id');
  594. if (!$segment_id) {
  595. Utils::throwError('1002:请选择分镜');
  596. }
  597. // 获取分镜信息
  598. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  599. // 验证用户权限
  600. if ($segment) {
  601. $anime = DB::table('mp_animes')->where('id', getProp($segment, 'anime_id'))->where('user_id', $uid)->where('is_deleted', 0)->first();
  602. if (!$anime) Utils::throwError('20003:权限不足');
  603. }
  604. $result = [
  605. 'segment_id' => getProp($segment, 'segment_id'),
  606. 'segment_number' => getProp($segment, 'segment_number'),
  607. 'segment_content' => getProp($segment, 'segment_content'),
  608. 'description' => getProp($segment, 'description'),
  609. 'composition' => getProp($segment, 'composition'),
  610. 'camera_movement' => getProp($segment, 'camera_movement'),
  611. 'voice_actor' => getProp($segment, 'voice_actor'),
  612. 'dialogue' => getProp($segment, 'dialogue'),
  613. 'frame_type' => getProp($segment, 'frame_type'),
  614. 'scene' => getProp($segment, 'scene'),
  615. 'characters' => getProp($segment, 'characters'),
  616. 'tail_frame' => getProp($segment, 'tail_frame'),
  617. 'emotion' => getProp($segment, 'emotion'),
  618. 'emotion_type' => getProp($segment, 'emotion_type'),
  619. 'gender' => getProp($segment, 'gender'),
  620. 'speed_ratio' => getProp($segment, 'speed_ratio'),
  621. 'loudness_ratio' => getProp($segment, 'loudness_ratio'),
  622. 'emotion_scale' => getProp($segment, 'emotion_scale'),
  623. 'pitch' => getProp($segment, 'pitch'),
  624. 'voice_name' => getProp($segment, 'voice_name'),
  625. 'voice_type' => getProp($segment, 'voice_type'),
  626. 'voice_audio_url' => getProp($segment, 'voice_audio_url'),
  627. 'img_url' => getProp($segment, 'img_url'),
  628. 'video_url' => getProp($segment, 'video_url'),
  629. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  630. ];
  631. return $result;
  632. }
  633. public function copyEpisodeVersion($data) {
  634. $episode_id = getProp($data, 'episode_id');
  635. $uid = Site::getUid();
  636. $cpid = Site::getCpid();
  637. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  638. if (!$episode) Utils::throwError('20003:该剧集不存在');
  639. $episode = (array)$episode;
  640. $anime_id = $episode['anime_id'];
  641. $episode_number = $episode['episode_number'];
  642. $count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->count('id');
  643. $sequence = $count + 1;
  644. unset($episode['id']);
  645. $now = date('Y-m-d H:i:s');
  646. $episode['created_at'] = $now;
  647. $episode['updated_at'] = $now;
  648. $episode['is_default'] = 1;
  649. // 获取版本中含有"(副本"字样的个数
  650. $copy_count = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('title', 'like', '%(副本%')->count('id');
  651. $episode['title'] = $copy_count > 0 ? $episode['title']."(副本{$copy_count})" : $episode['title']."(副本)"; // 生成带(副本)字样的标题
  652. $episode['sequence'] = $sequence;
  653. $episode['is_generated'] = 0;
  654. $episode['cpid'] = $cpid;
  655. // 获取ace_mode
  656. $ace_mode = DB::table('mp_animes')->where('id', $anime_id)->value('ace_mode');
  657. try {
  658. DB::beginTransaction();
  659. DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->update(['is_default' => 0, 'updated_at'=>$now]);
  660. // 新增副本
  661. $new_episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  662. if (!$new_episode_id) {
  663. Utils::throwError('20003:创建副本失败!');
  664. }
  665. // 获取分镜数据并准备插入
  666. $segments_for_insert = DB::table('mp_episode_segments')
  667. ->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')
  668. ->where('episode_id', $episode_id)->orderBy('segment_number')->get()->map(function($item) use ($new_episode_id,$ace_mode) {
  669. $item = (array)$item;
  670. $item['episode_id'] = $new_episode_id;
  671. if ((int)$ace_mode !== 1) $item['segment_id'] = date('YmdHis').mt_rand(1000,9999).str_pad($item['segment_number'], 3, "0", STR_PAD_LEFT);
  672. $item['created_at'] = $item['updated_at'] = date('Y-m-d H:i:s');
  673. return $item;
  674. })->toArray();
  675. // 写入分镜数据
  676. $boolen2 = DB::table('mp_episode_segments')->insert($segments_for_insert);
  677. if (!$boolen2) {
  678. Utils::throwError('20003:写入分镜数据失败!');
  679. }
  680. // 写入对话历史
  681. $records = [
  682. [
  683. 'uid' => $uid,
  684. 'anime_id' => $anime_id,
  685. 'role' => 'user',
  686. 'content' => '创建副本',
  687. 'sequence' => $episode_number,
  688. 'episode_id' => $new_episode_id,
  689. 'created_at' => $now,
  690. 'updated_at' => $now
  691. ],
  692. [
  693. 'uid' => $uid,
  694. 'anime_id' => $anime_id,
  695. 'role' => 'assistant',
  696. 'content' => '好的,已为您创建副本',
  697. 'sequence' => $episode_number,
  698. 'episode_id' => $new_episode_id,
  699. 'created_at' => $now,
  700. 'updated_at' => $now
  701. ]
  702. ];
  703. $boolen3 = DB::table('mp_anime_records')->insert($records);
  704. if (!$boolen3) {
  705. Utils::throwError('20003:对话记录保存失败');
  706. }
  707. }catch (\Exception $e) {
  708. DB::rollBack();
  709. Utils::throwError('20003:'.$e->getMessage());
  710. }
  711. DB::commit();
  712. // 构建与 episodeInfo 方法一致的返回数据结构
  713. $result = [
  714. 'episode_id' => $new_episode_id,
  715. 'anime_id' => $anime_id,
  716. 'episode_number' => $episode_number,
  717. 'title' => $episode['title'],
  718. 'intro' => $episode['intro'],
  719. 'art_style' => $episode['art_style'],
  720. 'roles' => json_decode($episode['roles'], true),
  721. 'scenes' => json_decode($episode['scenes'], true),
  722. 'is_generated' => (int)$episode['is_generated']
  723. ];
  724. if ((int)$ace_mode === 1) {
  725. // 获取分镜信息
  726. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $new_episode_id)->orderBy('act_number')
  727. ->select('*')->get()->map(function ($value) {
  728. return (array)$value;
  729. })->toArray();
  730. $segmentsStructure = $this->buildEpisodeActsStructureForAce($segments);
  731. }else {
  732. // 复用已有的分镜数据,按 act 分组(避免重复查询数据库)
  733. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments_for_insert);
  734. }
  735. $result['acts'] = $segmentsStructure['acts'];
  736. $result['total_duration'] = $segmentsStructure['total_duration'];
  737. return $result;
  738. }
  739. public function episodeVersions($data) {
  740. $anime_id = getProp($data, 'anime_id');
  741. $episode_id = getProp($data, 'episode_id');
  742. if (!$anime_id || !$episode_id) {
  743. Utils::throwError('1002:请选择剧集');
  744. }
  745. $episode_number = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('id', $episode_id)->value('episode_number');
  746. $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) {
  747. return (array)$value;
  748. })->toArray();
  749. if (!$episodes) Utils::throwError('20003:该剧集不存在!');
  750. foreach($episodes as &$episode) {
  751. $episode['version'] = 'V'.$episode['sequence'];
  752. $episode['roles'] = json_decode($episode['roles'], true);
  753. $episode['scenes'] = json_decode($episode['scenes'], true);
  754. // 获取分镜信息
  755. $segments = DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', getProp($episode, 'episode_id'))->orderBy('segment_number')
  756. ->select('*')->get()->map(function ($value) {
  757. return (array)$value;
  758. })->toArray();
  759. // 使用公共方法构建分镜结构
  760. $segmentsStructure = $this->buildEpisodeSegmentsStructure($segments);
  761. $episode['acts'] = $segmentsStructure['acts'];
  762. $episode['total_duration'] = $segmentsStructure['total_duration'];
  763. }
  764. return $episodes;
  765. }
  766. public function bindEpisodeVersion($data) {
  767. $episode_id = getProp($data, 'episode_id');
  768. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  769. if (!$episode) Utils::throwError('20003:该剧集不存在');
  770. $episode = (array)$episode;
  771. if ((int)$episode['is_default'] === 1) return true;
  772. try {
  773. DB::beginTransaction();
  774. // 移除is_default标志
  775. $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')]);
  776. if (!$boolen) {
  777. Utils::throwError('20003:更新失败!');
  778. }
  779. // 绑定副本
  780. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['is_default' => 1, 'updated_at'=>date('Y-m-d H:i:s')]);
  781. if (!$boolen2) {
  782. Utils::throwError('20003:绑定失败!');
  783. }
  784. }catch (\Exception $e) {
  785. DB::rollBack();
  786. Utils::throwError('20003:'.$e->getMessage());
  787. }
  788. DB::commit();
  789. return true;
  790. }
  791. public function chatChangeImg($data) {
  792. $segment_id = getProp($data, 'segment_id');
  793. $type = getProp($data, 'type', 1); // 类型: 1.对话改图 2.图片生成
  794. $prompt = getProp($data, 'prompt');
  795. if (!$prompt || !$segment_id) {
  796. Utils::throwError('1002:请输入提示词,并且选择分镜');
  797. }
  798. $segment = DB::table("mp_episode_segments")->where('segment_id', $segment_id)->first();
  799. if (!$segment) Utils::throwError('20003:该分镜不存在!');
  800. if ((int)$type === 1) $ref_img_url = getProp($segment, 'img_url');
  801. else $ref_img_url = '';
  802. // $ref_img_url = '';
  803. if (empty($prompt)) {
  804. if (empty($ref_img_url)) {
  805. $prompt = getProp($segment, 'segment_content');
  806. }else {
  807. $prompt = '请根据图片生成';
  808. }
  809. }
  810. $anime_id = getProp($segment, 'anime_id');
  811. $episode_id = getProp($segment, 'episode_id');
  812. $episode_number = getProp($segment, 'episode_number');
  813. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  814. $ratio = getProp($data, 'ratio');
  815. if (!$ratio) {
  816. $ratio = getProp($episode, 'ratio');
  817. if (!$ratio) $ratio = '9:16';
  818. }
  819. $art_style = getProp($episode, 'art_style');
  820. if ($art_style) {
  821. $prompt = "美术风格:{$art_style}\n{$prompt}";
  822. }
  823. $dimensions = $this->getRatioDimensions($ratio);
  824. $width = $dimensions['width'];
  825. $height = $dimensions['height'];
  826. try {
  827. $params = [
  828. 'alias_segment_id' => $segment_id,
  829. 'prompt' => $prompt,
  830. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  831. 'width' => $width,
  832. 'height' => $height
  833. ];
  834. // 优化提示词(不要生成字幕)
  835. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  836. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  837. $task_id = $task->id;
  838. if (!$task_id) {
  839. Utils::throwError("20003:生成图片失败");
  840. }
  841. // 更新任务ID
  842. $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')]);
  843. if (!$boolen) Utils::throwError('20003:更新任务ID失败');
  844. } catch (\Exception $e) {
  845. Utils::throwError("20003:" . $e->getMessage());
  846. }
  847. // 创建任务之后先暂停10s等待异步任务完成
  848. sleep(10);
  849. $img_url = $this->loopGetPicTaskResult($task_id);
  850. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  851. // 图片生成后新增对话记录
  852. try {
  853. $uid = Site::getUid();
  854. $now = date('Y-m-d H:i:s');
  855. // 使用AI反推图片提示词
  856. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  857. // 保存对话记录
  858. $records = [
  859. [
  860. 'uid' => $uid,
  861. 'anime_id' => $anime_id,
  862. 'sequence' => $episode_number,
  863. 'role' => 'user',
  864. 'content' => $prompt,
  865. 'segment_id' => $segment_id,
  866. 'pic_task_id' => $task_id,
  867. 'image_url' => '',
  868. 'created_at' => $now,
  869. 'updated_at' => $now
  870. ],
  871. [
  872. 'uid' => $uid,
  873. 'anime_id' => $anime_id,
  874. 'sequence' => $episode_number,
  875. 'role' => 'assistant',
  876. 'content' => $pic_prompt,
  877. 'segment_id' => $segment_id,
  878. 'pic_task_id' => $task_id,
  879. 'image_url' => $img_url,
  880. 'created_at' => $now,
  881. 'updated_at' => $now
  882. ]
  883. ];
  884. DB::table('mp_anime_records')->insert($records);
  885. } catch (\Exception $e) {
  886. // 记录日志但不影响主流程
  887. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  888. 'segment_id' => $segment_id,
  889. 'img_url' => $img_url
  890. ]);
  891. logDB('anime', 'error', '保存对话记录失败', [
  892. 'segment_id' => $segment_id,
  893. 'img_url' => $img_url,
  894. 'error' => $e->getMessage()
  895. ]);
  896. }
  897. return $img_url;
  898. }
  899. public function segmentChatHistory($data) {
  900. $segment_id = getProp($data, 'segment_id');
  901. if (!$segment_id) Utils::throwError('20003:请选择分镜!');
  902. $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');
  903. $chat = $query->orderBy('id')->get()->map(function ($value) {
  904. $value = (array)$value;
  905. $value['created_at'] = transDate($value['created_at']);
  906. return $value;
  907. })->toArray();
  908. // 获取历史图片
  909. $url = [];
  910. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  911. foreach($pic_history as $task) {
  912. $result_url = getProp($task, 'result_url');
  913. if (is_json($result_url)) {
  914. $url = array_merge($url, json_decode($result_url, true));
  915. }else {
  916. $url[] = $result_url;
  917. }
  918. }
  919. // 获取历史视频
  920. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  921. foreach($video_history as $task) {
  922. $result_url = getProp($task, 'compressed_url');
  923. if (is_json($result_url)) {
  924. $url = array_merge($url, json_decode($result_url, true));
  925. }else {
  926. $url[] = $result_url;
  927. }
  928. }
  929. return compact('chat', 'url');
  930. }
  931. public function changeEpisodeRoles($data) {
  932. $anime_id = getProp($data, 'anime_id');
  933. $episode_id = getProp($data, 'episode_id');
  934. $target_roles = getProp($data, 'roles');
  935. $is_deleted = getProp($data, 'is_deleted', 0);
  936. // 参数验证
  937. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  938. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  939. if (!$target_roles) Utils::throwError('20003:请提供角色信息');
  940. // 验证剧集是否存在
  941. $episode = DB::table('mp_anime_episodes')
  942. ->where('anime_id', $anime_id)
  943. ->where('id', $episode_id)
  944. ->first();
  945. if (!$episode) Utils::throwError('20003:该剧集不存在');
  946. $roles = json_decode(getProp($episode, 'roles'), true);
  947. // 获取anime信息,检查是否有关联的script_id
  948. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  949. if (!$anime) Utils::throwError('20003:动漫不存在');
  950. $script_id = getProp($anime, 'script_id');
  951. $episode_number = getProp($episode, 'episode_number', 1);
  952. $uid = Site::getUid();
  953. $cpid = Site::getCpid();
  954. try {
  955. $target_role_name = getProp($target_roles, 'role');
  956. if (empty($target_role_name)) {
  957. Utils::throwError('20003:角色名称不能为空');
  958. }
  959. // 如果是删除操作
  960. if ($is_deleted == 1) {
  961. // 从角色列表中移除该角色
  962. $roles = array_values(array_filter($roles, function($role) use ($target_role_name) {
  963. return getProp($role, 'role') !== $target_role_name;
  964. }));
  965. // 更新角色列表
  966. $result = DB::table('mp_anime_episodes')
  967. ->where('anime_id', $anime_id)
  968. ->where('id', $episode_id)
  969. ->update([
  970. 'roles' => json_encode($roles, 256),
  971. 'updated_at' => date('Y-m-d H:i:s')
  972. ]);
  973. if ($result === false) {
  974. Utils::throwError('20003:删除角色失败');
  975. }
  976. } else {
  977. // 新增或更新操作
  978. $role_found = false;
  979. $is_new_role = false;
  980. // 查找并更新已存在的角色
  981. foreach($roles as &$role) {
  982. if (getProp($role, 'role') === $target_role_name) {
  983. $role = $target_roles;
  984. $role_found = true;
  985. break;
  986. }
  987. }
  988. // 如果角色不存在,则新增
  989. if (!$role_found) {
  990. $roles[] = $target_roles;
  991. $is_new_role = true;
  992. }
  993. // 更新角色列表
  994. $result = DB::table('mp_anime_episodes')
  995. ->where('anime_id', $anime_id)
  996. ->where('id', $episode_id)
  997. ->update([
  998. 'roles' => json_encode($roles, 256),
  999. 'updated_at' => date('Y-m-d H:i:s')
  1000. ]);
  1001. if ($result === false) {
  1002. Utils::throwError('20003:更新角色列表失败');
  1003. }
  1004. // 同步更新分镜表中对应主体的音色信息
  1005. $voice_name = getProp($target_roles, 'voice_name');
  1006. $voice_type = getProp($target_roles, 'voice_type');
  1007. $voice_audio_url = getProp($target_roles, 'voice_audio_url');
  1008. DB::table('mp_episode_segments')
  1009. ->where('anime_id', $anime_id)
  1010. ->where('episode_id', $episode_id)
  1011. ->where('voice_actor', $target_role_name)
  1012. ->update([
  1013. 'voice_name' => $voice_name,
  1014. 'voice_type' => $voice_type,
  1015. 'voice_audio_url' => $voice_audio_url,
  1016. 'updated_at' => date('Y-m-d H:i:s')
  1017. ]);
  1018. // 如果有关联的script_id,则同步到mp_products表
  1019. if ($script_id) {
  1020. // 查询剧本信息
  1021. $script = DB::table('mp_scripts')
  1022. ->where('id', $script_id)
  1023. ->where('is_deleted', 0)
  1024. ->first();
  1025. if ($script) {
  1026. $script_name = $script->script_name ?? 'script_' . $script_id;
  1027. $product_name = getProp($target_roles, 'role');
  1028. $pic_prompt = getProp($target_roles, 'pic_prompt', '');
  1029. $url = getProp($target_roles, 'url', '');
  1030. $product_type = 1; // 1=角色
  1031. // 查找或创建以script_name命名的文件夹
  1032. $folder = DB::table('mp_products')
  1033. ->where('cpid', $cpid)
  1034. ->where('type', 2) // 文件夹类型
  1035. ->where('product', $product_type) // 角色类型
  1036. ->where('product_name', $script_name)
  1037. ->where('parent_id', 0)
  1038. ->where('is_deleted', 0)
  1039. ->first();
  1040. if (!$folder) {
  1041. // 创建文件夹
  1042. $folder_id = DB::table('mp_products')->insertGetId([
  1043. 'user_id' => $uid,
  1044. 'cpid' => $cpid,
  1045. 'type' => 2, // 文件夹
  1046. 'product' => $product_type, // 角色类型
  1047. 'parent_id' => 0,
  1048. 'level' => 1,
  1049. 'product_name' => $script_name,
  1050. 'sort_order' => time(),
  1051. 'is_deleted' => 0,
  1052. 'created_at' => date('Y-m-d H:i:s'),
  1053. 'updated_at' => date('Y-m-d H:i:s')
  1054. ]);
  1055. } else {
  1056. $folder_id = $folder->id;
  1057. }
  1058. // 查找该文件夹下是否已存在同名资产
  1059. $existing_product = DB::table('mp_products')
  1060. ->where('cpid', $cpid)
  1061. ->where('type', 1) // 资产类型
  1062. ->where('product', $product_type)
  1063. ->where('parent_id', $folder_id)
  1064. ->where('product_name', $product_name)
  1065. ->where('is_deleted', 0)
  1066. ->first();
  1067. if ($existing_product) {
  1068. // 更新已存在的资产
  1069. $updateData = [
  1070. 'pic_task_status' => '生成成功',
  1071. ];
  1072. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1073. if ($url) $updateData['url'] = $url;
  1074. // 处理versions字段
  1075. $versions = getProp($target_roles, 'versions', []);
  1076. if ($versions && is_array($versions)) {
  1077. $updateData['versions'] = json_encode($versions, 256);
  1078. }
  1079. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1080. DB::table('mp_products')
  1081. ->where('id', $existing_product->id)
  1082. ->update($updateData);
  1083. $product_id = $existing_product->id;
  1084. } else {
  1085. // 创建新资产
  1086. $versions = getProp($target_roles, 'versions', []);
  1087. $product_id = DB::table('mp_products')->insertGetId([
  1088. 'user_id' => $uid,
  1089. 'cpid' => $cpid,
  1090. 'type' => 1, // 资产
  1091. 'product' => $product_type, // 角色
  1092. 'parent_id' => $folder_id,
  1093. 'level' => 2,
  1094. 'product_name' => $product_name,
  1095. 'url' => $url,
  1096. 'pic_prompt' => $pic_prompt,
  1097. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1098. 'sort_order' => time(),
  1099. 'is_deleted' => 0,
  1100. 'pic_task_status' => '生成成功',
  1101. 'created_at' => date('Y-m-d H:i:s'),
  1102. 'updated_at' => date('Y-m-d H:i:s')
  1103. ]);
  1104. }
  1105. // 建立或更新绑定关系
  1106. $existing_mapping = DB::table('mp_script_product_mappings')
  1107. ->where('script_id', $script_id)
  1108. ->where('product_id', $product_id)
  1109. ->where('episode_number', $episode_number)
  1110. ->first();
  1111. if (!$existing_mapping) {
  1112. // 创建绑定关系
  1113. DB::table('mp_script_product_mappings')->insert([
  1114. 'script_id' => $script_id,
  1115. 'product_id' => $product_id,
  1116. 'episode_number' => $episode_number,
  1117. 'created_at' => date('Y-m-d H:i:s'),
  1118. 'updated_at' => date('Y-m-d H:i:s')
  1119. ]);
  1120. }
  1121. }
  1122. }
  1123. }
  1124. } catch (\Exception $e) {
  1125. dLog('anime')->error('更新剧集角色失败', [
  1126. 'anime_id' => $anime_id,
  1127. 'episode_id' => $episode_id,
  1128. 'error' => $e->getMessage()
  1129. ]);
  1130. Utils::throwError('20003:更新角色列表失败 ' . $e->getMessage());
  1131. }
  1132. return true;
  1133. }
  1134. public function changeEpisodeScenes($data) {
  1135. $anime_id = getProp($data, 'anime_id');
  1136. $episode_id = getProp($data, 'episode_id');
  1137. $target_scenes = getProp($data, 'scenes');
  1138. $is_deleted = getProp($data, 'is_deleted', 0);
  1139. // 参数验证
  1140. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1141. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1142. if (!$target_scenes) Utils::throwError('20003:请提供场景信息');
  1143. // 验证剧集是否存在
  1144. $episode = DB::table('mp_anime_episodes')
  1145. ->where('anime_id', $anime_id)
  1146. ->where('id', $episode_id)
  1147. ->first();
  1148. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1149. $scenes = json_decode(getProp($episode, 'scenes'), true);
  1150. // 获取anime信息,检查是否有关联的script_id
  1151. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1152. if (!$anime) Utils::throwError('20003:动漫不存在');
  1153. $script_id = getProp($anime, 'script_id');
  1154. $episode_number = getProp($episode, 'episode_number', 1);
  1155. $uid = Site::getUid();
  1156. $cpid = Site::getCpid();
  1157. try {
  1158. $target_scene_name = getProp($target_scenes, 'scene');
  1159. if (empty($target_scene_name)) {
  1160. Utils::throwError('20003:场景名称不能为空');
  1161. }
  1162. // 如果是删除操作
  1163. if ($is_deleted == 1) {
  1164. // 从场景列表中移除该场景
  1165. $scenes = array_values(array_filter($scenes, function($scene) use ($target_scene_name) {
  1166. return getProp($scene, 'scene') !== $target_scene_name;
  1167. }));
  1168. // 更新场景列表
  1169. $result = DB::table('mp_anime_episodes')
  1170. ->where('anime_id', $anime_id)
  1171. ->where('id', $episode_id)
  1172. ->update([
  1173. 'scenes' => json_encode($scenes, 256),
  1174. 'updated_at' => date('Y-m-d H:i:s')
  1175. ]);
  1176. if ($result === false) {
  1177. Utils::throwError('20003:删除场景失败');
  1178. }
  1179. } else {
  1180. // 新增或更新操作
  1181. $scene_found = false;
  1182. $is_new_scene = false;
  1183. // 查找并更新已存在的场景
  1184. foreach($scenes as &$scene) {
  1185. if (getProp($scene, 'scene') === $target_scene_name) {
  1186. $scene = $target_scenes;
  1187. $scene_found = true;
  1188. break;
  1189. }
  1190. }
  1191. // 如果场景不存在,则新增
  1192. if (!$scene_found) {
  1193. $scenes[] = $target_scenes;
  1194. $is_new_scene = true;
  1195. }
  1196. // 更新场景列表
  1197. $result = DB::table('mp_anime_episodes')
  1198. ->where('anime_id', $anime_id)
  1199. ->where('id', $episode_id)
  1200. ->update([
  1201. 'scenes' => json_encode($scenes, 256),
  1202. 'updated_at' => date('Y-m-d H:i:s')
  1203. ]);
  1204. if ($result === false) {
  1205. Utils::throwError('20003:更新场景列表失败');
  1206. }
  1207. // 如果有关联的script_id,则同步到mp_products表
  1208. if ($script_id) {
  1209. // 查询剧本信息
  1210. $script = DB::table('mp_scripts')
  1211. ->where('id', $script_id)
  1212. ->where('is_deleted', 0)
  1213. ->first();
  1214. if ($script) {
  1215. $script_name = $script->script_name ?? 'script_' . $script_id;
  1216. $product_name = getProp($target_scenes, 'scene');
  1217. $pic_prompt = getProp($target_scenes, 'pic_prompt', '');
  1218. $url = getProp($target_scenes, 'url', '');
  1219. $product_type = 2; // 2=场景
  1220. // 查找或创建以script_name命名的文件夹
  1221. $folder = DB::table('mp_products')
  1222. ->where('cpid', $cpid)
  1223. ->where('type', 2) // 文件夹类型
  1224. ->where('product', $product_type) // 场景类型
  1225. ->where('product_name', $script_name)
  1226. ->where('parent_id', 0)
  1227. ->where('is_deleted', 0)
  1228. ->first();
  1229. if (!$folder) {
  1230. // 创建文件夹
  1231. $folder_id = DB::table('mp_products')->insertGetId([
  1232. 'user_id' => $uid,
  1233. 'cpid' => $cpid,
  1234. 'type' => 2, // 文件夹
  1235. 'product' => $product_type, // 场景类型
  1236. 'parent_id' => 0,
  1237. 'level' => 1,
  1238. 'product_name' => $script_name,
  1239. 'sort_order' => time(),
  1240. 'is_deleted' => 0,
  1241. 'created_at' => date('Y-m-d H:i:s'),
  1242. 'updated_at' => date('Y-m-d H:i:s')
  1243. ]);
  1244. } else {
  1245. $folder_id = $folder->id;
  1246. }
  1247. // 查找该文件夹下是否已存在同名资产
  1248. $existing_product = DB::table('mp_products')
  1249. ->where('cpid', $cpid)
  1250. ->where('type', 1) // 资产类型
  1251. ->where('product', $product_type)
  1252. ->where('parent_id', $folder_id)
  1253. ->where('product_name', $product_name)
  1254. ->where('is_deleted', 0)
  1255. ->first();
  1256. if ($existing_product) {
  1257. // 更新已存在的资产
  1258. $updateData = [
  1259. 'pic_task_status' => '生成成功'
  1260. ];
  1261. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1262. if ($url) $updateData['url'] = $url;
  1263. // 处理versions字段
  1264. $versions = getProp($target_scenes, 'versions', []);
  1265. if ($versions && is_array($versions)) {
  1266. $updateData['versions'] = json_encode($versions, 256);
  1267. }
  1268. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1269. DB::table('mp_products')
  1270. ->where('id', $existing_product->id)
  1271. ->update($updateData);
  1272. $product_id = $existing_product->id;
  1273. } else {
  1274. // 创建新资产
  1275. $versions = getProp($target_scenes, 'versions', []);
  1276. $product_id = DB::table('mp_products')->insertGetId([
  1277. 'user_id' => $uid,
  1278. 'cpid' => $cpid,
  1279. 'type' => 1, // 资产
  1280. 'product' => $product_type, // 场景
  1281. 'parent_id' => $folder_id,
  1282. 'level' => 2,
  1283. 'product_name' => $product_name,
  1284. 'url' => $url,
  1285. 'pic_prompt' => $pic_prompt,
  1286. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1287. 'sort_order' => time(),
  1288. 'is_deleted' => 0,
  1289. 'pic_task_status' => '生成成功',
  1290. 'created_at' => date('Y-m-d H:i:s'),
  1291. 'updated_at' => date('Y-m-d H:i:s')
  1292. ]);
  1293. }
  1294. // 建立或更新绑定关系
  1295. $existing_mapping = DB::table('mp_script_product_mappings')
  1296. ->where('script_id', $script_id)
  1297. ->where('product_id', $product_id)
  1298. ->where('episode_number', $episode_number)
  1299. ->first();
  1300. if (!$existing_mapping) {
  1301. // 创建绑定关系
  1302. DB::table('mp_script_product_mappings')->insert([
  1303. 'script_id' => $script_id,
  1304. 'product_id' => $product_id,
  1305. 'episode_number' => $episode_number,
  1306. 'created_at' => date('Y-m-d H:i:s'),
  1307. 'updated_at' => date('Y-m-d H:i:s')
  1308. ]);
  1309. }
  1310. }
  1311. }
  1312. }
  1313. } catch (\Exception $e) {
  1314. dLog('anime')->error('更新剧集场景失败', [
  1315. 'anime_id' => $anime_id,
  1316. 'episode_id' => $episode_id,
  1317. 'error' => $e->getMessage()
  1318. ]);
  1319. Utils::throwError('20003:更新场景列表失败 ' . $e->getMessage());
  1320. }
  1321. return true;
  1322. }
  1323. public function changeEpisodeProps($data) {
  1324. $anime_id = getProp($data, 'anime_id');
  1325. $episode_id = getProp($data, 'episode_id');
  1326. $target_props = getProp($data, 'props');
  1327. $is_deleted = getProp($data, 'is_deleted', 0);
  1328. // 参数验证
  1329. if (!$anime_id) Utils::throwError('20003:请提供动漫ID');
  1330. if (!$episode_id) Utils::throwError('20003:请提供剧集ID');
  1331. if (!$target_props) Utils::throwError('20003:请提供道具信息');
  1332. // 验证剧集是否存在
  1333. $episode = DB::table('mp_anime_episodes')
  1334. ->where('anime_id', $anime_id)
  1335. ->where('id', $episode_id)
  1336. ->first();
  1337. if (!$episode) Utils::throwError('20003:该剧集不存在');
  1338. $props = json_decode(getProp($episode, 'props'), true);
  1339. // 获取anime信息,检查是否有关联的script_id
  1340. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  1341. if (!$anime) Utils::throwError('20003:动漫不存在');
  1342. $script_id = getProp($anime, 'script_id');
  1343. $episode_number = getProp($episode, 'episode_number', 1);
  1344. $uid = Site::getUid();
  1345. $cpid = Site::getCpid();
  1346. try {
  1347. $target_prop_name = getProp($target_props, 'prop');
  1348. if (empty($target_prop_name)) {
  1349. Utils::throwError('20003:道具名称不能为空');
  1350. }
  1351. // 如果是删除操作
  1352. if ($is_deleted == 1) {
  1353. // 从道具列表中移除该道具
  1354. $props = array_values(array_filter($props, function($prop) use ($target_prop_name) {
  1355. return getProp($prop, 'prop') !== $target_prop_name;
  1356. }));
  1357. // 更新道具列表
  1358. $result = DB::table('mp_anime_episodes')
  1359. ->where('anime_id', $anime_id)
  1360. ->where('id', $episode_id)
  1361. ->update([
  1362. 'props' => json_encode($props, 256),
  1363. 'updated_at' => date('Y-m-d H:i:s')
  1364. ]);
  1365. if ($result === false) {
  1366. Utils::throwError('20003:删除道具失败');
  1367. }
  1368. } else {
  1369. // 新增或更新操作
  1370. $prop_found = false;
  1371. $is_new_prop = false;
  1372. // 查找并更新已存在的道具
  1373. foreach($props as &$prop) {
  1374. if (getProp($prop, 'prop') === $target_prop_name) {
  1375. $prop = $target_props;
  1376. $prop_found = true;
  1377. break;
  1378. }
  1379. }
  1380. // 如果道具不存在,则新增
  1381. if (!$prop_found) {
  1382. $props[] = $target_props;
  1383. $is_new_prop = true;
  1384. }
  1385. // 更新道具列表
  1386. $result = DB::table('mp_anime_episodes')
  1387. ->where('anime_id', $anime_id)
  1388. ->where('id', $episode_id)
  1389. ->update([
  1390. 'props' => json_encode($props, 256),
  1391. 'updated_at' => date('Y-m-d H:i:s')
  1392. ]);
  1393. if ($result === false) {
  1394. Utils::throwError('20003:更新道具列表失败');
  1395. }
  1396. // 如果有关联的script_id,则同步到mp_products表
  1397. if ($script_id) {
  1398. // 查询剧本信息
  1399. $script = DB::table('mp_scripts')
  1400. ->where('id', $script_id)
  1401. ->where('is_deleted', 0)
  1402. ->first();
  1403. if ($script) {
  1404. $script_name = $script->script_name ?? 'script_' . $script_id;
  1405. $product_name = getProp($target_props, 'prop');
  1406. $pic_prompt = getProp($target_props, 'pic_prompt', '');
  1407. $url = getProp($target_props, 'url', '');
  1408. $product_type = 3; // 3=道具
  1409. // 查找或创建以script_name命名的文件夹
  1410. $folder = DB::table('mp_products')
  1411. ->where('cpid', $cpid)
  1412. ->where('type', 2) // 文件夹类型
  1413. ->where('product', $product_type) // 道具类型
  1414. ->where('product_name', $script_name)
  1415. ->where('parent_id', 0)
  1416. ->where('is_deleted', 0)
  1417. ->first();
  1418. if (!$folder) {
  1419. // 创建文件夹
  1420. $folder_id = DB::table('mp_products')->insertGetId([
  1421. 'user_id' => $uid,
  1422. 'cpid' => $cpid,
  1423. 'type' => 2, // 文件夹
  1424. 'product' => $product_type, // 道具类型
  1425. 'parent_id' => 0,
  1426. 'level' => 1,
  1427. 'product_name' => $script_name,
  1428. 'sort_order' => time(),
  1429. 'is_deleted' => 0,
  1430. 'created_at' => date('Y-m-d H:i:s'),
  1431. 'updated_at' => date('Y-m-d H:i:s')
  1432. ]);
  1433. } else {
  1434. $folder_id = $folder->id;
  1435. }
  1436. // 查找该文件夹下是否已存在同名资产
  1437. $existing_product = DB::table('mp_products')
  1438. ->where('cpid', $cpid)
  1439. ->where('type', 1) // 资产类型
  1440. ->where('product', $product_type)
  1441. ->where('parent_id', $folder_id)
  1442. ->where('product_name', $product_name)
  1443. ->where('is_deleted', 0)
  1444. ->first();
  1445. if ($existing_product) {
  1446. // 更新已存在的资产
  1447. $updateData = [
  1448. 'pic_task_status' => '生成成功'
  1449. ];
  1450. if ($pic_prompt) $updateData['pic_prompt'] = $pic_prompt;
  1451. if ($url) $updateData['url'] = $url;
  1452. // 处理versions字段
  1453. $versions = getProp($target_props, 'versions', []);
  1454. if ($versions && is_array($versions)) {
  1455. $updateData['versions'] = json_encode($versions, 256);
  1456. }
  1457. $updateData['updated_at'] = date('Y-m-d H:i:s');
  1458. DB::table('mp_products')
  1459. ->where('id', $existing_product->id)
  1460. ->update($updateData);
  1461. $product_id = $existing_product->id;
  1462. } else {
  1463. // 创建新资产
  1464. $versions = getProp($target_props, 'versions', []);
  1465. $product_id = DB::table('mp_products')->insertGetId([
  1466. 'user_id' => $uid,
  1467. 'cpid' => $cpid,
  1468. 'type' => 1, // 资产
  1469. 'product' => $product_type, // 道具
  1470. 'parent_id' => $folder_id,
  1471. 'level' => 2,
  1472. 'product_name' => $product_name,
  1473. 'url' => $url,
  1474. 'pic_prompt' => $pic_prompt,
  1475. 'versions' => is_array($versions) ? json_encode($versions, 256) : '[]',
  1476. 'sort_order' => time(),
  1477. 'is_deleted' => 0,
  1478. 'pic_task_status' => '生成成功',
  1479. 'created_at' => date('Y-m-d H:i:s'),
  1480. 'updated_at' => date('Y-m-d H:i:s')
  1481. ]);
  1482. }
  1483. // 建立或更新绑定关系
  1484. $existing_mapping = DB::table('mp_script_product_mappings')
  1485. ->where('script_id', $script_id)
  1486. ->where('product_id', $product_id)
  1487. ->where('episode_number', $episode_number)
  1488. ->first();
  1489. if (!$existing_mapping) {
  1490. // 创建绑定关系
  1491. DB::table('mp_script_product_mappings')->insert([
  1492. 'script_id' => $script_id,
  1493. 'product_id' => $product_id,
  1494. 'episode_number' => $episode_number,
  1495. 'created_at' => date('Y-m-d H:i:s'),
  1496. 'updated_at' => date('Y-m-d H:i:s')
  1497. ]);
  1498. }
  1499. }
  1500. }
  1501. }
  1502. } catch (\Exception $e) {
  1503. dLog('anime')->error('更新剧集道具失败', [
  1504. 'anime_id' => $anime_id,
  1505. 'episode_id' => $episode_id,
  1506. 'error' => $e->getMessage()
  1507. ]);
  1508. Utils::throwError('20003:更新道具列表失败 ' . $e->getMessage());
  1509. }
  1510. return true;
  1511. }
  1512. public function editSegment($data) {
  1513. $segment_id = getProp($data, 'segment_id');
  1514. $segment_content = getProp($data, 'segment_content');
  1515. $image_url = getProp($data, 'image_url');
  1516. $video_url = getProp($data, 'video_url');
  1517. // 参数验证
  1518. if (!$segment_id) Utils::throwError('20003:请提供分镜ID');
  1519. // 验证分镜是否存在
  1520. $segment = DB::table('mp_episode_segments')
  1521. ->where('segment_id', $segment_id)
  1522. ->first();
  1523. if (!$segment) Utils::throwError('20003:该分镜不存在');
  1524. $dubTaskId = 0;
  1525. try {
  1526. DB::beginTransaction();
  1527. // 准备更新数据
  1528. $update_data = [
  1529. 'updated_at' => date('Y-m-d H:i:s')
  1530. ];
  1531. if ($segment_content) {
  1532. // 先将segment_content赋值到update_data
  1533. $update_data['segment_content'] = $segment_content;
  1534. // 使用现有方法分析segment_content,提取各个字段
  1535. $this->handleSegmentContent($update_data);
  1536. // 如果有对话内容,创建视频配音合成任务
  1537. $dialogue = getProp($update_data, 'dialogue');
  1538. if (!empty($dialogue)) {
  1539. $now = date('Y-m-d H:i:s');
  1540. $generate_json = [
  1541. 'text' => $dialogue,
  1542. 'role' => getProp($update_data, 'voice_actor'),
  1543. 'voice_type' => getProp($update_data, 'voice_type'),
  1544. 'voice_name' => getProp($update_data, 'voice_name'),
  1545. 'emotion' => getProp($update_data, 'emotion'),
  1546. 'emotion_type' => getProp($update_data, 'emotion_type'),
  1547. 'gender' => getProp($update_data, 'gender'),
  1548. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  1549. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  1550. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  1551. 'pitch' => getProp($update_data, 'pitch', 0),
  1552. ];
  1553. // 插入视频配音合成任务
  1554. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1555. 'alias_segment_id' => $segment_id,
  1556. 'generate_status' => '执行中',
  1557. 'audio_url' => '',
  1558. 'generate_json' => json_encode($generate_json, 256),
  1559. 'created_at' => $now,
  1560. 'updated_at' => $now,
  1561. ]);
  1562. if (!$dubTaskId) {
  1563. Utils::throwError('20003:创建配音任务失败!');
  1564. }
  1565. $update_data['audio_url'] = '';
  1566. } else {
  1567. // dialogue为空时,直接写入默认音频信息
  1568. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1569. $update_data['audio_duration'] = 2.0;
  1570. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1571. }
  1572. }
  1573. if ($image_url) {
  1574. $update_data['img_url'] = $image_url;
  1575. // 同时写入一个简单的图片生成任务
  1576. $pic_task = [
  1577. 'alias_segment_id' => $segment_id,
  1578. 'ref_img_url' => json_encode([]),
  1579. 'status' => 'success',
  1580. 'result_url' => json_encode([$image_url], 256),
  1581. 'model' => '',
  1582. 'created_at' => date('Y-m-d H:i:s'),
  1583. 'updated_at' => date('Y-m-d H:i:s'),
  1584. ];
  1585. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  1586. }
  1587. if ($video_url) {
  1588. $update_data['origin_video_url'] = $video_url;
  1589. $compressed_video_url = compressVideo($video_url);
  1590. $update_data['current_type'] = 2;
  1591. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  1592. // 同时写入一个简单的视频生成任务
  1593. $video_task = [
  1594. 'alias_segment_id' => $segment_id,
  1595. 'status' => 'success',
  1596. 'result_url' => $update_data['origin_video_url'],
  1597. 'compressed_url' => $update_data['video_url'],
  1598. 'created_at' => date('Y-m-d H:i:s'),
  1599. 'updated_at' => date('Y-m-d H:i:s'),
  1600. ];
  1601. DB::table('mp_generate_video_tasks')->insert($video_task);
  1602. }
  1603. // 更新分镜信息
  1604. $result = DB::table('mp_episode_segments')
  1605. ->where('segment_id', $segment_id)
  1606. ->update($update_data);
  1607. if ($result === false) {
  1608. Utils::throwError('20003:更新分镜剧本失败');
  1609. }
  1610. DB::commit();
  1611. // 如果有创建音频生成任务则调用API
  1612. if ($dubTaskId) {
  1613. // 请求远程服务器执行生成
  1614. $client = new Client(['timeout' => 300, 'verify' => false]);
  1615. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1616. $response = $result->getBody()->getContents();
  1617. $response_arr = json_decode($response, true);
  1618. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1619. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1620. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1621. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id'=>$segment_id]);
  1622. Utils::throwError('20003:火山生成音频失败');
  1623. }
  1624. }
  1625. return true;
  1626. } catch (\Exception $e) {
  1627. DB::rollBack();
  1628. dLog('anime')->error('更新分镜剧本失败', [
  1629. 'segment_id' => $segment_id,
  1630. 'error' => $e->getMessage()
  1631. ]);
  1632. Utils::throwError('20003:更新分镜剧本失败 ' . $e->getMessage());
  1633. }
  1634. }
  1635. public function batchSetSegmentPics($data) {
  1636. $anime_id = getProp($data, 'anime_id');
  1637. $episode_id = getProp($data, 'episode_id');
  1638. $ratio = getProp($data, 'ratio');
  1639. $dimensions = $this->getRatioDimensions($ratio);
  1640. $width = $dimensions['width'];
  1641. $height = $dimensions['height'];
  1642. if (!$anime_id || !$episode_id) {
  1643. Utils::throwError('1002:请选择剧集');
  1644. }
  1645. // 获取剧集信息
  1646. $episode = DB::table('mp_anime_episodes')
  1647. ->where('anime_id', $anime_id)
  1648. ->where('id', $episode_id)
  1649. ->where('is_default', 1)
  1650. ->select('id as episode_id', 'anime_id', 'episode_number', 'roles', 'scenes', 'image_model')
  1651. ->first();
  1652. if (!$episode) {
  1653. Utils::throwError('20003:该剧集不存在');
  1654. }
  1655. $model = getProp($data, 'model');
  1656. if (!$model) {
  1657. $model = getProp($episode, 'image_model');
  1658. if (!$model) {
  1659. // episode表也没有,使用默认值
  1660. $model = 'doubao-seedream-5-0-lite-260128';
  1661. }
  1662. }
  1663. // 验证模型是否在可用模型表中
  1664. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1665. $model = 'doubao-seedream-5-0-lite-260128';
  1666. }
  1667. $roles = json_decode(getProp($episode, 'roles'), true);
  1668. if (!$roles) {
  1669. Utils::throwError('20003:角色信息格式错误');
  1670. }
  1671. // 构建角色名称到参考图的映射
  1672. $role_map = [];
  1673. foreach ($roles as $role) {
  1674. $role_name = getProp($role, 'role');
  1675. $role_url = getProp($role, 'url');
  1676. if (!empty($role_name) && !empty($role_url)) {
  1677. // // 处理角色名称,去除装扮后缀(如:许芸-校服装 -> 许芸)- 修复中文乱码问题(弃用,容易产生重复图片)
  1678. // $base_name = preg_replace('/[--].*$/u', '', $role_name);
  1679. // $role_map[$base_name] = $role_url;
  1680. // 同时保存完整名称的映射
  1681. $role_map[$role_name] = $role_url;
  1682. }
  1683. }
  1684. $scenes = json_decode(getProp($episode, 'roles'), true);
  1685. if (!$scenes) {
  1686. Utils::throwError('20003:场景信息格式错误');
  1687. }
  1688. // 构建角色名称到参考图的映射
  1689. $scene_map = [];
  1690. foreach ($scenes as $scene) {
  1691. $scene_name = getProp($scene, 'scene');
  1692. $scene_url = getProp($scene, 'url');
  1693. if (!empty($scene_name) && !empty($scene_url)) {
  1694. $scene_map[$scene_name] = $scene_url;
  1695. }
  1696. }
  1697. // 获取所有分镜信息
  1698. $segments = DB::table('mp_episode_segments')
  1699. ->where('anime_id', $anime_id)
  1700. ->where('episode_id', $episode_id)
  1701. ->whereNotIn('pic_task_status', ['已完成', '生成中'])
  1702. ->orderBy('segment_number')
  1703. ->get()
  1704. ->toArray();
  1705. if (empty($segments)) {
  1706. Utils::throwError('20003:所有分镜图片已完成或正在生成中');
  1707. }
  1708. // 保存图片比例
  1709. DB::table('mp_anime_episodes')->where('id', $episode_id)->update(['ratio' => $ratio, 'updated_at' => date('Y-m-d H:i:s')]);
  1710. $updated_segments = [];
  1711. $failed_segments = [];
  1712. // 批量为每个分镜生成图片任务
  1713. foreach ($segments as $segment) {
  1714. $segment_id = $segment->segment_id;
  1715. $segment_content = $segment->segment_content;
  1716. if (empty($segment_content)) {
  1717. $failed_segments[] = [
  1718. 'segment_id' => $segment_id,
  1719. 'error' => '分镜内容为空'
  1720. ];
  1721. continue;
  1722. }
  1723. try {
  1724. $dubTaskId = 0;
  1725. // 解析分镜内容,提取画面描述作为主要提示词
  1726. $prompt = $segment_content;
  1727. $ref_img_urls = [];
  1728. // 分镜场景
  1729. $scene = getProp($segment, 'scene');
  1730. $matched_scene = '';
  1731. if (isset($scene_map[$scene])) {
  1732. $img_index = count($ref_img_urls) + 1;
  1733. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1734. $ref_img_urls[] = $scene_map[$scene];
  1735. $matched_scene = $scene;
  1736. }
  1737. // 分镜角色
  1738. $characters = getProp($segment, 'characters');
  1739. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1740. $roles = explode(',', $characters);
  1741. // 从分镜内容中提取涉及的角色
  1742. $segment_characters = $this->extractCharactersFromSegment($segment_content, array_keys($role_map), $roles);
  1743. // 获取匹配角色的参考图
  1744. foreach ($segment_characters as $character) {
  1745. if (isset($role_map[$character])) {
  1746. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1747. $img_index = count($ref_img_urls) + 1;
  1748. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1749. $ref_img_urls[] = $role_map[$character];
  1750. }
  1751. }
  1752. // 如果没有找到匹配的角色参考图,不使用参考图
  1753. if (empty($ref_img_urls)) {
  1754. $ref_img_urls = [];
  1755. }
  1756. // 准备生成任务参数
  1757. $params = [
  1758. 'model' => $model,
  1759. 'alias_segment_id' => $segment_id,
  1760. 'prompt' => $prompt,
  1761. 'ref_img_urls' => $ref_img_urls,
  1762. 'width' => $width,
  1763. 'height' => $height,
  1764. ];
  1765. // 优化提示词(不要生成字幕)
  1766. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1767. // $task_id = mt_rand(100000, 999999);
  1768. // 调用AI图片生成服务
  1769. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  1770. $task_id = $task->id;
  1771. if (!$task_id) {
  1772. $failed_segments[] = [
  1773. 'segment_id' => $segment_id,
  1774. 'error' => '创建生成任务失败'
  1775. ];
  1776. continue;
  1777. }
  1778. $update_data = [
  1779. 'pic_task_id' => $task_id,
  1780. 'pic_task_status' => '生成中',
  1781. 'audio_url' => '',
  1782. 'updated_at' => date('Y-m-d H:i:s')
  1783. ];
  1784. // 如果有对话内容,创建视频配音合成任务
  1785. $dialogue = getProp($segment, 'dialogue');
  1786. if (!empty($dialogue)) {
  1787. $now = date('Y-m-d H:i:s');
  1788. $generate_json = [
  1789. 'text' => $dialogue,
  1790. 'role' => getProp($segment, 'voice_actor'),
  1791. 'voice_type' => getProp($segment, 'voice_type'),
  1792. 'voice_name' => getProp($segment, 'voice_name'),
  1793. 'emotion' => getProp($segment, 'emotion'),
  1794. 'emotion_type' => getProp($segment, 'emotion_type'),
  1795. 'gender' => getProp($segment, 'gender'),
  1796. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  1797. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  1798. 'emotion_scale' => getProp($segment, 'emotion_scale', 0),
  1799. 'pitch' => getProp($segment, 'pitch', 0),
  1800. ];
  1801. // 插入视频配音合成任务
  1802. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  1803. 'alias_segment_id' => $segment_id,
  1804. 'generate_status' => '执行中',
  1805. 'audio_url' => '',
  1806. 'generate_json' => json_encode($generate_json, 256),
  1807. 'created_at' => $now,
  1808. 'updated_at' => $now,
  1809. ]);
  1810. if (!$dubTaskId) {
  1811. dLog('anime')->error('火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1812. logDB('anime', 'error', '火山生成音频失败', ['segment_id' => $segment_id, 'generate_json'=>$generate_json]);
  1813. // Utils::throwError('20003:创建配音任务失败!');
  1814. }
  1815. } else {
  1816. // dialogue为空时,直接写入默认音频信息到分镜表
  1817. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1818. $update_data['audio_duration'] = 2.0;
  1819. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  1820. }
  1821. // 更新分镜的任务信息
  1822. $update_result = DB::table('mp_episode_segments')
  1823. ->where('segment_id', $segment_id)
  1824. ->update($update_data);
  1825. // 如果是第一集的首帧图片,则存入待更新数组
  1826. if ($update_result && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  1827. Redis::sadd('anime_first_frame_urls', $segment_id);
  1828. }
  1829. if ($update_result) {
  1830. $updated_segments[] = [
  1831. 'segment_id' => $segment_id,
  1832. 'task_id' => $task_id,
  1833. 'status' => '生成中',
  1834. 'matched_scenes' => $matched_scene,
  1835. 'matched_roles' => $segment_characters,
  1836. 'ref_urls_count' => count($ref_img_urls)
  1837. ];
  1838. } else {
  1839. $failed_segments[] = [
  1840. 'segment_id' => $segment_id,
  1841. 'error' => '更新分镜任务状态失败'
  1842. ];
  1843. }
  1844. if ($dubTaskId) {
  1845. sleep(1);
  1846. // 请求远程服务器执行生成
  1847. $client = new Client(['timeout' => 300, 'verify' => false]);
  1848. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  1849. $response = $result->getBody()->getContents();
  1850. $response_arr = json_decode($response, true);
  1851. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1852. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1853. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1854. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $segment_id]);
  1855. }
  1856. }
  1857. } catch (\Exception $e) {
  1858. $failed_segments[] = [
  1859. 'segment_id' => $segment_id,
  1860. 'error' => $e->getMessage()
  1861. ];
  1862. }
  1863. }
  1864. // 更新剧集生成状态
  1865. if (!empty($updated_segments)) {
  1866. DB::table('mp_anime_episodes')
  1867. ->where('id', $episode_id)
  1868. ->update([
  1869. 'is_generated' => 1,
  1870. 'updated_at' => date('Y-m-d H:i:s')
  1871. ]);
  1872. }
  1873. return [
  1874. 'success_count' => count($updated_segments),
  1875. 'failed_count' => count($failed_segments),
  1876. 'success_segments' => $updated_segments,
  1877. 'failed_segments' => $failed_segments,
  1878. 'total_segments' => count($segments)
  1879. ];
  1880. }
  1881. public function reGenerateSegment($data) {
  1882. $segment_id = getProp($data, 'segment_id');
  1883. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  1884. $anime_id = getProp($segment, 'anime_id');
  1885. $episode_id = getProp($segment, 'episode_id');
  1886. $episode_number = getProp($segment, 'episode_number');
  1887. $segment_content = getProp($data, 'segment_content');
  1888. $ratio = getProp($data, 'ratio');
  1889. if (!$ratio) {
  1890. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  1891. if (!$ratio) $ratio = '9:16';
  1892. }
  1893. $dimensions = $this->getRatioDimensions($ratio);
  1894. $width = $dimensions['width'];
  1895. $height = $dimensions['height'];
  1896. if (!$anime_id || !$episode_id) {
  1897. Utils::throwError('1002:请选择分镜');
  1898. }
  1899. // 使用文生文模型重新解析segment_content
  1900. if (!empty($segment_content)) {
  1901. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  1902. }
  1903. // 获取动漫的角色信息(包含参考图)
  1904. $anime = DB::table('mp_animes')
  1905. ->where('id', $anime_id)
  1906. ->select('roles', 'scenes')
  1907. ->first();
  1908. if (!$anime || !$anime->roles) {
  1909. Utils::throwError('20003:未找到角色信息');
  1910. }
  1911. $roles = json_decode($anime->roles, true);
  1912. if (!$roles) {
  1913. Utils::throwError('20003:角色信息格式错误');
  1914. }
  1915. // 构建角色名称到参考图的映射
  1916. $role_map = [];
  1917. foreach ($roles as $role) {
  1918. $role_name = getProp($role, 'role');
  1919. $role_url = getProp($role, 'url');
  1920. if (!empty($role_name) && !empty($role_url)) {
  1921. $role_map[$role_name] = $role_url;
  1922. }
  1923. }
  1924. $scenes = json_decode($anime->scenes, true);
  1925. if (!$scenes) {
  1926. Utils::throwError('20003:角色信息格式错误');
  1927. }
  1928. // 构建角色名称到参考图的映射
  1929. $scene_map = [];
  1930. foreach ($scenes as $scene) {
  1931. $scene_name = getProp($scene, 'scene');
  1932. $scene_url = getProp($scene, 'url');
  1933. if (!empty($scene_name) && !empty($scene_url)) {
  1934. $scene_map[$scene_name] = $scene_url;
  1935. }
  1936. }
  1937. $segment_id = $segment->segment_id;
  1938. $original_segment_content = $segment->segment_content;
  1939. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  1940. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  1941. if (empty($final_segment_content)) {
  1942. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  1943. }
  1944. try {
  1945. $dubTaskId = 0;
  1946. // 分镜剧本数组
  1947. $update_data = [
  1948. 'segment_content' => $final_segment_content,
  1949. 'pic_task_status' => '生成中',
  1950. 'updated_at' => date('Y-m-d H:i:s')
  1951. ];
  1952. // 解析分镜内容,提取画面描述作为主要提示词
  1953. $prompt = $final_segment_content;
  1954. $ref_img_urls = [];
  1955. // 分镜场景
  1956. $scene = getProp($data, 'scene');
  1957. if ($scene) {
  1958. $matched_scene = '';
  1959. if (isset($scene_map[$scene])) {
  1960. $img_index = count($ref_img_urls) + 1;
  1961. $prompt = "场景:$scene(图$img_index)\n$prompt";
  1962. $ref_img_urls[] = $scene_map[$scene];
  1963. $matched_scene = $scene;
  1964. }
  1965. $update_data['scene'] = $scene;
  1966. }
  1967. // 分镜角色
  1968. $characters = getProp($data, 'characters');
  1969. if ($characters) {
  1970. $update_data['characters'] = $characters;
  1971. $characters = str_replace(['、', ',', ';'], ',', $characters);
  1972. $characters = explode(',', $characters);
  1973. // 从分镜内容中提取涉及的角色
  1974. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  1975. // 获取匹配角色的参考图
  1976. foreach ($segment_characters as $character) {
  1977. if (isset($role_map[$character])) {
  1978. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  1979. $img_index = count($ref_img_urls) + 1;
  1980. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  1981. $ref_img_urls[] = $role_map[$character];
  1982. }
  1983. }
  1984. }
  1985. // 如果没有找到匹配的角色参考图,不使用参考图
  1986. if (empty($ref_img_urls)) {
  1987. $ref_img_urls = [];
  1988. }
  1989. // 准备生成任务参数
  1990. $params = [
  1991. 'alias_segment_id' => $segment_id,
  1992. 'prompt' => $prompt,
  1993. 'ref_img_urls' => $ref_img_urls,
  1994. 'width' => $width,
  1995. 'height' => $height,
  1996. ];
  1997. // 优化提示词(不要生成字幕)
  1998. $params['prompt'] = "前置要求:图片中不要带有任何对话台词或字幕信息\n".$params['prompt'];
  1999. // 调用AI图片生成服务
  2000. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2001. $task_id = $task->id;
  2002. if (!$task_id) {
  2003. Utils::throwError('20003:创建生成任务失败!');
  2004. }
  2005. $update_data['pic_task_id'] = $task_id;
  2006. // 更新分镜剧本信息
  2007. $this->handleSegmentContent($update_data);
  2008. // 如果有对话内容,创建视频配音合成任务(有更改分镜内容时创建)
  2009. if ($segment_content) {
  2010. $dialogue = getProp($update_data, 'dialogue');
  2011. if (!empty($dialogue)) {
  2012. $now = date('Y-m-d H:i:s');
  2013. $generate_json = [
  2014. 'text' => $dialogue,
  2015. 'role' => getProp($update_data, 'voice_actor'),
  2016. 'voice_type' => getProp($update_data, 'voice_type'),
  2017. 'voice_name' => getProp($update_data, 'voice_name'),
  2018. 'emotion' => getProp($update_data, 'emotion'),
  2019. 'emotion_type' => getProp($update_data, 'emotion_type'),
  2020. 'gender' => getProp($update_data, 'gender'),
  2021. 'speed_ratio' => getProp($update_data, 'speed_ratio', 0),
  2022. 'loudness_ratio' => getProp($update_data, 'loudness_ratio', 0),
  2023. 'emotion_scale' => getProp($update_data, 'emotion_scale', 0),
  2024. 'pitch' => getProp($update_data, 'pitch', 0),
  2025. ];
  2026. // 插入视频配音合成任务
  2027. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2028. 'alias_segment_id' => $segment_id,
  2029. 'generate_status' => '执行中',
  2030. 'audio_url' => '',
  2031. 'generate_json' => json_encode($generate_json, 256),
  2032. 'created_at' => date('Y-m-d H:i:s'),
  2033. 'updated_at' => date('Y-m-d H:i:s'),
  2034. ]);
  2035. if (!$dubTaskId) {
  2036. Utils::throwError('20003:创建配音任务失败!');
  2037. }
  2038. $update_data['audio_url'] = '';
  2039. } else {
  2040. // dialogue为空时,直接写入默认音频信息
  2041. $update_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2042. $update_data['audio_duration'] = 2.0;
  2043. $update_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2044. }
  2045. }
  2046. $boolen = DB::table('mp_episode_segments')
  2047. ->where('segment_id', $segment_id)
  2048. ->update($update_data);
  2049. // 如果是第一集的首帧图片,则存入待更新数组
  2050. if ($boolen && (int)getProp($segment, 'episode_number') === 1 && (int)getProp($segment, 'segment_number') === 1) {
  2051. Redis::sadd('anime_first_frame_urls', $segment_id);
  2052. }
  2053. if ($dubTaskId) {
  2054. // 请求远程服务器执行生成
  2055. $client = new Client(['timeout' => 300, 'verify' => false]);
  2056. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2057. $response = $result->getBody()->getContents();
  2058. $response_arr = json_decode($response, true);
  2059. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2060. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2061. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2062. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2063. Utils::throwError('20003:火山生成音频失败');
  2064. }
  2065. }
  2066. } catch (\Exception $e) {
  2067. $failed_segments[] = [
  2068. 'segment_id' => $segment_id,
  2069. 'error' => $e->getMessage()
  2070. ];
  2071. }
  2072. // 创建任务之后先暂停10s等待异步任务完成
  2073. sleep(10);
  2074. $img_url = $this->loopGetPicTaskResult($task_id);
  2075. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2076. // 图片生成后新增对话记录
  2077. try {
  2078. $uid = Site::getUid();
  2079. $now = date('Y-m-d H:i:s');
  2080. // 使用AI反推图片提示词
  2081. $pic_prompt = $this->generateImagePromptFromUrl($img_url);
  2082. // 保存对话记录
  2083. $records = [
  2084. [
  2085. 'uid' => $uid,
  2086. 'anime_id' => $anime_id,
  2087. 'sequence' => $episode_number,
  2088. 'role' => 'user',
  2089. 'content' => '重新生成',
  2090. 'segment_id' => $segment_id,
  2091. 'pic_task_id' => $task_id,
  2092. 'image_url' => '',
  2093. 'created_at' => $now,
  2094. 'updated_at' => $now
  2095. ],
  2096. [
  2097. 'uid' => $uid,
  2098. 'anime_id' => $anime_id,
  2099. 'sequence' => $episode_number,
  2100. 'role' => 'assistant',
  2101. 'content' => $pic_prompt,
  2102. 'segment_id' => $segment_id,
  2103. 'pic_task_id' => $task_id,
  2104. 'image_url' => $img_url,
  2105. 'created_at' => $now,
  2106. 'updated_at' => $now
  2107. ]
  2108. ];
  2109. DB::table('mp_anime_records')->insert($records);
  2110. } catch (\Exception $e) {
  2111. // 记录日志但不影响主流程
  2112. dLog('anime')->error('保存对话记录失败: ' . $e->getMessage(), [
  2113. 'segment_id' => $segment_id,
  2114. 'img_url' => $img_url
  2115. ]);
  2116. }
  2117. return $img_url;
  2118. }
  2119. public function addSegment($data) {
  2120. $prev_segment_id = getProp($data, 'prev_segment_id');
  2121. $img_url = getProp($data, 'img_url');
  2122. $video_url = getProp($data, 'video_url');
  2123. $segment = DB::table('mp_episode_segments')->where('segment_id', $prev_segment_id)->first();
  2124. if (!$segment) Utils::throwError('20003:该分镜不存在');
  2125. $anime_id = getProp($segment, 'anime_id');
  2126. $episode_id = getProp($segment, 'episode_id');
  2127. $episode_number = getProp($segment, 'episode_number');
  2128. $segment_number = getProp($segment, 'segment_number');
  2129. $new_segment_number = $segment_number + 1;
  2130. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2131. // 分镜剧本数组
  2132. $insert_data = [
  2133. 'anime_id' => $anime_id,
  2134. 'episode_id' => $episode_id,
  2135. 'episode_number' => $episode_number,
  2136. 'act_number' => getProp($segment, 'act_number'),
  2137. 'act_title' => getProp($segment, 'act_title'),
  2138. 'segment_id' => $segment_id,
  2139. 'segment_number' => $new_segment_number,
  2140. 'segment_content' => '',
  2141. 'img_url' => '',
  2142. 'video_url' => '',
  2143. 'created_at' => date('Y-m-d H:i:s'),
  2144. 'updated_at' => date('Y-m-d H:i:s')
  2145. ];
  2146. if ($img_url) $insert_data['img_url'] = $img_url;
  2147. if ($video_url) {
  2148. $insert_data['origin_video_url'] = $video_url;
  2149. $insert_data['current_type'] = 2;
  2150. $compressed_video_url = compressVideo($video_url);
  2151. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2152. }
  2153. try {
  2154. DB::beginTransaction();
  2155. // 先更新序号
  2156. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2157. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2158. if (!$id) {
  2159. Utils::throwError('20003:新增分镜失败!');
  2160. }
  2161. }catch (\Exception $e) {
  2162. DB::rollBack();
  2163. Utils::throwError('20003:'.$e->getMessage());
  2164. }
  2165. DB::commit();
  2166. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2167. $segment = $segment ? (array)$segment : [];
  2168. return $segment;
  2169. // 以下代码暂弃用
  2170. $anime_id = getProp($segment, 'anime_id');
  2171. $episode_id = getProp($segment, 'episode_id');
  2172. $episode_number = getProp($segment, 'episode_number');
  2173. $segment_number = getProp($segment, 'segment_number');
  2174. $segment_content = getProp($data, 'segment_content');
  2175. $img_url = getProp($data, 'img_url');
  2176. $video_url = getProp($data, 'video_url');
  2177. $ratio = getProp($data, 'ratio');
  2178. $dimensions = $this->getRatioDimensions($ratio);
  2179. $width = $dimensions['width'];
  2180. $height = $dimensions['height'];
  2181. if (!$anime_id || !$episode_id) {
  2182. Utils::throwError('1002:请选择分镜');
  2183. }
  2184. // 使用文生文模型重新解析segment_content
  2185. if (!empty($segment_content)) {
  2186. $segment_content = $this->parseSegmentContentWithAI($segment_content);
  2187. }
  2188. // 获取动漫的角色信息(包含参考图)
  2189. $anime = DB::table('mp_animes')
  2190. ->where('id', $anime_id)
  2191. ->select('roles', 'scenes')
  2192. ->first();
  2193. if (!$anime || !$anime->roles) {
  2194. Utils::throwError('20003:未找到角色信息');
  2195. }
  2196. $roles = json_decode($anime->roles, true);
  2197. if (!$roles) {
  2198. Utils::throwError('20003:角色信息格式错误');
  2199. }
  2200. // 构建角色名称到参考图的映射
  2201. $role_map = [];
  2202. foreach ($roles as $role) {
  2203. $role_name = getProp($role, 'role');
  2204. $role_url = getProp($role, 'url');
  2205. if (!empty($role_name) && !empty($role_url)) {
  2206. $role_map[$role_name] = $role_url;
  2207. }
  2208. }
  2209. $scenes = json_decode($anime->scenes, true);
  2210. if (!$scenes) {
  2211. Utils::throwError('20003:角色信息格式错误');
  2212. }
  2213. // 构建角色名称到参考图的映射
  2214. $scene_map = [];
  2215. foreach ($scenes as $scene) {
  2216. $scene_name = getProp($scene, 'scene');
  2217. $scene_url = getProp($scene, 'url');
  2218. if (!empty($scene_name) && !empty($scene_url)) {
  2219. $scene_map[$scene_name] = $scene_url;
  2220. }
  2221. }
  2222. $segment_id = $segment->segment_id;
  2223. $original_segment_content = $segment->segment_content;
  2224. // 如果传入了新的segment_content,使用新的内容,否则使用原有内容
  2225. $final_segment_content = !empty($segment_content) ? $segment_content : $original_segment_content;
  2226. if (empty($final_segment_content)) {
  2227. Utils::throwError('20003:分镜内容不存在,请填写内容后重试');
  2228. }
  2229. try {
  2230. $dubTaskId = 0;
  2231. DB::beginTransaction();
  2232. $new_segment_number = $segment_number + 1;
  2233. $segment_id = date('YmdHis') . mt_rand(1000, 9999) . str_pad($new_segment_number, 3, "0", STR_PAD_LEFT);
  2234. // 分镜剧本数组
  2235. $insert_data = [
  2236. 'anime_id' => $anime_id,
  2237. 'episode_id' => $episode_id,
  2238. 'episode_number' => $episode_number,
  2239. 'act_number' => getProp($segment, 'act_number'),
  2240. 'act_title' => getProp($segment, 'act_title'),
  2241. 'segment_id' => $segment_id,
  2242. 'segment_number' => $new_segment_number,
  2243. 'segment_content' => $final_segment_content,
  2244. 'img_url' => $img_url,
  2245. 'video_url' => $video_url,
  2246. 'created_at' => date('Y-m-d H:i:s'),
  2247. 'updated_at' => date('Y-m-d H:i:s')
  2248. ];
  2249. // 更新分镜剧本信息
  2250. $this->handleSegmentContent($insert_data);
  2251. // 如果有对话内容,创建视频配音合成任务
  2252. $dialogue = getProp($insert_data, 'dialogue');
  2253. if (!empty($dialogue)) {
  2254. $now = date('Y-m-d H:i:s');
  2255. $generate_json = [
  2256. 'text' => $dialogue,
  2257. 'role' => getProp($insert_data, 'voice_actor'),
  2258. 'voice_type' => getProp($insert_data, 'voice_type'),
  2259. 'voice_name' => getProp($insert_data, 'voice_name'),
  2260. 'emotion' => getProp($insert_data, 'emotion'),
  2261. 'emotion_type' => getProp($insert_data, 'emotion_type'),
  2262. 'gender' => getProp($insert_data, 'gender'),
  2263. 'speed_ratio' => getProp($insert_data, 'speed_ratio', 0),
  2264. 'loudness_ratio' => getProp($insert_data, 'loudness_ratio', 0),
  2265. 'emotion_scale' => getProp($insert_data, 'emotion_scale', 0),
  2266. 'pitch' => getProp($insert_data, 'pitch', 0),
  2267. ];
  2268. // 插入视频配音合成任务
  2269. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  2270. 'alias_segment_id' => $segment_id,
  2271. 'generate_status' => '执行中',
  2272. 'audio_url' => '',
  2273. 'generate_json' => json_encode($generate_json, 256),
  2274. 'created_at' => $now,
  2275. 'updated_at' => $now,
  2276. ]);
  2277. if (!$dubTaskId) {
  2278. Utils::throwError('20003:创建配音任务失败!');
  2279. }
  2280. $insert_data['audio_url'] = '';
  2281. } else {
  2282. // dialogue为空时,直接写入默认音频信息
  2283. $insert_data['audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2284. $insert_data['audio_duration'] = 2.0;
  2285. $insert_data['subtitle_info'] = json_encode(['duration' => 2.0, 'words' => []], 256);
  2286. }
  2287. // 如果没有上传图片则使用当前描述进行生成
  2288. if (!$img_url) {
  2289. // 解析分镜内容,提取画面描述作为主要提示词
  2290. $prompt = $final_segment_content;
  2291. $ref_img_urls = [];
  2292. // 分镜场景
  2293. $scene = getProp($insert_data, 'scene');
  2294. if ($scene) {
  2295. $matched_scene = '';
  2296. if (isset($scene_map[$scene])) {
  2297. $img_index = count($ref_img_urls) + 1;
  2298. $prompt = "场景:$scene(图$img_index)\n$prompt";
  2299. $ref_img_urls[] = $scene_map[$scene];
  2300. $matched_scene = $scene;
  2301. }
  2302. $update_data['scene'] = $scene;
  2303. }
  2304. // 分镜角色
  2305. $characters = getProp($insert_data, 'characters');
  2306. if ($characters) {
  2307. $update_data['characters'] = $characters;
  2308. $characters = str_replace(['、', ',', ';'], ',', $characters);
  2309. $characters = explode(',', $characters);
  2310. // 从分镜内容中提取涉及的角色
  2311. $segment_characters = $this->extractCharactersFromSegment($final_segment_content, array_keys($role_map), $characters);
  2312. // 获取匹配角色的参考图
  2313. foreach ($segment_characters as $character) {
  2314. if (isset($role_map[$character])) {
  2315. // 将$prompt中出现的角色替换成角色(图1、2、3,序号是$ref_img_urls的个数加1)
  2316. $img_index = count($ref_img_urls) + 1;
  2317. $prompt = str_replace($character, $character . '(图' . $img_index . ')', $prompt);
  2318. $ref_img_urls[] = $role_map[$character];
  2319. }
  2320. }
  2321. }
  2322. // 如果没有找到匹配的角色参考图,不使用参考图
  2323. if (empty($ref_img_urls)) {
  2324. $ref_img_urls = [];
  2325. }
  2326. // 准备生成任务参数
  2327. $params = [
  2328. 'alias_segment_id' => $segment_id,
  2329. 'prompt' => $prompt,
  2330. 'ref_img_urls' => $ref_img_urls,
  2331. 'width' => $width,
  2332. 'height' => $height,
  2333. ];
  2334. // 调用AI图片生成服务
  2335. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2336. $task_id = $task->id;
  2337. // $task_id = 'whatever';
  2338. if (!$task_id) {
  2339. Utils::throwError('20003:创建生成任务失败!');
  2340. }
  2341. $insert_data['pic_task_status'] = '生成中';
  2342. $insert_data['pic_task_id'] = $task_id;
  2343. }
  2344. // 先更新序号
  2345. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2346. $boolen = DB::table('mp_episode_segments')->insert($insert_data);
  2347. if (!$boolen) {
  2348. Utils::throwError('20003:新增分镜失败!');
  2349. }
  2350. // 如果是第一集的首帧图片,则存入待更新数组
  2351. if ($boolen && (int)$episode_number === 1 && (int)$new_segment_number === 1) {
  2352. Redis::sadd('anime_first_frame_urls', $segment_id);
  2353. }
  2354. if ($dubTaskId) {
  2355. // 请求远程服务器执行生成
  2356. $client = new Client(['timeout' => 300, 'verify' => false]);
  2357. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  2358. $response = $result->getBody()->getContents();
  2359. $response_arr = json_decode($response, true);
  2360. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2361. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2362. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId]);
  2363. Utils::throwError('20003:火山生成音频失败');
  2364. }
  2365. }
  2366. } catch (\Exception $e) {
  2367. DB::rollBack();
  2368. Utils::throwError('20003:'.$e->getMessage());
  2369. }
  2370. DB::commit();
  2371. // 创建任务之后先暂停10s等待异步任务完成
  2372. sleep(10);
  2373. if (isset($task_id)) $img_url = $this->loopGetPicTaskResult($task_id);
  2374. if (!$img_url) Utils::throwError('20003:图片生成中,请稍后刷新');
  2375. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2376. $segment = $segment ? (array)$segment : [];
  2377. return $segment;
  2378. }
  2379. public function copySegment($data) {
  2380. $segment_id = getProp($data, 'segment_id');
  2381. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2382. if (!$segment) Utils::throwError('20003:请选择分镜');
  2383. $anime_id = getProp($segment, 'anime_id');
  2384. $episode_id = getProp($segment, 'episode_id');
  2385. $episode_number = getProp($segment, 'episode_number');
  2386. $segment_number = getProp($segment, 'segment_number');
  2387. $new_segment_id = 0;
  2388. try {
  2389. DB::beginTransaction();
  2390. $segment = (array)$segment;
  2391. unset($segment['id']);
  2392. $segment['segment_number'] += 1;
  2393. $segment['segment_id'] = date('YmdHis') . mt_rand(1000, 9999) . str_pad($segment['segment_number'], 3, "0", STR_PAD_LEFT);
  2394. // $segment['pic_task_id'] = $segment['pic_task_status'] = $segment['video_task_id'] = $segment['video_task_status'] = '';
  2395. $segment['created_at'] = $segment['updated_at'] = date('Y-m-d H:i:s');
  2396. // 更新其他分镜序号
  2397. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->increment('segment_number');
  2398. // 复制分镜
  2399. $id = DB::table('mp_episode_segments')->insertGetId($segment);
  2400. if (!$id) {
  2401. Utils::throwError('20003:复制分镜失败');
  2402. }
  2403. }catch (\Exception $e) {
  2404. DB::rollBack();
  2405. Utils::throwError('20003:'.$e->getMessage());
  2406. }
  2407. DB::commit();
  2408. $segment = DB::table('mp_episode_segments')->where('id', $id)->first();
  2409. $segment = $segment ? (array)$segment : [];
  2410. return $segment;
  2411. }
  2412. public function moveSegment($data) {
  2413. $segment_id = getProp($data, 'segment_id');
  2414. $target_segment_id = getProp($data, 'target_segment_id');
  2415. // 获取源分镜信息
  2416. $source_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2417. if (!$source_segment) Utils::throwError('20003:请选择分镜');
  2418. // 获取目标分镜信息
  2419. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $target_segment_id)->first();
  2420. if (!$target_segment) Utils::throwError('20003:目标分镜不存在');
  2421. $anime_id = getProp($source_segment, 'anime_id');
  2422. $episode_id = getProp($source_segment, 'episode_id');
  2423. $episode_number = getProp($source_segment, 'episode_number');
  2424. $source_segment_number = getProp($source_segment, 'segment_number');
  2425. $target_segment_number = getProp($target_segment, 'segment_number');
  2426. // 验证源分镜和目标分镜必须属于同一个动漫的同一集
  2427. $target_anime_id = getProp($target_segment, 'anime_id');
  2428. $target_episode_number = getProp($target_segment, 'episode_number');
  2429. if ($anime_id != $target_anime_id || $episode_number != $target_episode_number) {
  2430. Utils::throwError('20003:只能在同一动漫的同一集内移动分镜');
  2431. }
  2432. // 如果源分镜和目标分镜相同,无需移动
  2433. if ($source_segment_number == $target_segment_number) {
  2434. return true;
  2435. }
  2436. try {
  2437. DB::beginTransaction();
  2438. if ($source_segment_number < $target_segment_number) {
  2439. // 向后移动:源分镜移动到目标分镜之后
  2440. // 1. 将源分镜和目标分镜之间的所有分镜序号减1
  2441. DB::table('mp_episode_segments')
  2442. ->where('anime_id', $anime_id)
  2443. ->where('episode_id', $episode_id)
  2444. ->where('segment_number', '>', $source_segment_number)
  2445. ->where('segment_number', '<=', $target_segment_number)
  2446. ->decrement('segment_number');
  2447. // 2. 将源分镜移动到目标分镜之后
  2448. $new_segment_number = $target_segment_number;
  2449. } else {
  2450. // 向前移动:源分镜移动到目标分镜之后
  2451. // 1. 将目标分镜之后到源分镜之前的所有分镜序号加1
  2452. DB::table('mp_episode_segments')
  2453. ->where('anime_id', $anime_id)
  2454. ->where('episode_id', $episode_id)
  2455. ->where('segment_number', '>', $target_segment_number)
  2456. ->where('segment_number', '<', $source_segment_number)
  2457. ->increment('segment_number');
  2458. // 2. 将源分镜移动到目标分镜之后
  2459. $new_segment_number = $target_segment_number + 1;
  2460. }
  2461. // 3. 更新源分镜的序号
  2462. $update_result = DB::table('mp_episode_segments')
  2463. ->where('segment_id', $segment_id)
  2464. ->update([
  2465. 'segment_number' => $new_segment_number,
  2466. 'updated_at' => date('Y-m-d H:i:s')
  2467. ]);
  2468. if (!$update_result) {
  2469. Utils::throwError('20003:更新分镜序号失败');
  2470. }
  2471. DB::commit();
  2472. return true;
  2473. } catch (\Exception $e) {
  2474. DB::rollBack();
  2475. Utils::throwError('20003:' . $e->getMessage());
  2476. }
  2477. }
  2478. public function delSegment($data) {
  2479. $segment_id = getProp($data, 'segment_id');
  2480. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  2481. if (!$segment) Utils::throwError('20003:请选择分镜');
  2482. $anime_id = getProp($segment, 'anime_id');
  2483. $episode_id = getProp($segment, 'episode_id');
  2484. $episode_number = getProp($segment, 'episode_number');
  2485. $segment_number = getProp($segment, 'segment_number');
  2486. try {
  2487. DB::beginTransaction();
  2488. // 删除分镜
  2489. $boolen = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->delete();
  2490. if (!$boolen) {
  2491. Utils::throwError('20003:删除分镜失败');
  2492. }
  2493. // 更新其他分镜序号
  2494. DB::table('mp_episode_segments')->where('anime_id', $anime_id)->where('episode_id', $episode_id)->where('segment_number', '>', $segment_number)->decrement('segment_number');
  2495. }catch (\Exception $e) {
  2496. DB::rollBack();
  2497. Utils::throwError('20003:'.$e->getMessage());
  2498. }
  2499. DB::commit();
  2500. return true;
  2501. }
  2502. public function applySegment($data) {
  2503. $segment_id = getProp($data, 'segment_id');
  2504. $url = getProp($data, 'url');
  2505. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  2506. if (!$url) Utils::throwError('20003:URL不能为空');
  2507. // 获取URL的文件扩展名
  2508. $urlPath = parse_url($url, PHP_URL_PATH);
  2509. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2510. // 定义图片和视频的扩展名
  2511. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2512. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2513. // 判断是图片还是视频
  2514. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2515. if (in_array($extension, $imageExtensions)) {
  2516. // 图片类型
  2517. $updateData['img_url'] = $url;
  2518. $updateData['current_type'] = 1;
  2519. } elseif (in_array($extension, $videoExtensions)) {
  2520. // 视频类型
  2521. $updateData['video_url'] = $url;
  2522. $updateData['current_type'] = 2;
  2523. } else {
  2524. Utils::throwError('20003:不支持的文件类型');
  2525. }
  2526. // 更新分镜表
  2527. $result = DB::table('mp_episode_segments')
  2528. ->where('segment_id', $segment_id)
  2529. ->update($updateData);
  2530. if (!$result) {
  2531. Utils::throwError('20003:更新分镜失败');
  2532. }
  2533. return true;
  2534. }
  2535. public function segmentHistory($data) {
  2536. $segment_id = getProp($data, 'segment_id');
  2537. // 获取历史图片
  2538. $pics = [];
  2539. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2540. foreach($pic_history as $task) {
  2541. $result_url = getProp($task, 'result_url');
  2542. if (is_json($result_url)) {
  2543. $pics = array_merge($pics, json_decode($result_url, true));
  2544. }else {
  2545. $pics[] = $result_url;
  2546. }
  2547. }
  2548. // 获取历史视频
  2549. $videos = [];
  2550. $video_history = DB::table('mp_generate_video_tasks')->where('alias_segment_id', $segment_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2551. foreach($video_history as $task) {
  2552. $result_url = getProp($task, 'result_url');
  2553. if (is_json($result_url)) {
  2554. $videos = array_merge($videos, json_decode($result_url, true));
  2555. }else {
  2556. $videos[] = $result_url;
  2557. }
  2558. }
  2559. return compact('pics', 'videos');
  2560. }
  2561. public function addAct($data) {
  2562. $prev_act_id = getProp($data, 'prev_act_id');
  2563. $act_title = getProp($data, 'act_title', '');
  2564. $act_content = getProp($data, 'act_content', '');
  2565. $act_duration = getProp($data, 'act_duration', 5);
  2566. $video_url = getProp($data, 'video_url');
  2567. // 根据prev_act_id获取记录
  2568. $prev_segment = DB::table('mp_episode_segments')->where('id', $prev_act_id)->first();
  2569. if (!$prev_segment) Utils::throwError('20003:该片段不存在');
  2570. $anime_id = getProp($prev_segment, 'anime_id');
  2571. $episode_id = getProp($prev_segment, 'episode_id');
  2572. $episode_number = getProp($prev_segment, 'episode_number');
  2573. $prev_act_number = getProp($prev_segment, 'act_number');
  2574. // 获取新的act_number
  2575. $new_act_number = $prev_act_number + 1;
  2576. try {
  2577. DB::beginTransaction();
  2578. // 更新后续所有act的act_number(全能模式下每个act只有一条记录)
  2579. DB::table('mp_episode_segments')
  2580. ->where('anime_id', $anime_id)
  2581. ->where('episode_id', $episode_id)
  2582. ->where('act_number', '>', $prev_act_number)
  2583. ->increment('act_number');
  2584. // 插入新片段记录
  2585. $insert_data = [
  2586. 'anime_id' => $anime_id,
  2587. 'episode_id' => $episode_id,
  2588. 'episode_number' => $episode_number,
  2589. 'act_number' => $new_act_number,
  2590. 'created_at' => date('Y-m-d H:i:s'),
  2591. 'updated_at' => date('Y-m-d H:i:s')
  2592. ];
  2593. if ($act_title) {
  2594. $insert_data['act_title'] = $act_title;
  2595. }
  2596. if ($act_content) {
  2597. $insert_data['act_content'] = $act_content;
  2598. }
  2599. if ($act_duration) {
  2600. $insert_data['act_duration'] = $act_duration;
  2601. }
  2602. if ($video_url) {
  2603. $insert_data['origin_video_url'] = $video_url;
  2604. $insert_data['current_type'] = 2;
  2605. $compressed_video_url = compressVideo($video_url);
  2606. $insert_data['video_url'] = $compressed_video_url ?: $video_url;
  2607. }
  2608. $id = DB::table('mp_episode_segments')->insertGetId($insert_data);
  2609. if (!$id) {
  2610. Utils::throwError('20003:新增片段失败!');
  2611. }
  2612. DB::commit();
  2613. }catch (\Exception $e) {
  2614. DB::rollBack();
  2615. Utils::throwError('20003:'.$e->getMessage());
  2616. }
  2617. $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();
  2618. $segment = $segment ? (array)$segment : [];
  2619. return $segment;
  2620. }
  2621. public function editAct($data) {
  2622. $act_id = getProp($data, 'act_id');
  2623. $act_content = getProp($data, 'act_content');
  2624. $act_duration = getProp($data, 'act_duration');
  2625. $act_title = getProp($data, 'act_title');
  2626. $image_url = getProp($data, 'image_url');
  2627. $video_url = getProp($data, 'video_url');
  2628. // 参数验证
  2629. if (!$act_id) Utils::throwError('20003:请提供片段ID');
  2630. // 验证片段是否存在(全能模式下每个act只有一条记录)
  2631. $segment = DB::table('mp_episode_segments')
  2632. ->where('id', $act_id)
  2633. ->first();
  2634. if (!$segment) Utils::throwError('20003:该片段不存在');
  2635. try {
  2636. DB::beginTransaction();
  2637. // 准备更新数据
  2638. $update_data = [
  2639. 'updated_at' => date('Y-m-d H:i:s')
  2640. ];
  2641. // 更新act相关字段
  2642. if (!empty($act_content)) {
  2643. $update_data['act_show_content'] = $act_content;
  2644. $update_data['act_content'] = str_replace(["@", "{", "}"], "", $act_content);
  2645. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  2646. $shot_counter = 0;
  2647. $update_data['act_show_content'] = preg_replace_callback(
  2648. '/【(?:镜头|分镜)(\d+)】/u',
  2649. function($matches) use (&$shot_counter) {
  2650. $shot_counter++;
  2651. return '【镜头' . $shot_counter . '】';
  2652. },
  2653. $update_data['act_show_content']
  2654. );
  2655. }
  2656. if (!empty($act_duration)) {
  2657. $update_data['act_duration'] = $act_duration;
  2658. }
  2659. if (!empty($act_title)) {
  2660. $update_data['act_title'] = $act_title;
  2661. }
  2662. // 处理图片上传
  2663. if ($image_url) {
  2664. $update_data['img_url'] = $image_url;
  2665. $update_data['current_type'] = 1;
  2666. // 同时写入一个图片生成任务记录
  2667. if ($act_id) {
  2668. $pic_task = [
  2669. 'alias_act_id' => $act_id,
  2670. 'ref_img_url' => json_encode([]),
  2671. 'status' => 'success',
  2672. 'result_url' => json_encode([$image_url], 256),
  2673. 'model' => '',
  2674. 'created_at' => date('Y-m-d H:i:s'),
  2675. 'updated_at' => date('Y-m-d H:i:s'),
  2676. ];
  2677. DB::table('mp_generate_pic_tasks')->insert($pic_task);
  2678. }
  2679. }
  2680. // 处理视频上传
  2681. if ($video_url) {
  2682. $update_data['origin_video_url'] = $video_url;
  2683. $compressed_video_url = compressVideo($video_url);
  2684. $update_data['current_type'] = 2;
  2685. $update_data['video_url'] = $compressed_video_url ?: $video_url;
  2686. // 同时写入一个视频生成任务记录
  2687. if ($act_id) {
  2688. $video_task = [
  2689. 'alias_act_id' => $act_id,
  2690. 'status' => 'success',
  2691. 'result_url' => $update_data['origin_video_url'],
  2692. 'compressed_url' => $update_data['video_url'],
  2693. 'created_at' => date('Y-m-d H:i:s'),
  2694. 'updated_at' => date('Y-m-d H:i:s'),
  2695. ];
  2696. DB::table('mp_generate_video_tasks')->insert($video_task);
  2697. }
  2698. }
  2699. // 更新片段信息
  2700. $result = DB::table('mp_episode_segments')
  2701. ->where('id', $act_id)
  2702. ->update($update_data);
  2703. if ($result === false) {
  2704. Utils::throwError('20003:更新片段失败');
  2705. }
  2706. DB::commit();
  2707. // 返回新复制的记录
  2708. $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();
  2709. $new_segment = (array)$new_segment;
  2710. return $new_segment;
  2711. } catch (\Exception $e) {
  2712. DB::rollBack();
  2713. dLog('anime')->error('更新片段失败', [
  2714. 'act_id' => $act_id,
  2715. 'error' => $e->getMessage()
  2716. ]);
  2717. Utils::throwError('20003:更新片段失败 ' . $e->getMessage());
  2718. }
  2719. }
  2720. public function copyAct($data) {
  2721. $act_id = getProp($data, 'act_id');
  2722. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2723. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2724. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2725. $anime_id = getProp($source_segment, 'anime_id');
  2726. $episode_id = getProp($source_segment, 'episode_id');
  2727. $episode_number = getProp($source_segment, 'episode_number');
  2728. $act_number = getProp($source_segment, 'act_number');
  2729. try {
  2730. DB::beginTransaction();
  2731. // 新act的编号
  2732. $new_act_number = $act_number + 1;
  2733. // 更新后续所有act的act_number
  2734. DB::table('mp_episode_segments')
  2735. ->where('anime_id', $anime_id)
  2736. ->where('episode_id', $episode_id)
  2737. ->where('act_number', '>', $act_number)
  2738. ->increment('act_number');
  2739. // 复制该片段记录
  2740. $segment_data = (array)$source_segment;
  2741. unset($segment_data['id']);
  2742. $segment_data['video_url'] = '';
  2743. $segment_data['video_task_id'] = '';
  2744. $segment_data['video_task_status'] = '';
  2745. $segment_data['act_number'] = $new_act_number;
  2746. $segment_data['created_at'] = $segment_data['updated_at'] = date('Y-m-d H:i:s');
  2747. $id = DB::table('mp_episode_segments')->insertGetId($segment_data);
  2748. if (!$id) {
  2749. Utils::throwError('20003:复制片段失败');
  2750. }
  2751. DB::commit();
  2752. }catch (\Exception $e) {
  2753. DB::rollBack();
  2754. Utils::throwError('20003:'.$e->getMessage());
  2755. }
  2756. // 返回新复制的记录
  2757. $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();
  2758. $new_segment = $new_segment ? (array)$new_segment : [];
  2759. $new_segment['act_id'] = $id;
  2760. return $new_segment;
  2761. }
  2762. public function moveAct($data) {
  2763. $act_id = getProp($data, 'act_id');
  2764. $target_act_id = getProp($data, 'target_act_id');
  2765. // 获取源片段信息
  2766. $source_segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2767. if (!$source_segment) Utils::throwError('20003:请选择片段');
  2768. // 获取目标片段信息
  2769. $target_segment = DB::table('mp_episode_segments')->where('id', $target_act_id)->first();
  2770. if (!$target_segment) Utils::throwError('20003:目标片段不存在');
  2771. $anime_id = getProp($source_segment, 'anime_id');
  2772. $episode_id = getProp($source_segment, 'episode_id');
  2773. $source_act_number = getProp($source_segment, 'act_number');
  2774. $target_act_number = getProp($target_segment, 'act_number');
  2775. // 验证源片段和目标片段必须属于同一个动漫的同一集
  2776. $target_anime_id = getProp($target_segment, 'anime_id');
  2777. $target_episode_id = getProp($target_segment, 'episode_id');
  2778. if ($anime_id != $target_anime_id || $episode_id != $target_episode_id) {
  2779. Utils::throwError('20003:只能在同一动漫的同一集内移动片段');
  2780. }
  2781. // 如果源片段和目标片段相同,无需移动
  2782. if ($source_act_number == $target_act_number) {
  2783. return true;
  2784. }
  2785. try {
  2786. DB::beginTransaction();
  2787. if ($source_act_number < $target_act_number) {
  2788. // 向后移动:源片段移动到目标片段之后
  2789. // 1. 将源片段和目标片段之间的所有片段编号减1
  2790. DB::table('mp_episode_segments')
  2791. ->where('anime_id', $anime_id)
  2792. ->where('episode_id', $episode_id)
  2793. ->where('act_number', '>', $source_act_number)
  2794. ->where('act_number', '<=', $target_act_number)
  2795. ->decrement('act_number');
  2796. // 2. 将源片段移动到目标片段之后
  2797. $new_act_number = $target_act_number;
  2798. } else {
  2799. // 向前移动:源片段移动到目标片段之后
  2800. // 1. 将目标片段之后到源片段之前的所有片段编号加1
  2801. DB::table('mp_episode_segments')
  2802. ->where('anime_id', $anime_id)
  2803. ->where('episode_id', $episode_id)
  2804. ->where('act_number', '>', $target_act_number)
  2805. ->where('act_number', '<', $source_act_number)
  2806. ->increment('act_number');
  2807. // 2. 将源片段移动到目标片段之后
  2808. $new_act_number = $target_act_number + 1;
  2809. }
  2810. // 3. 更新源片段的编号
  2811. $update_result = DB::table('mp_episode_segments')
  2812. ->where('id', $act_id)
  2813. ->update([
  2814. 'act_number' => $new_act_number,
  2815. 'updated_at' => date('Y-m-d H:i:s')
  2816. ]);
  2817. if (!$update_result) {
  2818. Utils::throwError('20003:更新片段编号失败');
  2819. }
  2820. DB::commit();
  2821. return true;
  2822. } catch (\Exception $e) {
  2823. DB::rollBack();
  2824. Utils::throwError('20003:' . $e->getMessage());
  2825. }
  2826. }
  2827. public function delAct($data) {
  2828. $act_id = getProp($data, 'act_id');
  2829. // 根据act_id获取记录(全能模式下每个act只有一条记录)
  2830. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2831. if (!$segment) Utils::throwError('20003:请选择片段');
  2832. $anime_id = getProp($segment, 'anime_id');
  2833. $episode_id = getProp($segment, 'episode_id');
  2834. $act_number = getProp($segment, 'act_number');
  2835. try {
  2836. DB::beginTransaction();
  2837. // 删除该片段记录
  2838. $deleted = DB::table('mp_episode_segments')->where('id', $act_id)->delete();
  2839. if (!$deleted) {
  2840. Utils::throwError('20003:删除片段失败');
  2841. }
  2842. // 更新后续act的编号
  2843. DB::table('mp_episode_segments')
  2844. ->where('anime_id', $anime_id)
  2845. ->where('episode_id', $episode_id)
  2846. ->where('act_number', '>', $act_number)
  2847. ->decrement('act_number');
  2848. DB::commit();
  2849. }catch (\Exception $e) {
  2850. DB::rollBack();
  2851. Utils::throwError('20003:'.$e->getMessage());
  2852. }
  2853. return true;
  2854. }
  2855. public function applyAct($data) {
  2856. $act_id = getProp($data, 'act_id');
  2857. $url = getProp($data, 'url');
  2858. if (!$act_id) Utils::throwError('20003:请选择片段');
  2859. if (!$url) Utils::throwError('20003:URL不能为空');
  2860. // 获取URL的文件扩展名
  2861. $urlPath = parse_url($url, PHP_URL_PATH);
  2862. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  2863. // 定义图片和视频的扩展名
  2864. $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
  2865. $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'];
  2866. // 判断是图片还是视频
  2867. $updateData = ['updated_at' => date('Y-m-d H:i:s')];
  2868. if (in_array($extension, $imageExtensions)) {
  2869. // 图片类型
  2870. $updateData['img_url'] = $url;
  2871. $updateData['current_type'] = 1;
  2872. } elseif (in_array($extension, $videoExtensions)) {
  2873. // 视频类型
  2874. $updateData['video_url'] = $url;
  2875. $updateData['current_type'] = 2;
  2876. } else {
  2877. Utils::throwError('20003:不支持的文件类型');
  2878. }
  2879. // 更新片段记录(全能模式下每个act只有一条记录)
  2880. $result = DB::table('mp_episode_segments')
  2881. ->where('id', $act_id)
  2882. ->update($updateData);
  2883. if (!$result) {
  2884. Utils::throwError('20003:更新片段失败');
  2885. }
  2886. return true;
  2887. }
  2888. public function actChatHistory($data) {
  2889. $act_id = getProp($data, 'act_id');
  2890. if (!$act_id) Utils::throwError('20003:请选择片段!');
  2891. $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');
  2892. $chat = $query->orderBy('id')->get()->map(function ($value) {
  2893. $value = (array)$value;
  2894. $value['created_at'] = transDate($value['created_at']);
  2895. if ($value['reference_images']) $value['reference_images'] = json_decode($value['reference_images'], 256);
  2896. else $value['reference_images'] = [];
  2897. return $value;
  2898. })->toArray();
  2899. // 获取历史图片
  2900. $url = [];
  2901. $pic_history = DB::table('mp_generate_pic_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2902. foreach($pic_history as $task) {
  2903. $result_url = getProp($task, 'result_url');
  2904. if (is_json($result_url)) {
  2905. $url = array_merge($url, json_decode($result_url, true));
  2906. }else {
  2907. $url[] = $result_url;
  2908. }
  2909. }
  2910. // 获取历史视频
  2911. $video_history = DB::table('mp_generate_video_tasks')->where('alias_act_id', $act_id)->where('status', 'success')->orderBy('created_at', 'desc')->get();
  2912. foreach($video_history as $task) {
  2913. $result_url = getProp($task, 'result_url');
  2914. if (is_json($result_url)) {
  2915. $url = array_merge($url, json_decode($result_url, true));
  2916. }else {
  2917. $url[] = $result_url;
  2918. }
  2919. }
  2920. // 获取资产库
  2921. $products = [];
  2922. // 通过act_id查询片段信息获取episode_id
  2923. $segment = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  2924. if ($segment) {
  2925. $episode_id = getProp($segment, 'episode_id');
  2926. // 查询剧集信息获取roles、scenes和extra_products
  2927. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  2928. if ($episode) {
  2929. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  2930. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  2931. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  2932. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  2933. // 先合并roles、scenes和props
  2934. // 处理角色数组
  2935. foreach ($roles as $role) {
  2936. $product = $role;
  2937. // 将role字段重命名为product_name
  2938. if (is_array($product) && !empty($product['role'] ?? null)) {
  2939. $product['product_name'] = $product['role'];
  2940. unset($product['role']);
  2941. $product['product'] = 1; // 标记类型为角色
  2942. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2943. }
  2944. }
  2945. // 处理场景数组
  2946. foreach ($scenes as $scene) {
  2947. $product = $scene;
  2948. // 将scene字段重命名为product_name
  2949. if (is_array($product) && !empty($product['scene'] ?? null)) {
  2950. $product['product_name'] = $product['scene'];
  2951. unset($product['scene']);
  2952. $product['product'] = 2; // 标记类型为场景
  2953. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2954. }
  2955. }
  2956. // 处理道具数组
  2957. foreach ($props as $prop) {
  2958. $product = $prop;
  2959. // 将prop字段重命名为product_name
  2960. if (is_array($product) && !empty($product['prop'] ?? null)) {
  2961. $product['product_name'] = $product['prop'];
  2962. unset($product['prop']);
  2963. $product['product'] = 3; // 标记类型为道具
  2964. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  2965. }
  2966. }
  2967. // extra_products优先级更高,直接覆盖同名的roles和scenes
  2968. foreach ($extra_products as $extra_product) {
  2969. $product_name = getProp($extra_product, 'product_name');
  2970. if ($product_name) {
  2971. $products[$product_name] = $extra_product; // 覆盖同名数据
  2972. }
  2973. }
  2974. // 重新索引数组(去除key)
  2975. $products = array_values($products);
  2976. }
  2977. }
  2978. // 获取执行中的任务
  2979. $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) {
  2980. $value = (array)$value;
  2981. if ($value['ref_image_url']) $value['ref_image_url'] = json_decode($value['ref_image_url'], true);
  2982. else $value['ref_image_url'] = [];
  2983. $value['status'] = $value['status'] == 'pending' ? '视频待生成' : '视频生成中';
  2984. // 处理prompt:删除人物音色部分,保留【镜头】开始的内容,并去掉<图片X>标记
  2985. if (!empty($value['prompt'])) {
  2986. $prompt = $value['prompt'];
  2987. // 查找第一个【镜头】的位置
  2988. if (preg_match('/【镜头\d+】/u', $prompt, $matches, PREG_OFFSET_CAPTURE)) {
  2989. // 从【镜头】开始截取
  2990. $prompt = substr($prompt, $matches[0][1]);
  2991. }
  2992. // 去除所有<图片X>格式的标记(X可以是任意数字)
  2993. $prompt = preg_replace('/<图片\d+>/u', '', $prompt);
  2994. $value['prompt'] = $prompt;
  2995. }
  2996. return $value;
  2997. })->toArray();
  2998. return compact('chat', 'url', 'products', 'tasks');
  2999. }
  3000. public function applyAudioData($data) {
  3001. $segment_id = getProp($data, 'segment_id');
  3002. $global_data = getProp($data, 'global_data');
  3003. $segment_data = getProp($data, 'segment_data');
  3004. if (!$segment_id) Utils::throwError('20003:请选择分镜');
  3005. $global_data = is_array($global_data) ? $global_data : [];
  3006. $segment_data = is_array($segment_data) ? $segment_data : [];
  3007. // dialogue只能在segment_data中,如果在global_data中则移到segment_data
  3008. $dialogue_item = null;
  3009. foreach ($global_data as $key => $item) {
  3010. if (trim((string)getProp($item, 'name')) === 'dialogue') {
  3011. $dialogue_item = $item;
  3012. unset($global_data[$key]);
  3013. break;
  3014. }
  3015. }
  3016. if ($dialogue_item) {
  3017. $segment_data[] = $dialogue_item;
  3018. }
  3019. // 特殊参数: audio_url,audio_duration,subtitle_info
  3020. // 这些特殊参数必须同时存在才对当前分镜有效,直接保存但不创建音频任务
  3021. // 如果不是全部存在,则仍需创建音频任务
  3022. $special_fields = ['audio_url', 'audio_duration', 'subtitle_info'];
  3023. $special_update_data = [];
  3024. $has_all_special_params = false;
  3025. // 从segment_data中提取特殊参数
  3026. $filtered_segment_data = [];
  3027. foreach ($segment_data as $item) {
  3028. $field_name = trim((string)getProp($item, 'name'));
  3029. if (in_array($field_name, $special_fields)) {
  3030. $special_update_data[$field_name] = getProp($item, 'value');
  3031. } else {
  3032. // 非特殊参数保留,继续后续处理
  3033. $filtered_segment_data[] = $item;
  3034. }
  3035. }
  3036. // 检查是否三个特殊参数都存在
  3037. if (count($special_update_data) === 3 &&
  3038. isset($special_update_data['audio_url']) &&
  3039. isset($special_update_data['audio_duration']) &&
  3040. isset($special_update_data['subtitle_info'])) {
  3041. $has_all_special_params = true;
  3042. // 立即更新到当前分镜
  3043. $special_update_data['updated_at'] = date('Y-m-d H:i:s');
  3044. DB::table('mp_episode_segments')
  3045. ->where('segment_id', $segment_id)
  3046. ->update($special_update_data);
  3047. }
  3048. // 使用过滤后的segment_data继续处理其他参数
  3049. $segment_data = $filtered_segment_data;
  3050. $allow_fields = ['dialogue', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch'];
  3051. $global_update_data = [];
  3052. $segment_update_data = [];
  3053. $global_voice_type = '';
  3054. $target_segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3055. if (!$target_segment) Utils::throwError('20003:分镜不存在');
  3056. $episode_id = getProp($target_segment, 'episode_id');
  3057. $target_voice_actor = trim((string)getProp($target_segment, 'voice_actor'));
  3058. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3059. if (!$episode) Utils::throwError('20003:分集不存在');
  3060. foreach ($global_data as $item) {
  3061. $field_name = trim((string)getProp($item, 'name'));
  3062. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3063. continue;
  3064. }
  3065. $global_update_data[$field_name] = getProp($item, 'value');
  3066. if ($field_name === 'voice_type') {
  3067. $global_voice_type = trim((string)getProp($item, 'value'));
  3068. }
  3069. }
  3070. foreach ($segment_data as $item) {
  3071. $field_name = trim((string)getProp($item, 'name'));
  3072. if (!$field_name || !in_array($field_name, $allow_fields)) {
  3073. continue;
  3074. }
  3075. $segment_update_data[$field_name] = getProp($item, 'value');
  3076. }
  3077. if ($global_voice_type) {
  3078. $timbre_info = DB::table('mp_timbres')
  3079. ->where('timbre_type', $global_voice_type)
  3080. ->select('audio_url', 'timbre_name')
  3081. ->first();
  3082. if ($timbre_info) {
  3083. $global_update_data['voice_audio_url'] = getProp($timbre_info, 'audio_url');
  3084. $global_update_data['voice_name'] = str_replace('(多情感)', '', getProp($timbre_info, 'timbre_name'));
  3085. }
  3086. }
  3087. try {
  3088. DB::beginTransaction();
  3089. // 收集需要创建音频合成任务的segment_id和对应的分镜数据
  3090. $segment_ids_to_create_task = [];
  3091. $segments_data = [];
  3092. // 如果有全局更新,获取该角色的所有分镜数据并检查是否有变化
  3093. if (!empty($global_update_data)) {
  3094. // 如果角色不存在,则只更新当前分镜
  3095. if (!$target_voice_actor) {
  3096. // 只处理当前分镜
  3097. $affected_segments = DB::table('mp_episode_segments')
  3098. ->where('segment_id', $segment_id)
  3099. ->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')
  3100. ->get();
  3101. } else {
  3102. // 获取该角色的所有分镜
  3103. $affected_segments = DB::table('mp_episode_segments')
  3104. ->where('episode_id', $episode_id)
  3105. ->where('voice_actor', $target_voice_actor)
  3106. ->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')
  3107. ->get();
  3108. }
  3109. foreach ($affected_segments as $seg) {
  3110. $seg = (array)$seg;
  3111. $sid = getProp($seg, 'segment_id');
  3112. // 检查参数是否发生变化
  3113. $has_changed = false;
  3114. foreach ($global_update_data as $field => $new_value) {
  3115. $old_value = getProp($seg, $field);
  3116. if ($old_value != $new_value) {
  3117. $has_changed = true;
  3118. break;
  3119. }
  3120. }
  3121. if ($has_changed) {
  3122. $segment_ids_to_create_task[] = $sid;
  3123. $segments_data[$sid] = $seg;
  3124. }
  3125. }
  3126. // 只有在有变化的分镜时才更新
  3127. if (!empty($segment_ids_to_create_task)) {
  3128. $global_segment_update_data = $global_update_data;
  3129. $global_segment_update_data['audio_url'] = ''; // 清空音频URL
  3130. $global_segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3131. DB::table('mp_episode_segments')
  3132. ->where('episode_id', $episode_id)
  3133. ->where('voice_actor', $target_voice_actor)
  3134. ->whereIn('segment_id', $segment_ids_to_create_task)
  3135. ->update($global_segment_update_data);
  3136. }
  3137. if ($global_voice_type) {
  3138. $episode_roles = json_decode((string)getProp($episode, 'roles'), true);
  3139. $episode_roles = is_array($episode_roles) ? $episode_roles : [];
  3140. $roles_updated = false;
  3141. foreach ($episode_roles as &$role) {
  3142. // 通过 role 字段匹配角色名,而不是 voice_name
  3143. if (trim((string)getProp($role, 'role')) !== $target_voice_actor) {
  3144. continue;
  3145. }
  3146. $role['voice_type'] = $global_voice_type;
  3147. $role['voice_audio_url'] = getProp($global_update_data, 'voice_audio_url');
  3148. $role['voice_name'] = getProp($global_update_data, 'voice_name');
  3149. $roles_updated = true;
  3150. }
  3151. unset($role);
  3152. if ($roles_updated) {
  3153. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3154. 'roles' => json_encode($episode_roles, 256),
  3155. 'updated_at' => date('Y-m-d H:i:s'),
  3156. ]);
  3157. }
  3158. }
  3159. }
  3160. // 如果有单个分镜更新,检查是否有变化
  3161. if (!empty($segment_update_data)) {
  3162. // 获取当前分镜数据
  3163. $current_segment = DB::table('mp_episode_segments')
  3164. ->where('segment_id', $segment_id)
  3165. ->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')
  3166. ->first();
  3167. if ($current_segment) {
  3168. $current_segment = (array)$current_segment;
  3169. // 检查参数是否发生变化
  3170. $has_changed = false;
  3171. foreach ($segment_update_data as $field => $new_value) {
  3172. $old_value = getProp($current_segment, $field);
  3173. if ($old_value != $new_value) {
  3174. $has_changed = true;
  3175. break;
  3176. }
  3177. }
  3178. if ($has_changed) {
  3179. // 如果该分镜还未在列表中,添加进去
  3180. if (!in_array($segment_id, $segment_ids_to_create_task)) {
  3181. $segment_ids_to_create_task[] = $segment_id;
  3182. $segments_data[$segment_id] = $current_segment;
  3183. }
  3184. // 更新分镜数据并清空音频URL
  3185. $segment_update_data['audio_url'] = '';
  3186. $segment_update_data['updated_at'] = date('Y-m-d H:i:s');
  3187. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update($segment_update_data);
  3188. }
  3189. }
  3190. }
  3191. // 为所有有变化的分镜创建音频合成任务
  3192. // 但如果当前分镜同时设置了全部三个特殊参数(audio_url, audio_duration, subtitle_info),则跳过该分镜
  3193. if (!empty($segment_ids_to_create_task)) {
  3194. foreach ($segment_ids_to_create_task as $sid) {
  3195. // 如果当前分镜同时设置了全部三个特殊参数,则跳过音频任务创建
  3196. if ($sid === $segment_id && $has_all_special_params) {
  3197. continue;
  3198. }
  3199. // 重新获取更新后的分镜数据
  3200. $updated_segment = DB::table('mp_episode_segments')
  3201. ->where('segment_id', $sid)
  3202. ->select('voice_actor', 'dialogue', 'voice_type', 'voice_name', 'emotion', 'emotion_type', 'gender', 'speed_ratio', 'loudness_ratio', 'emotion_scale', 'pitch')
  3203. ->first();
  3204. if (!$updated_segment) continue;
  3205. $updated_segment = (array)$updated_segment;
  3206. // 检查dialogue是否为空
  3207. $dialogue = getProp($updated_segment, 'dialogue');
  3208. if (empty($dialogue)) {
  3209. // dialogue为空时,直接写入默认音频信息
  3210. DB::table('mp_episode_segments')->where('segment_id', $sid)->update([
  3211. 'audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3',
  3212. 'audio_duration' => 2.0,
  3213. 'subtitle_info' => json_encode(['duration' => 2.0, 'words' => []], 256),
  3214. 'updated_at' => date('Y-m-d H:i:s')
  3215. ]);
  3216. continue;
  3217. }
  3218. $generate_json = [
  3219. 'text' => $dialogue,
  3220. 'role' => getProp($updated_segment, 'voice_actor'),
  3221. 'voice_type' => getProp($updated_segment, 'voice_type'),
  3222. 'voice_name' => getProp($updated_segment, 'voice_name'),
  3223. 'emotion' => getProp($updated_segment, 'emotion'),
  3224. 'emotion_type' => getProp($updated_segment, 'emotion_type'),
  3225. 'gender' => getProp($updated_segment, 'gender'),
  3226. 'speed_ratio' => getProp($updated_segment, 'speed_ratio', 0),
  3227. 'loudness_ratio' => getProp($updated_segment, 'loudness_ratio', 0),
  3228. 'emotion_scale' => getProp($updated_segment, 'emotion_scale', 0),
  3229. 'pitch' => getProp($updated_segment, 'pitch', 0),
  3230. ];
  3231. // 插入视频配音合成任务
  3232. $dubTaskId = DB::table('mp_dub_video_tasks')->insertGetId([
  3233. 'alias_segment_id' => $sid,
  3234. 'generate_status' => '执行中',
  3235. 'audio_url' => '',
  3236. 'generate_json' => json_encode($generate_json, 256),
  3237. 'created_at' => date('Y-m-d H:i:s'),
  3238. 'updated_at' => date('Y-m-d H:i:s'),
  3239. ]);
  3240. if (!$dubTaskId) {
  3241. dLog('anime')->error('创建配音任务失败', ['segment_id' => $sid]);
  3242. continue;
  3243. }
  3244. // 将任务ID添加到Redis列表中
  3245. Redis::lpush('dub_video_task_queue', $dubTaskId);
  3246. // 请求远程服务器执行生成
  3247. try {
  3248. sleep(1);
  3249. $client = new Client(['timeout' => 300, 'verify' => false]);
  3250. $result = $client->get("http://122.9.129.83:5000/api/anime/genAudio?taskId={$dubTaskId}");
  3251. $response = $result->getBody()->getContents();
  3252. $response_arr = json_decode($response, true);
  3253. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3254. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3255. dLog('anime')->error('火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3256. logDB('anime', 'error', '火山生成音频失败', ['error' => $error_msg, 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3257. }
  3258. } catch (\Exception $e) {
  3259. dLog('anime')->error('调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3260. logDB('anime', 'error', '调用音频生成API失败', ['error' => $e->getMessage(), 'task_id' => $dubTaskId, 'segment_id' => $sid]);
  3261. }
  3262. }
  3263. }
  3264. DB::commit();
  3265. } catch (\Exception $e) {
  3266. DB::rollBack();
  3267. Utils::throwError('20003:'.$e->getMessage());
  3268. }
  3269. return true;
  3270. }
  3271. public function episodePicsInfo($data) {
  3272. $anime_id = getProp($data, 'anime_id');
  3273. $episode_id = getProp($data, 'episode_id');
  3274. // 参数验证
  3275. if (!$anime_id && !$episode_id) {
  3276. Utils::throwError('20003:请提供动漫ID或分集ID');
  3277. }
  3278. // 根据参数获取数据源
  3279. if ($episode_id) {
  3280. // 从剧集表获取
  3281. $source = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3282. if (!$source) Utils::throwError('20003:该剧集不存在');
  3283. $table_name = 'mp_anime_episodes';
  3284. $id_field = 'id';
  3285. $id_value = $episode_id;
  3286. // 获取剧集的anime_id用于继承全局数据
  3287. $anime_id = getProp($source, 'anime_id');
  3288. } else {
  3289. // 从动漫表获取
  3290. $source = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3291. if (!$source) Utils::throwError('20003:该动漫不存在');
  3292. $table_name = 'mp_animes';
  3293. $id_field = 'id';
  3294. $id_value = $anime_id;
  3295. }
  3296. $source = (array)$source;
  3297. $roles = json_decode(getProp($source, 'roles', '[]'), true) ?: [];
  3298. $scenes = json_decode(getProp($source, 'scenes', '[]'), true) ?: [];
  3299. $props = json_decode(getProp($source, 'props', '[]'), true) ?: [];
  3300. // 如果是分集数据,需要处理继承和任务创建逻辑
  3301. if ($episode_id) {
  3302. $this->processEpisodeRolesAndScenes($episode_id, $anime_id, $roles, $scenes, $source);
  3303. }
  3304. // 返回生成器函数,用于 SSE 流式输出
  3305. return function() use ($roles, $scenes, $props, $table_name, $id_field, $id_value) {
  3306. $startTime = time();
  3307. $maxDuration = 600; // 10分钟超时
  3308. $checkInterval = 3; // 每3秒检查一次
  3309. // Redis 缓存键
  3310. $cacheKey = "anime:pics_info:{$table_name}:{$id_value}";
  3311. // 生成当前数据的哈希值用于比较
  3312. $generateHash = function($roles, $scenes, $props) {
  3313. return md5(json_encode(['roles' => $roles, 'scenes' => $scenes, 'props' => $props], JSON_UNESCAPED_UNICODE));
  3314. };
  3315. // 发送初始数据
  3316. $currentHash = $generateHash($roles, $scenes, $props);
  3317. Redis::setex($cacheKey, 600, $currentHash); // 缓存10分钟
  3318. echo "data: " . json_encode([
  3319. 'type' => 'init',
  3320. 'data' => [
  3321. 'roles' => $roles,
  3322. 'scenes' => $scenes,
  3323. 'props' => $props,
  3324. 'start_time' => $startTime
  3325. ]
  3326. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3327. if (ob_get_level() > 0) {
  3328. ob_flush();
  3329. }
  3330. flush();
  3331. // 持续轮询任务状态
  3332. while (time() - $startTime < $maxDuration) {
  3333. $hasProcessing = false;
  3334. $updated = false;
  3335. // 检查角色任务状态
  3336. foreach ($roles as $index => &$role) {
  3337. $task_id = getProp($role, 'task_id');
  3338. $task_status = getProp($role, 'task_status');
  3339. $existing_url = getProp($role, 'url');
  3340. // 只处理有任务ID且状态为processing的角色,或者状态为processing但没有URL的角色
  3341. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3342. $hasProcessing = ($task_status === 'processing');
  3343. // 查询任务状态
  3344. $task = DB::table('mp_generate_pic_tasks')
  3345. ->where('id', $task_id)
  3346. ->select('id', 'status', 'result_url', 'error_message')
  3347. ->first();
  3348. if ($task) {
  3349. $task = (array)$task;
  3350. $status = getProp($task, 'status');
  3351. // 如果任务完成或失败
  3352. if (in_array($status, ['success', 'failed'])) {
  3353. $role['task_status'] = $status;
  3354. if ($status === 'success') {
  3355. $result_url = getProp($task, 'result_url');
  3356. if ($result_url) {
  3357. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3358. if (is_array($result_urls) && !empty($result_urls[0])) {
  3359. $role['url'] = $result_urls[0];
  3360. }
  3361. }
  3362. }
  3363. $updated = true;
  3364. } else if ($status === 'processing') {
  3365. $hasProcessing = true;
  3366. }
  3367. }
  3368. }
  3369. }
  3370. // 检查场景任务状态
  3371. foreach ($scenes as $index => &$scene) {
  3372. $task_id = getProp($scene, 'task_id');
  3373. $task_status = getProp($scene, 'task_status');
  3374. $existing_url = getProp($scene, 'url');
  3375. // 只处理有任务ID且状态为processing的场景,或者状态为success但没有URL的场景
  3376. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3377. $hasProcessing = ($task_status === 'processing');
  3378. // 查询任务状态
  3379. $task = DB::table('mp_generate_pic_tasks')
  3380. ->where('id', $task_id)
  3381. ->select('id', 'status', 'result_url', 'error_message')
  3382. ->first();
  3383. if ($task) {
  3384. $task = (array)$task;
  3385. $status = getProp($task, 'status');
  3386. // 如果任务完成或失败
  3387. if (in_array($status, ['success', 'failed'])) {
  3388. $scene['task_status'] = $status;
  3389. if ($status === 'success') {
  3390. $result_url = getProp($task, 'result_url');
  3391. if ($result_url) {
  3392. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3393. if (is_array($result_urls) && !empty($result_urls[0])) {
  3394. $scene['url'] = $result_urls[0];
  3395. }
  3396. }
  3397. }
  3398. $updated = true;
  3399. } else if ($status === 'processing') {
  3400. $hasProcessing = true;
  3401. }
  3402. }
  3403. }
  3404. }
  3405. // 检查道具任务状态
  3406. foreach ($props as $index => &$prop) {
  3407. $task_id = getProp($prop, 'task_id');
  3408. $task_status = getProp($prop, 'task_status');
  3409. $existing_url = getProp($prop, 'url');
  3410. // 只处理有任务ID且状态为processing的道具,或者状态为success但没有URL的道具
  3411. if ($task_id && ($task_status === 'processing' || (in_array($task_status, ['success', 'completed']) && empty($existing_url)))) {
  3412. $hasProcessing = ($task_status === 'processing');
  3413. // 查询任务状态
  3414. $task = DB::table('mp_generate_pic_tasks')
  3415. ->where('id', $task_id)
  3416. ->select('id', 'status', 'result_url', 'error_message')
  3417. ->first();
  3418. if ($task) {
  3419. $task = (array)$task;
  3420. $status = getProp($task, 'status');
  3421. // 如果任务完成或失败
  3422. if (in_array($status, ['success', 'failed'])) {
  3423. $prop['task_status'] = $status;
  3424. if ($status === 'success') {
  3425. $result_url = getProp($task, 'result_url');
  3426. if ($result_url) {
  3427. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  3428. if (is_array($result_urls) && !empty($result_urls[0])) {
  3429. $prop['url'] = $result_urls[0];
  3430. }
  3431. }
  3432. }
  3433. $updated = true;
  3434. } else if ($status === 'processing') {
  3435. $hasProcessing = true;
  3436. }
  3437. }
  3438. }
  3439. }
  3440. // 如果有更新,检查数据是否真的变化了(通过哈希对比)
  3441. if ($updated) {
  3442. $newHash = $generateHash($roles, $scenes, $props);
  3443. $cachedHash = Redis::get($cacheKey);
  3444. // 只有当数据真正变化时才更新数据库和发送事件
  3445. if ($newHash !== $cachedHash) {
  3446. try {
  3447. // 更新数据库
  3448. DB::table($table_name)->where($id_field, $id_value)->update([
  3449. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3450. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3451. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3452. 'updated_at' => date('Y-m-d H:i:s')
  3453. ]);
  3454. // 更新缓存
  3455. Redis::setex($cacheKey, 600, $newHash);
  3456. // 发送更新事件
  3457. echo "data: " . json_encode([
  3458. 'type' => 'update',
  3459. 'data' => [
  3460. 'roles' => $roles,
  3461. 'scenes' => $scenes,
  3462. 'props' => $props,
  3463. 'elapsed_time' => time() - $startTime
  3464. ]
  3465. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3466. if (ob_get_level() > 0) {
  3467. ob_flush();
  3468. }
  3469. flush();
  3470. } catch (\Exception $e) {
  3471. dLog('anime')->error('更新角色/场景/道具信息失败: ' . $e->getMessage());
  3472. }
  3473. } else {
  3474. // 即使哈希相同,如果有URL更新也要发送事件
  3475. $hasUrlUpdate = false;
  3476. foreach ($roles as $role) {
  3477. if (!empty(getProp($role, 'url')) && getProp($role, 'task_status') === 'success') {
  3478. $hasUrlUpdate = true;
  3479. break;
  3480. }
  3481. }
  3482. if (!$hasUrlUpdate) {
  3483. foreach ($scenes as $scene) {
  3484. if (!empty(getProp($scene, 'url')) && getProp($scene, 'task_status') === 'success') {
  3485. $hasUrlUpdate = true;
  3486. break;
  3487. }
  3488. }
  3489. }
  3490. if (!$hasUrlUpdate) {
  3491. foreach ($props as $prop) {
  3492. if (!empty(getProp($prop, 'url')) && getProp($prop, 'task_status') === 'success') {
  3493. $hasUrlUpdate = true;
  3494. break;
  3495. }
  3496. }
  3497. }
  3498. if ($hasUrlUpdate) {
  3499. // 强制更新数据库和发送事件
  3500. try {
  3501. DB::table($table_name)->where($id_field, $id_value)->update([
  3502. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  3503. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  3504. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  3505. 'updated_at' => date('Y-m-d H:i:s')
  3506. ]);
  3507. // 更新缓存
  3508. Redis::setex($cacheKey, 600, $newHash);
  3509. // 发送更新事件
  3510. echo "data: " . json_encode([
  3511. 'type' => 'update',
  3512. 'data' => [
  3513. 'roles' => $roles,
  3514. 'scenes' => $scenes,
  3515. 'props' => $props,
  3516. 'elapsed_time' => time() - $startTime
  3517. ]
  3518. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3519. if (ob_get_level() > 0) {
  3520. ob_flush();
  3521. }
  3522. flush();
  3523. } catch (\Exception $e) {
  3524. dLog('anime')->error('强制更新角色/场景/道具信息失败: ' . $e->getMessage());
  3525. }
  3526. }
  3527. }
  3528. }
  3529. // 如果所有任务都已完成,发送完成事件并退出
  3530. if (!$hasProcessing) {
  3531. // 查询数据库中的最终数据,确保返回最新的完整数据
  3532. try {
  3533. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3534. if ($finalSource) {
  3535. $finalSource = (array)$finalSource;
  3536. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3537. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3538. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3539. // 使用数据库中的最终数据
  3540. $roles = $finalRoles;
  3541. $scenes = $finalScenes;
  3542. $props = $finalProps;
  3543. }
  3544. } catch (\Exception $e) {
  3545. dLog('anime')->error('查询最终数据失败: ' . $e->getMessage());
  3546. // 如果查询失败,继续使用内存中的数据
  3547. }
  3548. // 清理缓存
  3549. Redis::del($cacheKey);
  3550. echo "data: " . json_encode([
  3551. 'type' => 'completed',
  3552. 'data' => [
  3553. 'roles' => $roles,
  3554. 'scenes' => $scenes,
  3555. 'props' => $props,
  3556. 'total_time' => time() - $startTime
  3557. ]
  3558. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3559. if (ob_get_level() > 0) {
  3560. ob_flush();
  3561. }
  3562. flush();
  3563. break;
  3564. }
  3565. // 等待下次检查
  3566. sleep($checkInterval);
  3567. }
  3568. // 超时处理
  3569. if (time() - $startTime >= $maxDuration) {
  3570. // 查询数据库中的最终数据,即使超时也要返回最新数据
  3571. try {
  3572. $finalSource = DB::table($table_name)->where($id_field, $id_value)->first();
  3573. if ($finalSource) {
  3574. $finalSource = (array)$finalSource;
  3575. $finalRoles = json_decode(getProp($finalSource, 'roles', '[]'), true) ?: [];
  3576. $finalScenes = json_decode(getProp($finalSource, 'scenes', '[]'), true) ?: [];
  3577. $finalProps = json_decode(getProp($finalSource, 'props', '[]'), true) ?: [];
  3578. // 使用数据库中的最终数据
  3579. $roles = $finalRoles;
  3580. $scenes = $finalScenes;
  3581. $props = $finalProps;
  3582. }
  3583. } catch (\Exception $e) {
  3584. dLog('anime')->error('超时时查询最终数据失败: ' . $e->getMessage());
  3585. // 如果查询失败,继续使用内存中的数据
  3586. }
  3587. // 清理缓存
  3588. Redis::del($cacheKey);
  3589. echo "data: " . json_encode([
  3590. 'type' => 'timeout',
  3591. 'message' => '轮询超时,请刷新页面查看最新状态',
  3592. 'data' => [
  3593. 'roles' => $roles,
  3594. 'scenes' => $scenes,
  3595. 'props' => $props
  3596. ]
  3597. ], JSON_UNESCAPED_UNICODE) . "\n\n";
  3598. if (ob_get_level() > 0) {
  3599. ob_flush();
  3600. }
  3601. flush();
  3602. }
  3603. };
  3604. }
  3605. public function clipSegmentVideo($data) {
  3606. $segment_id = getProp($data, 'segment_id');
  3607. $video_time_point_start = getProp($data, 'video_time_point_start');
  3608. $video_time_point_end = getProp($data, 'video_time_point_end');
  3609. if (!$segment_id || !$video_time_point_start || !$video_time_point_end) {
  3610. Utils::throwError('20003:参数异常');
  3611. }
  3612. if (!DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('video_url')) {
  3613. Utils::throwError('20003:该分镜没有视频,无法裁剪');
  3614. }
  3615. $video_duration = $video_time_point_end - $video_time_point_start;
  3616. if (!$video_duration < 0) Utils::throwError('20003:参数异常');
  3617. return DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  3618. 'video_duration' => $video_duration,
  3619. 'video_time_point_start' => $video_time_point_start,
  3620. 'video_time_point_end' => $video_time_point_end,
  3621. 'updated_at' => date('Y-m-d H:i:s')
  3622. ]);
  3623. }
  3624. // 轮训获取图片任务结果
  3625. private function loopGetPicTaskResult($task_id) {
  3626. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3627. if (!$task) {
  3628. return '';
  3629. }
  3630. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  3631. $model = getProp($task, 'model');
  3632. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  3633. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  3634. $isSyncModel = $isVolcModel || $isGptModel;
  3635. // 轮询查询任务状态(火山API和即梦AI都需要轮询)
  3636. $start_count = 0;
  3637. $img_url = '';
  3638. while ($start_count <= 60) { // 循环20次请求,每3s一次
  3639. sleep(3);
  3640. $task = MpGeneratePicTask::where('id', $task_id)->first();
  3641. // 如果任务已经完成,直接返回结果
  3642. if ($task->status === 'success' && $task->result_url) {
  3643. $result_urls = is_array($task->result_url) ? $task->result_url : json_decode($task->result_url, true);
  3644. return is_array($result_urls) ? $result_urls[0] : $task->result_url;
  3645. }
  3646. // 如果任务已失败,返回空
  3647. if ($task->status === 'failed') {
  3648. return '';
  3649. }
  3650. if ($isSyncModel) continue;
  3651. // 查询任务状态
  3652. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  3653. if ($statusInfo['status'] === 'success') {
  3654. $task->updateStatus('success', [
  3655. 'result_url' => $statusInfo['result_url'],
  3656. 'result_json' => $statusInfo['result_json'] ?? []
  3657. ]);
  3658. // 同步调整分镜图片状态和结果
  3659. if (getProp($task, 'alias_segment_id')) {
  3660. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3661. 'img_url' => $statusInfo['result_url'][0],
  3662. 'pic_task_status' => '已完成',
  3663. ]);
  3664. }
  3665. $img_url = $statusInfo['result_url'][0];
  3666. break;
  3667. } elseif ($statusInfo['status'] === 'failed') {
  3668. $task->updateStatus('failed', [
  3669. 'error_message' => $statusInfo['error_message'],
  3670. 'result_json' => $statusInfo['result_json'] ?? []
  3671. ]);
  3672. if (getProp($task, 'alias_segment_id')) {
  3673. DB::table('mp_episode_segments')->where('segment_id', getProp($task, 'alias_segment_id'))->update([
  3674. 'pic_task_status' => '失败',
  3675. ]);
  3676. }
  3677. break;
  3678. }
  3679. $start_count++;
  3680. }
  3681. return $img_url;
  3682. }
  3683. /**
  3684. * 从分镜内容中提取涉及的角色
  3685. */
  3686. private function extractCharactersFromSegment($segment_content, $available_characters, $roles) {
  3687. $found_characters = [];
  3688. foreach ($available_characters as $character) {
  3689. // 检查角色名称是否在分镜内容中出现
  3690. if (strpos($segment_content, $character) !== false) {
  3691. $found_characters[] = $character;
  3692. }
  3693. }
  3694. if (!$found_characters) {
  3695. foreach ($roles as $character) {
  3696. // 检查角色名称是否在分镜内容中出现
  3697. if (strpos($segment_content, $character) !== false) {
  3698. $found_characters[] = $character;
  3699. }
  3700. }
  3701. }
  3702. return array_unique($found_characters);
  3703. }
  3704. // 从分镜剧本中提取关键字段
  3705. private function handleSegmentContent(&$data) {
  3706. $segmentContent = getProp($data, 'segment_content');
  3707. // 解析分镜详细信息 - 与 Helpers.php 中 handleEpisodeContent 的 segmentData 结构保持一致
  3708. $segmentData = [
  3709. 'description' => '',
  3710. 'composition' => '',
  3711. 'camera_movement' => '',
  3712. 'voice_actor' => '',
  3713. 'dialogue' => '',
  3714. 'frame_type' => '',
  3715. 'scene' => '', // 场景
  3716. 'characters' => '', // 出镜角色
  3717. 'tail_frame' => '', // 尾帧描述
  3718. 'emotion' => '中性', // 情感
  3719. 'gender' => '0', // 性别(0未知,1男,2女)
  3720. 'speed_ratio' => 0, // 语速
  3721. 'loudness_ratio' => 0, // 音量
  3722. 'emotion_scale' => 4, // 情感强度
  3723. 'pitch' => 0, // 音调
  3724. ];
  3725. // 用于存储需要从 segment_content 中移除的匹配项
  3726. $replaceEmptyArr = [];
  3727. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  3728. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3729. $segmentData['description'] = trim($descMatch[1]);
  3730. $data['description'] = trim($descMatch[1]);
  3731. }
  3732. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3733. $segmentData['composition'] = trim($compMatch[1]);
  3734. $data['composition'] = trim($compMatch[1]);
  3735. }
  3736. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3737. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3738. $data['camera_movement'] = trim($cameraMatch[1]);
  3739. }
  3740. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3741. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3742. $data['voice_actor'] = trim($voiceMatch[1]);
  3743. }
  3744. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3745. $segmentData['dialogue'] = trim($dialogueMatch[1]);
  3746. $data['dialogue'] = trim($dialogueMatch[1]);
  3747. }
  3748. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3749. $segmentData['frame_type'] = trim($frameMatch[1]);
  3750. $data['frame_type'] = trim($frameMatch[1]);
  3751. }
  3752. // 场景字段
  3753. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3754. $segmentData['scene'] = trim($sceneMatch[1]);
  3755. $data['scene'] = trim($sceneMatch[1]);
  3756. }
  3757. // 出镜角色字段
  3758. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3759. $segmentData['characters'] = trim($charactersMatch[1]);
  3760. $data['characters'] = trim($charactersMatch[1]);
  3761. }
  3762. // 尾帧描述字段
  3763. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3764. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3765. $data['tail_frame'] = trim($tailFrameMatch[1]);
  3766. }
  3767. // 情感字段
  3768. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3769. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3770. $segmentData['emotion'] = trim($emotionMatch[1]);
  3771. $data['emotion'] = trim($emotionMatch[1]);
  3772. }
  3773. // 性别字段
  3774. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3775. $replaceEmptyArr[] = trim($genderMatch[0]);
  3776. $genderStr = trim($genderMatch[1]);
  3777. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3778. $segmentData['gender'] = '1';
  3779. $data['gender'] = '1';
  3780. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3781. $segmentData['gender'] = '2';
  3782. $data['gender'] = '2';
  3783. } else {
  3784. $segmentData['gender'] = '0';
  3785. $data['gender'] = '0';
  3786. }
  3787. }
  3788. // 语速字段
  3789. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3790. $replaceEmptyArr[] = trim($speedMatch[0]);
  3791. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3792. $data['speed_ratio'] = (float)trim($speedMatch[1]);
  3793. }
  3794. // 音量字段
  3795. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3796. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3797. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3798. $data['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3799. }
  3800. // 情感强度字段
  3801. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3802. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3803. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3804. $data['emotion_scale'] = (int)trim($scaleMatch[1]);
  3805. }
  3806. // 音调字段
  3807. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3808. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3809. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3810. $data['pitch'] = (int)trim($pitchMatch[1]);
  3811. }
  3812. // 从 segment_content 中移除已提取的配音参数字段
  3813. if (!empty($replaceEmptyArr)) {
  3814. $data['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3815. }
  3816. // 如果有配音角色,查询音色信息并验证情感
  3817. $voice_actor = $segmentData['voice_actor'];
  3818. if (!empty($voice_actor) && $voice_actor !== '旁白') {
  3819. // 从当前分镜所属的剧集或动漫中查找角色音色信息
  3820. $anime_id = getProp($data, 'anime_id');
  3821. $episode_id = getProp($data, 'episode_id');
  3822. // 优先从剧集的角色列表中查找
  3823. $roles = [];
  3824. if ($episode_id) {
  3825. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  3826. if ($episode && getProp($episode, 'roles')) {
  3827. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  3828. }
  3829. }
  3830. // 如果剧集中没有,从动漫的角色列表中查找
  3831. if (empty($roles) && $anime_id) {
  3832. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3833. if ($anime && getProp($anime, 'roles')) {
  3834. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  3835. }
  3836. }
  3837. // 查找匹配的角色音色信息
  3838. $timbre_info = null;
  3839. foreach ($roles as $role) {
  3840. if (getProp($role, 'role') === $voice_actor) {
  3841. $timbre_info = $role;
  3842. break;
  3843. }
  3844. }
  3845. // 如果找到音色信息,添加到数据中
  3846. if ($timbre_info) {
  3847. $voice_type = getProp($timbre_info, 'voice_type');
  3848. $voice_name = getProp($timbre_info, 'voice_name');
  3849. $voice_audio_url = getProp($timbre_info, 'voice_audio_url');
  3850. if ($voice_type) {
  3851. $data['voice_type'] = $voice_type;
  3852. $segmentData['voice_type'] = $voice_type;
  3853. }
  3854. if ($voice_name) {
  3855. $data['voice_name'] = $voice_name;
  3856. $segmentData['voice_name'] = $voice_name;
  3857. }
  3858. if ($voice_audio_url) {
  3859. $data['voice_audio_url'] = $voice_audio_url;
  3860. $segmentData['voice_audio_url'] = $voice_audio_url;
  3861. }
  3862. // 验证情感是否在音色支持的情感列表中
  3863. if ($voice_type) {
  3864. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  3865. if ($timbre_emotion) {
  3866. $timbre_emotion = explode(',', $timbre_emotion);
  3867. } else {
  3868. $timbre_emotion = [];
  3869. }
  3870. $emotion = getProp($segmentData, 'emotion', '中性');
  3871. if (!in_array($emotion, $timbre_emotion)) {
  3872. $emotion = '中性';
  3873. }
  3874. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3875. $emotion_list = array_flip($emotion_list);
  3876. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3877. $data['emotion_type'] = $emotion_type;
  3878. $segmentData['emotion_type'] = $emotion_type;
  3879. }
  3880. }
  3881. }
  3882. return $segmentData;
  3883. }
  3884. public function createSegmentVideoTask($data) {
  3885. $segment_id = getProp($data, 'segment_id');
  3886. $tail_frame = getProp($data, 'tail_frame');
  3887. $first_frame_url = getProp($data, 'first_frame_url');
  3888. $tail_frame_url = getProp($data, 'tail_frame_url');
  3889. $generate_audio = getProp($data, 'generate_audio', 0);
  3890. if (!$segment_id) {
  3891. Utils::throwError('1002:分镜ID不能为空');
  3892. }
  3893. // 获取分镜信息
  3894. $segment = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->first();
  3895. if (!$segment) {
  3896. Utils::throwError('20003:分镜不存在');
  3897. }
  3898. $segment = (array)$segment;
  3899. $episode_id = getProp($segment, 'episode_id');
  3900. $ratio = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('ratio');
  3901. if (!$ratio) $ratio = '9:16';
  3902. // 获取分镜内容
  3903. $segmentContent = getProp($segment, 'segment_content', '');
  3904. // 检查 $segmentContent 中是否已有尾帧描述
  3905. $contentHasTailFrame = preg_match('/(?:尾帧描述|尾帧)[::]\s*([^\n]+)/u', $segmentContent, $contentTailFrameMatch);
  3906. // 确定最终使用的尾帧描述(优先级:用户输入 > segmentContent自带 > 分镜表字段)
  3907. $finalTailFrame = '';
  3908. if ($tail_frame) {
  3909. // 用户输入了尾帧描述,优先使用
  3910. $finalTailFrame = $tail_frame;
  3911. // 如果 segmentContent 中已有尾帧描述,需要替换
  3912. if ($contentHasTailFrame) {
  3913. $segmentContent = preg_replace('/(?:尾帧描述|尾帧)[::]\s*[^\n]+/u', "尾帧描述:$tail_frame", $segmentContent);
  3914. }
  3915. } elseif ($contentHasTailFrame) {
  3916. // segmentContent 中有尾帧描述,使用它
  3917. $finalTailFrame = trim($contentTailFrameMatch[1]);
  3918. } else {
  3919. // 两者都没有,使用分镜表中的尾帧描述
  3920. $finalTailFrame = getProp($segment, 'tail_frame', '');
  3921. }
  3922. // 判断 $segmentContent 是否有台词内容,如果有则确保使用中文左右双引号
  3923. $hasDialogue = false;
  3924. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  3925. $dialogue = trim($dialogueMatch[1]);
  3926. // 如果台词不为空且不是"无"
  3927. if (!empty($dialogue) && $dialogue !== '无') {
  3928. // 过滤掉所有符号(引号、标点、空格等),只保留文字内容来判断是否有实际台词
  3929. $dialogueFiltered = preg_replace('/[""\'\',。!?、;:…—\-\s\p{P}\p{S}]/u', '', $dialogue);
  3930. if (!empty($dialogueFiltered) && $dialogueFiltered !== '无') {
  3931. $hasDialogue = true;
  3932. }
  3933. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  3934. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  3935. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  3936. if (!preg_match('/^[“]/', $dialogue)) {
  3937. $dialogue = '“' . $dialogue;
  3938. }
  3939. if (!preg_match('/[”]$/', $dialogue)) {
  3940. $dialogue .= '”';
  3941. }
  3942. // 将修改后的台词替换回 $segmentContent
  3943. $originalDialogue = $dialogueMatch[1];
  3944. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  3945. }
  3946. }
  3947. // 构建完整的提示词
  3948. $fullPrompt = $segmentContent;
  3949. if ($finalTailFrame && !$contentHasTailFrame) {
  3950. // 只有当 segmentContent 中没有尾帧描述时才追加
  3951. $fullPrompt .= "\n尾帧描述:$finalTailFrame";
  3952. }
  3953. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  3954. $fullPrompt = preg_replace('/\n{2,}/', "\n", $fullPrompt);
  3955. $fullPrompt = trim($fullPrompt);
  3956. // 当前是否启用音效同出(没台词强制关闭音效同出,节省资源收费)
  3957. $current_generate_audio = $hasDialogue ? $generate_audio : 0;
  3958. // 智能选择视频时长
  3959. // $videoDuration = $this->calculateOptimalVideoDuration($segmentContent, $tail_frame);
  3960. $videoDuration = -1;
  3961. // 处理视频模型
  3962. $model = getProp($data, 'model');
  3963. if (!$model) {
  3964. // 用户没有输入,从episode表获取
  3965. $episode = DB::table('mp_anime_episodes')->where('id', getProp($segment, 'episode_id'))->first();
  3966. $model = getProp($episode, 'video_model');
  3967. if (!$model) {
  3968. // episode表也没有,使用默认值
  3969. $model = 'doubao-seedance-1-5-pro-251215';
  3970. }
  3971. }
  3972. // 验证模型是否在可用模型表中
  3973. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3974. $model = 'doubao-seedance-1-5-pro-251215';
  3975. }
  3976. // 保存到episode表
  3977. $episode_id = getProp($segment, 'episode_id');
  3978. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  3979. 'video_model' => $model,
  3980. 'updated_at' => date('Y-m-d H:i:s')
  3981. ]);
  3982. // 构建视频生成参数
  3983. $videoParams = [
  3984. 'model' => $model,
  3985. 'alias_segment_id' => $segment_id,
  3986. 'prompt' => trim($fullPrompt),
  3987. 'video_duration' => $videoDuration,
  3988. 'video_resolution' => '720P',
  3989. 'seed' => -1,
  3990. 'ratio' => $ratio,
  3991. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  3992. 'draft' => false,
  3993. 'watermark' => false,
  3994. 'camera_fixed' => false,
  3995. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  3996. ];
  3997. // 如果分镜有图片,作为首帧
  3998. $hasImage = !empty(getProp($segment, 'img_url')) || $first_frame_url;
  3999. $hasVideo = !empty(getProp($segment, 'video_url'));
  4000. if ($hasImage) {
  4001. if ($first_frame_url) {
  4002. $videoParams['first_frame_url'] = $first_frame_url;
  4003. }else {
  4004. $videoParams['first_frame_url'] = getProp($segment, 'img_url');
  4005. }
  4006. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4007. }
  4008. // 构建content数组
  4009. $videoParams['content'] = [
  4010. [
  4011. 'type' => 'text',
  4012. 'text' => $videoParams['prompt'],
  4013. ]
  4014. ];
  4015. // 如果有首帧图片,添加到content中
  4016. if ($hasImage) {
  4017. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615'])) {
  4018. $videoParams['content'][] = [
  4019. 'type' => 'image_url',
  4020. 'image_url' => [
  4021. 'url' => $videoParams['first_frame_url'],
  4022. ],
  4023. 'role' => 'reference_image',
  4024. ];
  4025. if (isset($videoParams['tail_frame_url'])) {
  4026. $videoParams['content'][] = [
  4027. 'type' => 'image_url',
  4028. 'image_url' => [
  4029. 'url' => $videoParams['tail_frame_url'],
  4030. ],
  4031. 'role' => 'reference_image',
  4032. ];
  4033. }
  4034. }else {
  4035. $videoParams['content'][] = [
  4036. 'type' => 'image_url',
  4037. 'image_url' => [
  4038. 'url' => $videoParams['first_frame_url'],
  4039. ],
  4040. 'role' => 'first_frame',
  4041. ];
  4042. if (isset($videoParams['tail_frame_url'])) {
  4043. $videoParams['content'][] = [
  4044. 'type' => 'image_url',
  4045. 'image_url' => [
  4046. 'url' => $videoParams['tail_frame_url'],
  4047. ],
  4048. 'role' => 'last_frame',
  4049. ];
  4050. }
  4051. }
  4052. }
  4053. // 获取配音音频URL
  4054. $audioUrl = getProp($segment, 'audio_url');
  4055. $audioDuration = getProp($segment, 'audio_duration');
  4056. // 音频传入的前提:必须有至少一张图片或一个视频
  4057. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  4058. // 余额预检:按预估时长计算所需积分,不足直接报错
  4059. $chargeDuration = (int)ceil((float)$audioDuration);
  4060. if ($chargeDuration <= 0) {
  4061. $chargeDuration = 5; // 无音频时长时按默认5秒预估
  4062. }
  4063. $this->pointsService->checkUserPointsEnough(
  4064. $this->pointsService->getVideoChargePoints([
  4065. 'model' => $model,
  4066. 'video_resolution' => strtolower($videoParams['video_resolution'] ?? '720P'),
  4067. 'video_duration' => $chargeDuration,
  4068. 'ratio' => $ratio,
  4069. 'generate_audio' => $current_generate_audio,
  4070. ])
  4071. );
  4072. // dd($videoParams);
  4073. // 根据模型选择不同的视频生成方法
  4074. if (strpos($model, 'jimeng') !== false) {
  4075. // 即梦模型参数调整
  4076. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  4077. unset($videoParams['content']); // 即梦不使用content格式
  4078. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4079. } elseif (strpos($model, 'kling') !== false) {
  4080. // Keling模型参数调整
  4081. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  4082. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4083. unset($videoParams['ratio']);
  4084. unset($videoParams['content']); // Keling不使用content格式
  4085. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4086. } elseif (strpos($model, 'zhizhen') !== false) {
  4087. // 智帧20等新模型使用统一API
  4088. // 构建统一API参数
  4089. $unifiedParams = [
  4090. 'model_code' => $model,
  4091. 'alias_segment_id' => $segment_id,
  4092. 'prompt' => trim($fullPrompt),
  4093. 'video_duration' => $audioDuration > 0 ? max(5, min(15, ceil($audioDuration))) : 5,
  4094. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4095. 'video_ratio' => $ratio,
  4096. 'seed' => -1,
  4097. ];
  4098. // 构建parameters参数
  4099. $parameters = [
  4100. 'seconds' => $unifiedParams['video_duration'],
  4101. 'resolution' => $unifiedParams['video_resolution'],
  4102. 'ratio' => $ratio,
  4103. // 'video_mode' => 'multi_image',
  4104. // 'mode' => 'multi_image',
  4105. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4106. ];
  4107. $hasImage = false;
  4108. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4109. if ($hasImage) {
  4110. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4111. if (isset($videoParams['tail_frame_url'])) {
  4112. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4113. }
  4114. // 只有在有图片的情况下才能添加参考音频
  4115. if ($audioUrl) {
  4116. // $parameters['reference_audios'] = [$audioUrl];
  4117. }
  4118. } else {
  4119. // 没有图片时,记录错误日志
  4120. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4121. 'segment_id' => $segment_id,
  4122. 'model' => $model
  4123. ]);
  4124. }
  4125. $unifiedParams['parameters'] = $parameters;
  4126. // 调用统一API创建任务
  4127. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4128. } else {
  4129. // Seedance模型(默认)
  4130. // 快快AI Seedance 2.0/2.5:配音音频需先上传为素材,走聚合网关 /v1/video/generations
  4131. if ($this->isKuaikuaiSeedanceModel($model)) {
  4132. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4133. if ($canUseAudio && $audioUrl) {
  4134. // 上传配音音频为素材(上传失败时同步清理提示词中的<音频N>标记,不阻断任务)
  4135. $reference_audio_assets = $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets([$audioUrl], $fullPrompt);
  4136. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4137. // 优化提示词,增加音频相关描述
  4138. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4139. $videoParams['prompt'] = $audioPrompt;
  4140. } elseif ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4141. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration)));
  4142. }
  4143. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4144. } elseif ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615'])) {
  4145. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  4146. // 添加配音音频到content中
  4147. $videoParams['content'][] = [
  4148. 'type' => 'audio_url',
  4149. 'audio_url' => [
  4150. 'url' => $audioUrl,
  4151. ],
  4152. 'role' => 'reference_audio',
  4153. ];
  4154. // 优化提示词,增加音频相关描述
  4155. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  4156. $videoParams['prompt'] = $audioPrompt;
  4157. $videoParams['content'][0]['text'] = $audioPrompt;
  4158. } else {
  4159. if ($audioDuration) { // 有音频时长则需将视频时长设置为比音频时长更长的整数
  4160. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  4161. }
  4162. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4163. }
  4164. }
  4165. // 更新分镜表的视频任务信息
  4166. DB::table('mp_episode_segments')->where('segment_id', $segment_id)->update([
  4167. 'video_task_id' => $task->id,
  4168. 'video_task_status' => '生成中',
  4169. 'generate_audio' => $generate_audio,
  4170. 'updated_at' => date('Y-m-d H:i:s')
  4171. ]);
  4172. return [
  4173. 'task_id' => $task->id,
  4174. 'status' => $task->status,
  4175. 'segment_id' => $segment_id,
  4176. 'video_duration' => $videoDuration
  4177. ];
  4178. }
  4179. /**
  4180. * 是否为快快AI Seedance 2.0/2.5 系列模型
  4181. * 快快AI平台模型ID:seed-2-fast / seed-2-mini / seed-2.5 / seed-2
  4182. *
  4183. * @param string $model
  4184. * @return bool
  4185. */
  4186. public function isKuaikuaiSeedanceModel(string $model): bool
  4187. {
  4188. return in_array($model, ['seed-2-fast', 'seed-2-mini', 'seed-2.5', 'seed-2'], true);
  4189. }
  4190. /**
  4191. * 是否为百度AI网关Seedance 2.0系列模型(系统内使用 baidu- 前缀名,请求网关时映射为 doubao- 原名)
  4192. *
  4193. * @param string $model
  4194. * @return bool
  4195. */
  4196. public function isBaiduSeedanceModel(string $model): bool
  4197. {
  4198. return in_array($model, [
  4199. 'baidu-doubao-seedance-2-0-260128',
  4200. 'baidu-doubao-seedance-2-0-fast-260128',
  4201. 'baidu-doubao-seedance-2-0-mini-260615',
  4202. 'baidu-doubao-seedance-2-5-260628',
  4203. ], true);
  4204. }
  4205. /**
  4206. * 是否为 Seedance 2.0 系列模型(百度 doubao-seedance-2.0 / baidu-* / 快快AI seed-2 系列)
  4207. * 供单条与批量生成入口统一判断,避免各入口各自维护模型白名单
  4208. *
  4209. * @param string $model
  4210. * @return bool
  4211. */
  4212. public function isSeedance20SeriesModel(string $model): bool
  4213. {
  4214. return strpos($model, 'doubao-seedance-2.0') !== false
  4215. || $this->isKuaikuaiSeedanceModel($model)
  4216. || $this->isBaiduSeedanceModel($model);
  4217. }
  4218. public function createActVideoTask($data) {
  4219. $act_id = getProp($data, 'act_id');
  4220. $first_frame_url = getProp($data, 'first_frame_url');
  4221. $tail_frame_url = getProp($data, 'tail_frame_url');
  4222. $generate_audio = getProp($data, 'generate_audio', 1);
  4223. $video_duration = getProp($data, 'video_duration');
  4224. $video_resolution = getProp($data, 'video_resolution');
  4225. $ratio = getProp($data, 'ratio');
  4226. $products = getProp($data, 'products', []);
  4227. $reference_images = array_unique(getProp($data, 'reference_images', []));
  4228. if (!is_array($reference_images) || !is_array($products)) {
  4229. Utils::throwError('20003:传入的参考图或资产格式不正确');
  4230. }
  4231. if (!$act_id) {
  4232. Utils::throwError('1002:片段ID不能为空');
  4233. }
  4234. // 获取片段信息
  4235. $act = DB::table('mp_episode_segments')->where('id', $act_id)->first();
  4236. if (!$act) {
  4237. Utils::throwError('20003:片段不存在');
  4238. }
  4239. $act = (array)$act;
  4240. $anime_id = getProp($act, 'anime_id');
  4241. $episode_id = getProp($act, 'episode_id');
  4242. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4243. $ace_mode = getProp($anime, 'ace_mode');
  4244. $art_style_type = getProp($anime, 'art_style_type');
  4245. $art_style = getProp($anime, 'art_style');
  4246. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  4247. if (!$ratio) $ratio = getProp($episode, 'ratio', '9:16');
  4248. if (!$video_resolution) $video_resolution = getProp($episode, 'video_resolution', '720p');
  4249. // 将资产中新出现的资产放到extra_products中
  4250. // 满足以下要求: 遍历传入的$products,将product_name与$episode中的roles、scenes和props做比对,如果不在其中,则与$episode中的extra_products做比对,如果有同名的则覆盖,没有则新增后存入$episode中的extra_products字段中
  4251. if (!empty($products) && $episode) {
  4252. // 获取剧集中的角色、场景和道具列表
  4253. $roles = json_decode(getProp($episode, 'roles', '[]'), true) ?: [];
  4254. $scenes = json_decode(getProp($episode, 'scenes', '[]'), true) ?: [];
  4255. $props = json_decode(getProp($episode, 'props', '[]'), true) ?: [];
  4256. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  4257. // 构建角色名称列表
  4258. $role_names = array_column($roles, 'role');
  4259. // 构建场景名称列表
  4260. $scene_names = array_column($scenes, 'scene');
  4261. // 构建道具名称列表
  4262. $prop_names = array_column($props, 'prop');
  4263. // 遍历传入的products
  4264. foreach ($products as $product) {
  4265. $product_name = getProp($product, 'product_name');
  4266. // 如果product_name不在roles、scenes和props中
  4267. if (!in_array($product_name, $role_names) && !in_array($product_name, $scene_names) && !in_array($product_name, $prop_names)) {
  4268. // 查找是否在extra_products中存在同名的
  4269. $found = false;
  4270. foreach ($extra_products as $key => $extra_product) {
  4271. if (getProp($extra_product, 'product_name') === $product_name) {
  4272. // 有同名的则覆盖
  4273. $extra_products[$key] = $product;
  4274. $found = true;
  4275. break;
  4276. }
  4277. }
  4278. // 没有则新增
  4279. if (!$found) {
  4280. $extra_products[] = $product;
  4281. }
  4282. }
  4283. }
  4284. if ($extra_products) {
  4285. // 保存到数据库
  4286. DB::table('mp_anime_episodes')
  4287. ->where('id', $episode_id)
  4288. ->update([
  4289. 'extra_products' => json_encode($extra_products, 256),
  4290. 'updated_at' => date('Y-m-d H:i:s')
  4291. ]);
  4292. }
  4293. }
  4294. // 获取分镜内容
  4295. $actContent = getProp($act, 'act_show_content', '');
  4296. // 音效同出(默认使用)
  4297. $current_generate_audio = $generate_audio ? 1 : 0;
  4298. // 构建完整的提示词
  4299. $processResult = $this->processActContentWithProducts($actContent, $products);
  4300. $fullPrompt = $processResult['content'];
  4301. // if ($art_style_type == '3D真人风格') $fullPrompt = "美术风格: $art_style\n\n".$fullPrompt;
  4302. $reference_images = array_merge($processResult['reference_images'], $reference_images);
  4303. $videoDuration = $video_duration ? $video_duration : getProp($act, 'act_duration');
  4304. // 处理视频模型
  4305. $model = getProp($data, 'model');
  4306. if (!$model) {
  4307. $model = getProp($episode, 'video_model');
  4308. if (!$model) {
  4309. // episode表也没有,使用默认值
  4310. $model = 'seed-2';
  4311. }
  4312. }
  4313. // 验证模型是否在可用模型表中(全能模式片段转视频仅允许 ace_mode=1 的模型)
  4314. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  4315. if (!in_array($model, $valid_models)) {
  4316. $model = 'seed-2';
  4317. }
  4318. // 保存到episode表(仅在专用方法中更新模型)
  4319. // DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  4320. // 'video_model' => $model,
  4321. // 'updated_at' => date('Y-m-d H:i:s')
  4322. // ]);
  4323. // 余额预检:按预估时长计算所需积分,不足直接报错
  4324. $chargeDuration = (int)$videoDuration;
  4325. if ($chargeDuration <= 0) {
  4326. $chargeDuration = 5; // 无时长时按默认5秒预估
  4327. }
  4328. $this->pointsService->checkUserPointsEnough(
  4329. $this->pointsService->getVideoChargePoints([
  4330. 'model' => $model,
  4331. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4332. 'video_duration' => $chargeDuration,
  4333. 'ratio' => $ratio,
  4334. 'generate_audio' => $current_generate_audio,
  4335. ])
  4336. );
  4337. // 构建视频生成参数
  4338. $videoParams = [
  4339. 'model' => $model,
  4340. 'alias_act_id' => $act_id,
  4341. 'prompt' => trim($fullPrompt),
  4342. 'video_duration' => $videoDuration,
  4343. 'video_resolution' => $video_resolution,
  4344. 'seed' => -1,
  4345. 'ratio' => $ratio,
  4346. 'generate_audio' => (int)$current_generate_audio === 0 ? false : true,
  4347. 'draft' => false,
  4348. 'watermark' => false,
  4349. 'camera_fixed' => false,
  4350. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  4351. ];
  4352. // 如果分镜有图片,作为首帧
  4353. $hasImage = !empty(getProp($act, 'img_url')) || $first_frame_url;
  4354. $hasVideo = !empty(getProp($act, 'video_url'));
  4355. if ($hasImage) {
  4356. if ($first_frame_url) {
  4357. $videoParams['first_frame_url'] = $first_frame_url;
  4358. }else {
  4359. $videoParams['first_frame_url'] = getProp($act, 'img_url');
  4360. }
  4361. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4362. }
  4363. // 构建content数组
  4364. $videoParams['content'] = [
  4365. [
  4366. 'type' => 'text',
  4367. 'text' => $videoParams['prompt'],
  4368. ]
  4369. ];
  4370. // 如果有首帧图片,添加到content中
  4371. if ($hasImage) {
  4372. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128', 'doubao-seedance-2.0', 'baidu-doubao-seedance-2-5-260628', 'baidu-doubao-seedance-2-0-260128', 'baidu-doubao-seedance-2-0-fast-260128', 'baidu-doubao-seedance-2-0-mini-260615'])) {
  4373. $videoParams['content'][] = [
  4374. 'type' => 'image_url',
  4375. 'image_url' => [
  4376. 'url' => $videoParams['first_frame_url'],
  4377. ],
  4378. 'role' => 'reference_image',
  4379. ];
  4380. if (isset($videoParams['tail_frame_url'])) {
  4381. $videoParams['content'][] = [
  4382. 'type' => 'image_url',
  4383. 'image_url' => [
  4384. 'url' => $videoParams['tail_frame_url'],
  4385. ],
  4386. 'role' => 'reference_image',
  4387. ];
  4388. }
  4389. }else {
  4390. $videoParams['content'][] = [
  4391. 'type' => 'image_url',
  4392. 'image_url' => [
  4393. 'url' => $videoParams['first_frame_url'],
  4394. ],
  4395. 'role' => 'first_frame',
  4396. ];
  4397. if (isset($videoParams['tail_frame_url'])) {
  4398. $videoParams['content'][] = [
  4399. 'type' => 'image_url',
  4400. 'image_url' => [
  4401. 'url' => $videoParams['tail_frame_url'],
  4402. ],
  4403. 'role' => 'last_frame',
  4404. ];
  4405. }
  4406. }
  4407. }
  4408. // dd($videoParams);
  4409. // 根据模型选择不同的视频生成方法
  4410. if (strpos($model, 'jimeng') !== false) {
  4411. // 即梦模型参数调整
  4412. unset($videoParams['content']); // 即梦不使用content格式
  4413. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4414. } elseif (strpos($model, 'kling') !== false) {
  4415. // Keling模型参数调整
  4416. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  4417. unset($videoParams['ratio']);
  4418. unset($videoParams['content']); // Keling不使用content格式
  4419. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4420. } elseif (strpos($model, 'zhizhen') !== false) {
  4421. // 智帧20等新模型使用统一API
  4422. // 构建统一API参数
  4423. $unifiedParams = [
  4424. 'model_code' => $model,
  4425. 'alias_act_id' => $act_id,
  4426. 'prompt' => trim($fullPrompt),
  4427. 'video_duration' => $videoDuration,
  4428. 'video_resolution' => strtolower($videoParams['video_resolution']),
  4429. 'video_ratio' => $ratio,
  4430. 'seed' => -1,
  4431. ];
  4432. // 构建parameters参数
  4433. $parameters = [
  4434. 'seconds' => $unifiedParams['video_duration'],
  4435. 'resolution' => $unifiedParams['video_resolution'],
  4436. 'ratio' => $ratio,
  4437. // 'video_mode' => 'multi_image',
  4438. // 'mode' => 'multi_image',
  4439. 'generate_audio' => (int)$current_generate_audio === 1 ? true : false,
  4440. ];
  4441. $hasImage = false;
  4442. // 处理首帧和尾帧(智帧20模型必须要有首帧图片)
  4443. if ($hasImage) {
  4444. $parameters['first_frame_url'] = $videoParams['first_frame_url'];
  4445. if (isset($videoParams['tail_frame_url'])) {
  4446. $parameters['last_frame_url'] = $videoParams['tail_frame_url'];
  4447. }
  4448. } else {
  4449. // 没有图片时,记录错误日志
  4450. logDB('anime', 'error', '智帧20模型缺少首帧图片', [
  4451. 'act_id' => $act_id,
  4452. 'model' => $model
  4453. ]);
  4454. }
  4455. if ($reference_images) {
  4456. // 限制只传入9张参考图
  4457. $reference_images = array_slice($reference_images, 0, 9);
  4458. // 在处理之前先保存原始reference_images到任务参数中
  4459. $unifiedParams['ref_image_url'] = json_encode($reference_images, 256);
  4460. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4461. $parameters['reference_images'] = $reference_images;
  4462. $parameters['video_mode'] = 'multi_image';
  4463. $parameters['mode'] = 'multi_image';
  4464. }
  4465. $unifiedParams['parameters'] = $parameters;
  4466. // 调用统一API创建任务
  4467. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4468. } elseif ($this->isSeedance20SeriesModel($model)) {
  4469. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片需要先上传为素材
  4470. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4471. // 保存原始参考图用于任务记录
  4472. $videoParams['reference_images'] = $reference_images;
  4473. if ($reference_images) {
  4474. // 限制只传入9张参考图
  4475. $reference_images = array_slice($reference_images, 0, 9);
  4476. // 维护ref_image_url字段(参考图URL,JSON数组,与智帧分支保持一致)
  4477. $videoParams['ref_image_url'] = json_encode($reference_images, 256);
  4478. // 参考图上传为素材(百度网关/快快AI),上传失败时同步清理提示词中的<图片N>标记
  4479. $reference_image_assets = $isKuaikuai
  4480. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $fullPrompt)
  4481. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $fullPrompt);
  4482. // 素材上传失败后提示词可能被清理,同步更新视频参数中的提示词
  4483. $videoParams['prompt'] = trim($fullPrompt);
  4484. $videoParams['content'][0]['text'] = trim($fullPrompt);
  4485. $videoParams['reference_image_assets'] = $reference_image_assets;
  4486. }
  4487. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4488. if ($isKuaikuai) {
  4489. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4490. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4491. } else {
  4492. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4493. }
  4494. } else {
  4495. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4496. }
  4497. // 更新分镜表的视频任务信息
  4498. DB::table('mp_episode_segments')->where('id', $act_id)->update([
  4499. 'video_task_id' => $task->id,
  4500. 'video_task_status' => '生成中',
  4501. 'generate_audio' => $generate_audio,
  4502. 'updated_at' => date('Y-m-d H:i:s')
  4503. ]);
  4504. // 如果是全能模式,并且是第一集的第一个片段,将act_id存入Redis
  4505. $episode_number = getProp($act, 'episode_number');
  4506. $act_number = getProp($act, 'act_number');
  4507. if ((int)$ace_mode === 1 && (int)$episode_number === 1 && (int)$act_number === 1) {
  4508. Redis::sadd('anime_act_first_frame_urls', $act_id);
  4509. }
  4510. return [
  4511. 'task_id' => $task->id,
  4512. 'status' => $task->status,
  4513. 'act_id' => $act_id,
  4514. 'video_duration' => $videoDuration
  4515. ];
  4516. }
  4517. /**
  4518. * 文生视频通用方法
  4519. * 支持传入视频参数、提示词、参考图等信息,不支持products入参
  4520. * 用户提示词不做任何处理,直接组装参数后根据模型调用
  4521. *
  4522. * @param array $data 请求参数
  4523. * @return array
  4524. */
  4525. public function generateVideo($data) {
  4526. $prompt = getProp($data, 'prompt');
  4527. if (empty($prompt)) {
  4528. Utils::throwError('20003:提示词不能为空');
  4529. }
  4530. $model = getProp($data, 'model');
  4531. if (!$model) {
  4532. $model = 'seed-2';
  4533. }
  4534. // 验证模型是否在可用模型表中
  4535. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4536. Utils::throwError('20003:该模型已不可用,请更换!');
  4537. }
  4538. $video_duration = getProp($data, 'video_duration', 5);
  4539. $video_resolution = getProp($data, 'video_resolution', '480p');
  4540. $ratio = getProp($data, 'ratio', '9:16');
  4541. $generate_audio = getProp($data, 'generate_audio', 1);
  4542. $seed = getProp($data, 'seed', -1);
  4543. $first_frame_url = getProp($data, 'first_frame_url');
  4544. $tail_frame_url = getProp($data, 'tail_frame_url');
  4545. // 参考图(支持数组或JSON字符串,最多9张)
  4546. $reference_images = getProp($data, 'reference_images', []);
  4547. if (is_string($reference_images)) {
  4548. $reference_images = json_decode($reference_images, true) ?: [];
  4549. }
  4550. if (!is_array($reference_images)) {
  4551. Utils::throwError('20003:参考图格式不正确');
  4552. }
  4553. $reference_images = array_values(array_unique(array_filter($reference_images)));
  4554. $reference_images = array_slice($reference_images, 0, 9);
  4555. // 参考视频(支持数组或JSON字符串,最多3个)
  4556. $reference_videos = getProp($data, 'reference_videos', []);
  4557. if (is_string($reference_videos)) {
  4558. $reference_videos = json_decode($reference_videos, true) ?: [];
  4559. }
  4560. if (!is_array($reference_videos)) {
  4561. Utils::throwError('20003:参考视频格式不正确');
  4562. }
  4563. $reference_videos = array_values(array_unique(array_filter($reference_videos)));
  4564. if (count($reference_videos) > 3) {
  4565. Utils::throwError('20003:参考视频最多选择3个');
  4566. }
  4567. $reference_videos = array_slice($reference_videos, 0, 3);
  4568. // 参考音频(支持数组或JSON字符串,最多3个)
  4569. $reference_audios = getProp($data, 'reference_audios', []);
  4570. if (is_string($reference_audios)) {
  4571. $reference_audios = json_decode($reference_audios, true) ?: [];
  4572. }
  4573. if (!is_array($reference_audios)) {
  4574. Utils::throwError('20003:参考音频格式不正确');
  4575. }
  4576. $reference_audios = array_values(array_unique(array_filter($reference_audios)));
  4577. if (count($reference_audios) > 3) {
  4578. Utils::throwError('20003:参考音频最多选择3个');
  4579. }
  4580. $reference_audios = array_slice($reference_audios, 0, 3);
  4581. // 余额预检:按预估时长计算所需积分,不足直接报错
  4582. $chargeDuration = (int)ceil((float)$video_duration);
  4583. if ($chargeDuration <= 0) {
  4584. $chargeDuration = 5; // 无时长时按默认5秒预估
  4585. }
  4586. $this->pointsService->checkUserPointsEnough(
  4587. $this->pointsService->getVideoChargePoints([
  4588. 'model' => $model,
  4589. 'video_resolution' => strtolower($video_resolution ?? '720p'),
  4590. 'video_duration' => $chargeDuration,
  4591. 'ratio' => $ratio,
  4592. 'generate_audio' => (int)$generate_audio,
  4593. ])
  4594. );
  4595. // 构建视频生成参数(用户参数直接透传,提示词不做处理)
  4596. $videoParams = [
  4597. 'model' => $model,
  4598. 'prompt' => $prompt,
  4599. 'video_duration' => $video_duration,
  4600. 'video_resolution' => $video_resolution,
  4601. 'seed' => $seed,
  4602. 'ratio' => $ratio,
  4603. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4604. 'draft' => getProp($data, 'draft', false),
  4605. 'watermark' => getProp($data, 'watermark', false),
  4606. 'camera_fixed' => getProp($data, 'camera_fixed', false),
  4607. ];
  4608. if ($first_frame_url) $videoParams['first_frame_url'] = $first_frame_url;
  4609. if ($tail_frame_url) $videoParams['tail_frame_url'] = $tail_frame_url;
  4610. // 构建content数组
  4611. $videoParams['content'] = [
  4612. [
  4613. 'type' => 'text',
  4614. 'text' => $prompt,
  4615. ]
  4616. ];
  4617. // 根据模型选择不同的视频生成方法
  4618. if (strpos($model, 'jimeng') !== false) {
  4619. // 即梦模型参数调整
  4620. unset($videoParams['content']); // 即梦不使用content格式
  4621. $task = $this->aiVideoGenerationService->createJimengTask($videoParams);
  4622. } elseif (strpos($model, 'kling') !== false) {
  4623. // 可灵模型参数调整
  4624. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 可灵使用aspect_ratio
  4625. unset($videoParams['ratio']);
  4626. unset($videoParams['content']); // 可灵不使用content格式
  4627. $task = $this->aiVideoGenerationService->createKelingOmniTask($videoParams);
  4628. } elseif (strpos($model, 'zhizhen') !== false) {
  4629. // 智帧等新模型使用统一API
  4630. $unifiedParams = [
  4631. 'model_code' => $model,
  4632. 'prompt' => $prompt,
  4633. 'video_duration' => $video_duration,
  4634. 'video_resolution' => strtolower($video_resolution),
  4635. 'video_ratio' => $ratio,
  4636. 'seed' => $seed,
  4637. ];
  4638. // 构建parameters参数
  4639. $parameters = [
  4640. 'seconds' => $unifiedParams['video_duration'],
  4641. 'resolution' => $unifiedParams['video_resolution'],
  4642. 'ratio' => $ratio,
  4643. 'generate_audio' => (int)$generate_audio === 1 ? true : false,
  4644. ];
  4645. // 首帧和尾帧
  4646. if ($first_frame_url) $parameters['first_frame_url'] = $first_frame_url;
  4647. if ($tail_frame_url) $parameters['last_frame_url'] = $tail_frame_url;
  4648. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组,与参考图处理方式一致)
  4649. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4650. if ($refImageUrls) {
  4651. $unifiedParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4652. }
  4653. // 参考图处理
  4654. if ($reference_images) {
  4655. $reference_images = $this->aiImageGenerationService->processReferenceImagesToAssets($reference_images, $unifiedParams['prompt']);
  4656. $parameters['reference_images'] = $reference_images;
  4657. $parameters['video_mode'] = 'multi_image';
  4658. $parameters['mode'] = 'multi_image';
  4659. }
  4660. // 参考视频和参考音频(与参考图一致,先上传为智帧素材)
  4661. if ($reference_videos) {
  4662. $reference_videos = $this->aiImageGenerationService->processReferenceVideosToAssets($reference_videos, $unifiedParams['prompt']);
  4663. $parameters['reference_videos'] = $reference_videos;
  4664. }
  4665. if ($reference_audios) {
  4666. $reference_audios = $this->aiImageGenerationService->processReferenceAudiosToAssets($reference_audios, $unifiedParams['prompt']);
  4667. $parameters['reference_audios'] = $reference_audios;
  4668. }
  4669. $unifiedParams['parameters'] = $parameters;
  4670. // 调用统一API创建任务
  4671. $task = $this->aiVideoGenerationService->createUnifiedApiTask($unifiedParams);
  4672. } elseif ($this->isSeedance20SeriesModel($model)) {
  4673. // 豆包Seedance 2.0(百度AI网关)/ 快快AI Seedance 2.0/2.5:图片/视频/音频需要先上传为素材
  4674. $isKuaikuai = $this->isKuaikuaiSeedanceModel($model);
  4675. $videoParams['reference_images'] = $reference_images;
  4676. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4677. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4678. if ($refImageUrls) {
  4679. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4680. }
  4681. if ($reference_images) {
  4682. // 参考图上传为素材(百度网关/快快AI)
  4683. $reference_image_assets = $isKuaikuai
  4684. ? $this->aiVideoGenerationService->processReferenceImagesToKuaikuaiAssets($reference_images, $videoParams['prompt'])
  4685. : $this->aiVideoGenerationService->processReferenceImagesToSeedance20Assets($reference_images, $videoParams['prompt']);
  4686. $videoParams['reference_image_assets'] = $reference_image_assets;
  4687. }
  4688. // 参考视频上传为素材(百度网关/快快AI)
  4689. if ($reference_videos) {
  4690. $reference_video_assets = $isKuaikuai
  4691. ? $this->aiVideoGenerationService->processReferenceVideosToKuaikuaiAssets($reference_videos, $videoParams['prompt'])
  4692. : $this->aiVideoGenerationService->processReferenceVideosToSeedance20Assets($reference_videos, $videoParams['prompt']);
  4693. $videoParams['reference_video_assets'] = $reference_video_assets;
  4694. }
  4695. // 参考音频上传为素材(百度网关/快快AI)
  4696. if ($reference_audios) {
  4697. $reference_audio_assets = $isKuaikuai
  4698. ? $this->aiVideoGenerationService->processReferenceAudiosToKuaikuaiAssets($reference_audios, $videoParams['prompt'])
  4699. : $this->aiVideoGenerationService->processReferenceAudiosToSeedance20Assets($reference_audios, $videoParams['prompt']);
  4700. $videoParams['reference_audio_assets'] = $reference_audio_assets;
  4701. }
  4702. // 参考素材上传失败时可能清理提示词中的素材标记,需要同步回content文本
  4703. if ($reference_images || $reference_videos || $reference_audios) {
  4704. $videoParams['content'][0]['text'] = $videoParams['prompt'];
  4705. }
  4706. // 快快AI走聚合网关 /v1/video/generations(火山豆包格式)
  4707. if ($isKuaikuai) {
  4708. $videoParams['gateway_base_url'] = env('KUAIKUAI_AI_BASE_URL', 'https://ai-api.kkidc.com');
  4709. $task = $this->aiVideoGenerationService->createKuaikuaiVideoTask($videoParams);
  4710. } else {
  4711. $task = $this->aiVideoGenerationService->createSeedance20Task($videoParams);
  4712. }
  4713. } else {
  4714. // 官方Seedance模型:兼容参考视频和参考音频(content直接透传公网URL)
  4715. // 维护ref_image_url字段(参考图+参考视频+参考音频URL,JSON数组)
  4716. $refImageUrls = array_merge($reference_images, $reference_videos, $reference_audios);
  4717. if ($refImageUrls) {
  4718. $videoParams['ref_image_url'] = json_encode(array_values(array_filter($refImageUrls)), 256);
  4719. }
  4720. if ($reference_videos) {
  4721. foreach ($reference_videos as $videoUrl) {
  4722. $videoParams['content'][] = [
  4723. 'type' => 'video_url',
  4724. 'video_url' => [
  4725. 'url' => $videoUrl,
  4726. ],
  4727. 'role' => 'reference_video',
  4728. ];
  4729. }
  4730. }
  4731. if ($reference_audios) {
  4732. foreach ($reference_audios as $audioUrl) {
  4733. $videoParams['content'][] = [
  4734. 'type' => 'audio_url',
  4735. 'audio_url' => [
  4736. 'url' => $audioUrl,
  4737. ],
  4738. 'role' => 'reference_audio',
  4739. ];
  4740. }
  4741. }
  4742. $task = $this->aiVideoGenerationService->createSeedanceTask($videoParams);
  4743. }
  4744. return [
  4745. 'task_id' => $task->id,
  4746. 'status' => $task->status,
  4747. 'model' => $model,
  4748. 'video_duration' => $video_duration,
  4749. 'video_resolution' => $video_resolution,
  4750. 'ratio' => $ratio
  4751. ];
  4752. }
  4753. /**
  4754. * 预估生成所需积分(mode=chat/image/video,支持多数量总额)
  4755. *
  4756. * chat : count(默认1,AI对话单次10积分);批量分集可传 anime_id + generate_episode_number 按实际待创建集数估算
  4757. * image : model 必传;resolution(1k/2k/4k)或 width/height 自动归一化;image_num(默认1)
  4758. * video : model 必传;video_resolution(默认720p);video_duration(默认5秒);count(默认1);scene(默认video_generation)
  4759. *
  4760. * @param array $data
  4761. * @return array
  4762. */
  4763. public function previewCharge(array $data): array
  4764. {
  4765. $mode = (string)getProp($data, 'mode', '');
  4766. if (!in_array($mode, ['chat', 'image', 'video'])) {
  4767. Utils::throwError('1003:请传入mode参数(chat/image/video)');
  4768. }
  4769. // 视频计费场景(video_generation/video_to_video),默认视频生成
  4770. $scene = (string)getProp($data, 'scene', 'video_generation');
  4771. // 未显式传scene且带参考视频时,自动按video_to_video定价
  4772. if ($mode === 'video' && !array_key_exists('scene', $data) && !empty(getProp($data, 'reference_videos', []))) {
  4773. $scene = 'video_to_video';
  4774. }
  4775. $items = [];
  4776. $model = '';
  4777. $resolution = '';
  4778. if ($mode === 'video') {
  4779. // 通用视频预估:单价/秒 × 时长 × 数量(多个视频计算总额)
  4780. $model = (string)getProp($data, 'model', '');
  4781. if (!$model) {
  4782. Utils::throwError('1002:model参数不能为空');
  4783. }
  4784. $resolution = strtolower((string)getProp($data, 'video_resolution', '720p'));
  4785. $duration = (int)getProp($data, 'video_duration', 5);
  4786. if ($duration <= 0) {
  4787. $duration = 5;
  4788. }
  4789. $count = max(1, (int)getProp($data, 'count', 1));
  4790. $pointsPerVideo = $this->pointsService->getVideoChargePoints([
  4791. 'model' => $model,
  4792. 'video_resolution' => $resolution,
  4793. 'video_duration' => $duration,
  4794. 'mode' => $scene,
  4795. ]);
  4796. $points = $pointsPerVideo * $count;
  4797. $items[] = [
  4798. 'type' => 'video',
  4799. 'model' => $model,
  4800. 'video_resolution' => $resolution,
  4801. 'video_duration' => $duration,
  4802. 'count' => $count,
  4803. 'points' => $points,
  4804. ];
  4805. } elseif ($mode === 'image') {
  4806. // 通用图片预估:单张价格 × 张数(resolution 可直传,或传 width/height 自动归一化)
  4807. $model = (string)getProp($data, 'model', '');
  4808. if (!$model) {
  4809. Utils::throwError('1002:model参数不能为空');
  4810. }
  4811. $resolution = strtolower((string)getProp($data, 'resolution', ''));
  4812. if (!$resolution) {
  4813. $width = (int)getProp($data, 'width', 0);
  4814. $height = (int)getProp($data, 'height', 0);
  4815. if ($width <= 0 || $height <= 0) {
  4816. $width = 1600;
  4817. $height = 2848;
  4818. }
  4819. $resolution = $this->pointsService->normalizeImageResolutionKey($width, $height);
  4820. }
  4821. $imageNum = max(1, (int)getProp($data, 'image_num', 1));
  4822. $points = $this->pointsService->getImageChargePoints([
  4823. 'model' => $model,
  4824. 'resolution' => $resolution,
  4825. ]) * $imageNum;
  4826. $items[] = [
  4827. 'type' => 'image',
  4828. 'model' => $model,
  4829. 'resolution' => $resolution,
  4830. 'image_num' => $imageNum,
  4831. 'points' => $points,
  4832. ];
  4833. } else {
  4834. // AI对话预估:按 price_type 档位取价(special 默认10 / normal 3);
  4835. // 批量生成分集传 anime_id + generate_episode_number 时按实际待创建集数估算(该场景实际扣费固定 special 档)
  4836. $priceType = (string)getProp($data, 'price_type', 'special');
  4837. if (!in_array($priceType, ['special', 'normal'], true)) {
  4838. Utils::throwError('1003:price_type参数仅支持special或normal');
  4839. }
  4840. $count = max(1, (int)getProp($data, 'count', 1));
  4841. $animeId = getProp($data, 'anime_id');
  4842. $generateEpisodes = (int)getProp($data, 'generate_episode_number', 0);
  4843. if ($animeId && $generateEpisodes > 0) {
  4844. // 批量生成分集按 special 档预估,与实际扣费口径一致
  4845. $priceType = 'special';
  4846. $currentMaxEpisode = DB::table('mp_anime_episodes')
  4847. ->where('anime_id', $animeId)
  4848. ->where('is_default', 1)
  4849. ->max('episode_number');
  4850. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  4851. $startEpisodeNumber = $currentMaxEpisode + 1;
  4852. $endEpisodeNumber = $startEpisodeNumber + $generateEpisodes - 1;
  4853. $existingSkipped = DB::table('mp_batch_episode_generation_details')
  4854. ->where('anime_id', $animeId)
  4855. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  4856. ->whereIn('status', ['pending', 'processing', 'completed'])
  4857. ->count();
  4858. $count = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkipped;
  4859. if ($count < 0) {
  4860. $count = 0;
  4861. }
  4862. }
  4863. $points = $this->pointsService->getChatChargePoints((string)$model, $priceType) * $count;
  4864. $items[] = [
  4865. 'type' => 'chat',
  4866. 'count' => $count,
  4867. 'price_type' => $priceType,
  4868. 'points' => $points,
  4869. ];
  4870. }
  4871. $totalPoints = 0;
  4872. foreach ($items as $item) {
  4873. $totalPoints += $item['points'];
  4874. }
  4875. return [
  4876. 'mode' => $mode,
  4877. 'total_points' => $totalPoints,
  4878. 'items' => $items,
  4879. 'points_balance' => $this->pointsService->getUserPointsBalance(),
  4880. 'remark' => '积分为预估值,实际扣费以生成完成后的实际消耗为准',
  4881. ];
  4882. }
  4883. /**
  4884. * 根据提示词内容智能计算最优视频时长
  4885. *
  4886. * @param string $segmentContent 分镜内容
  4887. * @param string $tailFrame 尾帧描述
  4888. * @return int 视频时长(2-12秒)
  4889. */
  4890. public function calculateOptimalVideoDuration($segmentContent, $tailFrame = '') {
  4891. // 合并所有文本内容
  4892. $fullText = trim($segmentContent . ' ' . $tailFrame);
  4893. // 如果没有内容,返回默认时长
  4894. if (empty($fullText)) {
  4895. return 5;
  4896. }
  4897. // 计算文本长度(中文字符按2个字符计算)
  4898. $textLength = mb_strlen($fullText, 'UTF-8');
  4899. $chineseCharCount = preg_match_all('/[\x{4e00}-\x{9fff}]/u', $fullText);
  4900. $adjustedLength = $textLength + $chineseCharCount; // 中文字符权重更高
  4901. // 分析内容复杂度
  4902. $complexityScore = $this->analyzeContentComplexity($fullText);
  4903. // 基础时长计算(根据文本长度)
  4904. $baseDuration = 3; // 默认2秒
  4905. // if ($adjustedLength <= 20) {
  4906. // $baseDuration = 3;
  4907. // } elseif ($adjustedLength <= 40) {
  4908. // $baseDuration = 4;
  4909. // } elseif ($adjustedLength <= 60) {
  4910. // $baseDuration = 5;
  4911. // } elseif ($adjustedLength <= 80) {
  4912. // $baseDuration = 6;
  4913. // } elseif ($adjustedLength <= 100) {
  4914. // $baseDuration = 7;
  4915. // } elseif ($adjustedLength <= 120) {
  4916. // $baseDuration = 8;
  4917. // } else {
  4918. // $baseDuration = 9;
  4919. // }
  4920. // 根据内容复杂度调整时长
  4921. $finalDuration = $baseDuration + $complexityScore;
  4922. // 确保时长在2-12秒范围内
  4923. return max(4, min(12, $finalDuration));
  4924. }
  4925. /**
  4926. * 分析内容复杂度,返回时长调整值
  4927. *
  4928. * @param string $text 文本内容
  4929. * @return int 调整值(-2到+3)
  4930. */
  4931. private function analyzeContentComplexity($text) {
  4932. $score = 0;
  4933. // 动作关键词(需要更长时间展现)
  4934. $actionKeywords = [
  4935. '跑步', '奔跑', '飞行', '跳跃', '战斗', '打斗', '追逐', '逃跑', '舞蹈', '表演',
  4936. '变化', '变身', '爆炸', '崩塌', '建造', '制作', '烹饪', '绘画', '写字',
  4937. '移动', '旋转', '翻滚', '攀爬', '游泳', '潜水', '滑行', '飞翔'
  4938. ];
  4939. // 静态关键词(可以用较短时间)
  4940. $staticKeywords = [
  4941. '站立', '坐着', '躺着', '静止', '凝视', '思考', '沉思', '观察', '等待',
  4942. '睡觉', '休息', '静坐', '冥想', '阅读', '听音乐'
  4943. ];
  4944. // 复杂场景关键词(需要更长时间)
  4945. $complexSceneKeywords = [
  4946. '人群', '聚会', '会议', '战争', '庆典', '仪式', '表演', '比赛', '竞技',
  4947. '多人', '群体', '团队', '合作', '互动', '对话', '争论', '讨论'
  4948. ];
  4949. // 情感关键词(需要适中时间表现)
  4950. $emotionKeywords = [
  4951. '哭泣', '笑容', '愤怒', '惊讶', '恐惧', '悲伤', '喜悦', '兴奋', '紧张',
  4952. '感动', '震惊', '困惑', '失望', '希望', '绝望', '温柔', '严肃'
  4953. ];
  4954. // 检查动作关键词
  4955. foreach ($actionKeywords as $keyword) {
  4956. if (strpos($text, $keyword) !== false) {
  4957. $score += 1;
  4958. break; // 避免重复加分
  4959. }
  4960. }
  4961. // 检查静态关键词
  4962. foreach ($staticKeywords as $keyword) {
  4963. if (strpos($text, $keyword) !== false) {
  4964. $score -= 1;
  4965. break;
  4966. }
  4967. }
  4968. // 检查复杂场景关键词
  4969. foreach ($complexSceneKeywords as $keyword) {
  4970. if (strpos($text, $keyword) !== false) {
  4971. $score += 1;
  4972. break;
  4973. }
  4974. }
  4975. // 检查情感关键词
  4976. foreach ($emotionKeywords as $keyword) {
  4977. if (strpos($text, $keyword) !== false) {
  4978. $score += 1;
  4979. break;
  4980. }
  4981. }
  4982. // 检查时间相关词汇
  4983. if (preg_match('/缓慢|慢慢|渐渐|逐渐|慢动作/', $text)) {
  4984. $score += 1;
  4985. }
  4986. if (preg_match('/快速|迅速|急速|瞬间|立刻|马上/', $text)) {
  4987. $score -= 1;
  4988. }
  4989. // 检查转场词汇
  4990. if (preg_match('/然后|接着|随后|紧接着|同时|与此同时/', $text)) {
  4991. $score += 1;
  4992. }
  4993. // 检查环境描述(复杂环境需要更多时间)
  4994. if (preg_match('/风景|景色|环境|背景|氛围|光线|阴影|色彩|细节/', $text)) {
  4995. $score += 1;
  4996. }
  4997. // 检查对话内容(对话需要更多时间)
  4998. if (preg_match('/说|讲|告诉|回答|询问|问|对话|交谈/', $text)) {
  4999. $score += 1;
  5000. }
  5001. // 限制调整范围
  5002. return max(-1, min(4, $score));
  5003. }
  5004. /**
  5005. * 创建完整视频合成任务
  5006. *
  5007. * @param array $data
  5008. * @return array
  5009. */
  5010. public function createCompleteVideoTask($data)
  5011. {
  5012. $animeId = getProp($data, 'anime_id');
  5013. $episodeId = getProp($data, 'episode_id');
  5014. // 验证参数
  5015. if (!$animeId || !$episodeId) {
  5016. Utils::throwError('20003:anime_id 和 episode_id 不能为空');
  5017. }
  5018. // 检查是否已存在处理中的任务
  5019. $existingTask = DB::table('mp_complete_video_tasks')
  5020. ->where('anime_id', $animeId)
  5021. ->where('episode_id', $episodeId)
  5022. ->whereIn('generate_status', ['执行中'])
  5023. ->first();
  5024. if ($existingTask) {
  5025. Utils::throwError('20003:该剧集已有正在处理的视频合成任务');
  5026. }
  5027. // 获取全能模式状态
  5028. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  5029. if ((int)$ace_mode === 1) {
  5030. // 获取所有片段的配音视频,按 act_number 排序
  5031. $segments = DB::table('mp_episode_segments')
  5032. ->where('anime_id', $animeId)
  5033. ->where('episode_id', $episodeId)
  5034. ->orderBy('segment_number')
  5035. ->select('id as act_id', 'act_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5036. ->get();
  5037. // 检查是否所有片段都有视频
  5038. $missingVideos = $segments->filter(function($segment) {
  5039. return empty($segment->video_url);
  5040. });
  5041. if ($missingVideos->isNotEmpty()) {
  5042. Utils::throwError('20003:存在未完成视频的片段,请确保所有片段都已完成配音');
  5043. }
  5044. }else {
  5045. // 获取所有分镜的配音视频,按 segment_number 排序
  5046. $segments = DB::table('mp_episode_segments')
  5047. ->where('anime_id', $animeId)
  5048. ->where('episode_id', $episodeId)
  5049. ->orderBy('segment_number')
  5050. ->select('segment_id', 'segment_number', 'video_url', 'audio_url', 'video_time_point_start', 'video_time_point_end')
  5051. ->get();
  5052. // 检查是否所有分镜都有配音和视频
  5053. $missingVideos = $segments->filter(function($segment) {
  5054. return empty($segment->audio_url) || empty($segment->video_url);
  5055. });
  5056. if ($missingVideos->isNotEmpty()) {
  5057. Utils::throwError('20003:存在未完成配音或视频的分镜,请确保所有分镜都已完成配音或视频');
  5058. }
  5059. }
  5060. if ($segments->isEmpty()) {
  5061. Utils::throwError('20003:未找到该剧集的分镜数据');
  5062. }
  5063. // 获取当前完整视频url
  5064. $completeVideoUrl = DB::table('mp_anime_episodes')
  5065. ->where('anime_id', $animeId)
  5066. ->where('id', $episodeId)
  5067. ->value('complete_video_url');
  5068. // 构建 generate_json
  5069. $generateJson = [];
  5070. $sequence = 1;
  5071. foreach ($segments as $segment) {
  5072. if ((int)$ace_mode === 1) {
  5073. $generateJson[] = [
  5074. 'sequence' => $sequence++,
  5075. 'video_url' => $segment->video_url,
  5076. 'video_time_point_start' => $segment->video_time_point_start,
  5077. 'video_time_point_end' => $segment->video_time_point_end
  5078. ];
  5079. }else {
  5080. $generateJson[] = [
  5081. 'sequence' => $sequence++,
  5082. 'video_url' => $segment->video_url,
  5083. 'audio_url' => $segment->audio_url,
  5084. 'video_time_point_start' => $segment->video_time_point_start,
  5085. 'video_time_point_end' => $segment->video_time_point_end
  5086. ];
  5087. }
  5088. }
  5089. // 创建任务
  5090. $now = date('Y-m-d H:i:s');
  5091. $taskId = DB::table('mp_complete_video_tasks')->insertGetId([
  5092. 'anime_id' => $animeId,
  5093. 'episode_id' => $episodeId,
  5094. 'generate_json' => json_encode($generateJson, 256),
  5095. 'generate_status' => '执行中',
  5096. 'complete_video_url' => '',
  5097. 'created_at' => $now,
  5098. 'updated_at' => $now
  5099. ]);
  5100. if (!$taskId) {
  5101. Utils::throwError('20003:创建任务失败');
  5102. }
  5103. // 更新剧集表的任务ID和状态
  5104. $boolen = DB::table('mp_anime_episodes')
  5105. ->where('anime_id', $animeId)
  5106. ->where('id', $episodeId)
  5107. ->update([
  5108. 'complete_video_task_id' => $taskId,
  5109. 'complete_video_task_status' => '执行中',
  5110. 'updated_at' => $now
  5111. ]);
  5112. if (!$boolen) {
  5113. Utils::throwError('20003:更新剧集表失败');
  5114. }
  5115. dLog('anime')->info('创建完整视频合成任务', [
  5116. 'task_id' => $taskId,
  5117. 'anime_id' => $animeId,
  5118. 'episode_id' => $episodeId,
  5119. 'segment_count' => count($generateJson)
  5120. ]);
  5121. // 请求远程服务器执行生成
  5122. $client = new Client(['timeout' => 600, 'verify' => false]);
  5123. try {
  5124. $result = $client->get("http://122.9.129.83:5000/api/anime/genVideo?taskId={$taskId}");
  5125. $response = $result->getBody()->getContents();
  5126. $response_arr = json_decode($response, true);
  5127. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5128. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5129. dLog('anime')->error('火山合成完整视频失败', ['error' => $error_msg, 'task_id' => $taskId]);
  5130. // // 更新任务状态为失败
  5131. // DB::table('mp_complete_video_tasks')
  5132. // ->where('id', $taskId)
  5133. // ->update([
  5134. // 'generate_status' => '执行失败',
  5135. // 'error_message' => $error_msg,
  5136. // 'updated_at' => date('Y-m-d H:i:s')
  5137. // ]);
  5138. // // 同步更新剧集表状态
  5139. // DB::table('mp_anime_episodes')
  5140. // ->where('complete_video_task_id', $taskId)
  5141. // ->update([
  5142. // 'complete_video_task_status' => '执行失败',
  5143. // 'updated_at' => date('Y-m-d H:i:s')
  5144. // ]);
  5145. Utils::throwError('20003:火山合成完整视频失败: ' . $error_msg);
  5146. }
  5147. } catch (\Exception $e) {
  5148. dLog('anime')->error('调用远程服务器失败', ['error' => $e->getMessage(), 'task_id' => $taskId]);
  5149. // 更新任务状态为失败
  5150. DB::table('mp_complete_video_tasks')
  5151. ->where('id', $taskId)
  5152. ->update([
  5153. 'generate_status' => '执行失败',
  5154. 'error_message' => $e->getMessage(),
  5155. 'updated_at' => date('Y-m-d H:i:s')
  5156. ]);
  5157. // 同步更新剧集表状态
  5158. DB::table('mp_anime_episodes')
  5159. ->where('complete_video_task_id', $taskId)
  5160. ->update([
  5161. 'complete_video_task_status' => '执行失败',
  5162. 'updated_at' => date('Y-m-d H:i:s')
  5163. ]);
  5164. Utils::throwError('20003:调用远程服务器失败: ' . $e->getMessage());
  5165. }
  5166. // 开始轮询任务状态
  5167. $maxAttempts = 60; // 5分钟 = 60次 * 5秒
  5168. $pollInterval = 5; // 每5秒轮询一次
  5169. $attempt = 0;
  5170. dLog('anime')->info('开始轮询任务状态', ['task_id' => $taskId]);
  5171. while ($attempt < $maxAttempts) {
  5172. sleep($pollInterval);
  5173. $attempt++;
  5174. // 查询任务状态
  5175. $task = DB::table('mp_complete_video_tasks')
  5176. ->where('id', $taskId)
  5177. ->first();
  5178. if (!$task) {
  5179. dLog('anime')->error('任务不存在', ['task_id' => $taskId]);
  5180. Utils::throwError('20003:任务不存在');
  5181. }
  5182. dLog('anime')->info('轮询任务状态', [
  5183. 'task_id' => $taskId,
  5184. 'attempt' => $attempt,
  5185. 'status' => $task->generate_status
  5186. ]);
  5187. // 检查任务是否完成
  5188. if ($task->generate_status === '执行成功') {
  5189. // 同步更新剧集表状态
  5190. $boolen3 = DB::table('mp_anime_episodes')
  5191. ->where('anime_id', $animeId)
  5192. ->where('id', $episodeId)
  5193. ->update([
  5194. 'complete_video_url' => $task->complete_video_url,
  5195. 'complete_video_task_status' => '执行成功',
  5196. 'updated_at' => date('Y-m-d H:i:s')
  5197. ]);
  5198. dLog('anime')->info('视频合成任务完成', [
  5199. 'task_id' => $taskId,
  5200. 'video_url' => $task->complete_video_url,
  5201. 'attempts' => $attempt
  5202. ]);
  5203. // 如果更新成功则远程删除之前的文件
  5204. if ($boolen3 && $completeVideoUrl) {
  5205. $encode_url = urlencode($completeVideoUrl);
  5206. $client = new Client(['timeout' => 300, 'verify' => false]);
  5207. // 根据ID通过API通知合成音频
  5208. // $result = $client->get("http://47.240.171.155:5000/api/fileDelete?url={$encode_url}");
  5209. $result = $client->get("http://122.9.129.83:5000/api/fileDelete?url={$encode_url}");
  5210. $response = $result->getBody()->getContents();
  5211. $response_arr = json_decode($response, true);
  5212. Log::info('火山删除音频返回: '.$response);
  5213. if (!isset($response_arr['status']) || (int)$response_arr['status'] !== 0) {
  5214. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5215. Log::info('火山删除音频失败: '.$error_msg);
  5216. // Utils::throwError('20003:火山删除音频失败');
  5217. }
  5218. }
  5219. return [
  5220. 'task_id' => $taskId,
  5221. 'anime_id' => $animeId,
  5222. 'episode_id' => $episodeId,
  5223. 'segment_count' => count($generateJson),
  5224. 'generate_status' => '执行成功',
  5225. 'complete_video_url' => $task->complete_video_url,
  5226. ];
  5227. }
  5228. // 检查任务是否失败
  5229. if ($task->generate_status === '执行失败') {
  5230. // 同步更新剧集表状态
  5231. DB::table('mp_anime_episodes')
  5232. ->where('anime_id', $animeId)
  5233. ->where('id', $episodeId)
  5234. ->update([
  5235. 'complete_video_task_status' => '执行失败',
  5236. 'updated_at' => date('Y-m-d H:i:s')
  5237. ]);
  5238. $errorMessage = $task->error_message ?? '未知错误';
  5239. dLog('anime')->error('视频合成任务失败', [
  5240. 'task_id' => $taskId,
  5241. 'error' => $errorMessage,
  5242. 'attempts' => $attempt
  5243. ]);
  5244. return [
  5245. 'task_id' => $taskId,
  5246. 'anime_id' => $animeId,
  5247. 'episode_id' => $episodeId,
  5248. 'segment_count' => count($generateJson),
  5249. 'generate_status' => '执行失败',
  5250. 'error_message' => $errorMessage
  5251. ];
  5252. }
  5253. }
  5254. // 超时处理
  5255. dLog('anime')->warning('视频合成任务超时', [
  5256. 'task_id' => $taskId,
  5257. 'max_attempts' => $maxAttempts,
  5258. 'timeout_seconds' => $maxAttempts * $pollInterval
  5259. ]);
  5260. // 更新任务状态为超时
  5261. DB::table('mp_complete_video_tasks')
  5262. ->where('id', $taskId)
  5263. ->update([
  5264. 'generate_status' => '超时',
  5265. 'error_message' => '任务执行超时(5分钟)',
  5266. 'updated_at' => date('Y-m-d H:i:s')
  5267. ]);
  5268. return [
  5269. 'task_id' => $taskId,
  5270. 'anime_id' => $animeId,
  5271. 'episode_id' => $episodeId,
  5272. 'segment_count' => count($generateJson),
  5273. 'generate_status' => '超时',
  5274. 'error_message' => '任务执行超时,请稍后查询任务状态'
  5275. ];
  5276. }
  5277. /**
  5278. * 根据 inner_prompt_type 附加内置提示词
  5279. *
  5280. * @param string $prompt 用户提示词
  5281. * @param int $innerPromptType 内置提示词类型(1=三视图, 2=九宫格)
  5282. * @return string 合并后的提示词
  5283. */
  5284. public static function appendInnerPrompt($prompt, $innerPromptType = 0)
  5285. {
  5286. $innerPromptMap = [
  5287. 1 => '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字',
  5288. 2 => '基于参考图及提示词内容,生成9张连贯的系列图片:9张图片围绕同一主体展开,保持角色形象、美术风格和色彩搭配完全一致,画面内容依次衔接、情节连贯,整体构成一组完整的系列图。每张图片主体完整清晰,构图合理,画面干净,无文字、无水印、无字幕。',
  5289. ];
  5290. if (!isset($innerPromptMap[$innerPromptType])) {
  5291. return $prompt;
  5292. }
  5293. return trim((string)$prompt) . "\n" . $innerPromptMap[$innerPromptType];
  5294. }
  5295. /**
  5296. * 根据 inner_prompt_type 获取生成图片数量
  5297. *
  5298. * @param int $innerPromptType 内置提示词类型
  5299. * @param int $imageNum 传入的图片张数
  5300. * @return int 图片数量
  5301. */
  5302. public static function getInnerImageNum($innerPromptType = 0, $imageNum)
  5303. {
  5304. return (int)$innerPromptType === 2 ? 9 : $imageNum;
  5305. }
  5306. /**
  5307. * 提取图片生成结果URL
  5308. *
  5309. * @param mixed $resultUrl 任务结果URL(数组、JSON字符串或普通字符串)
  5310. * @param int $innerPromptType 内置提示词类型
  5311. * @return mixed 类型2返回全部URL数组,其它类型返回首个URL
  5312. */
  5313. public static function extractResultUrls($resultUrl, $innerPromptType = 0)
  5314. {
  5315. $resultUrls = is_array($resultUrl) ? $resultUrl : json_decode((string)$resultUrl, true);
  5316. if (is_array($resultUrls) && !empty($resultUrls)) {
  5317. $resultUrls = array_values($resultUrls);
  5318. return (int)$innerPromptType === 2 ? $resultUrls : $resultUrls[0];
  5319. }
  5320. if (!empty($resultUrl)) {
  5321. return (int)$innerPromptType === 2 ? [$resultUrl] : $resultUrl;
  5322. }
  5323. return (int)$innerPromptType === 2 ? [] : '';
  5324. }
  5325. public function generateImg($data, $onTaskCreated = null, $onPoll = null) {
  5326. $prompt = getProp($data, 'prompt');
  5327. $episode_id = getProp($data, 'episode_id');
  5328. $ref_img_urls = getProp($data, 'ref_img_urls');
  5329. $ratio = getProp($data, 'ratio', '9:16');
  5330. $resolution = getProp($data, 'resolution', '2k');
  5331. $inner_prompt_type = getProp($data, 'inner_prompt_type', 0);
  5332. $imageNum = (int)getProp($data, 'image_num', 1);
  5333. // 定义分辨率和宽高比对应的尺寸映射表
  5334. $sizeMap = [
  5335. '2k' => [
  5336. '1:1' => ['width' => 2048, 'height' => 2048],
  5337. '4:3' => ['width' => 2304, 'height' => 1728],
  5338. '3:4' => ['width' => 1728, 'height' => 2304],
  5339. '16:9' => ['width' => 2848, 'height' => 1600],
  5340. '9:16' => ['width' => 1600, 'height' => 2848],
  5341. '3:2' => ['width' => 2496, 'height' => 1664],
  5342. '2:3' => ['width' => 1664, 'height' => 2496],
  5343. '21:9' => ['width' => 3136, 'height' => 1344],
  5344. ],
  5345. '3k' => [
  5346. '1:1' => ['width' => 3072, 'height' => 3072],
  5347. '4:3' => ['width' => 3456, 'height' => 2592],
  5348. '3:4' => ['width' => 2592, 'height' => 3456],
  5349. '16:9' => ['width' => 4096, 'height' => 2304],
  5350. '9:16' => ['width' => 2304, 'height' => 4096],
  5351. '2:3' => ['width' => 2496, 'height' => 3744],
  5352. '3:2' => ['width' => 3744, 'height' => 2496],
  5353. '21:9' => ['width' => 4704, 'height' => 2016],
  5354. ],
  5355. '4k' => [
  5356. '1:1' => ['width' => 4096, 'height' => 4096],
  5357. '3:4' => ['width' => 3520, 'height' => 4704],
  5358. '4:3' => ['width' => 4704, 'height' => 3520],
  5359. '16:9' => ['width' => 5504, 'height' => 3040],
  5360. '9:16' => ['width' => 3040, 'height' => 5504],
  5361. '2:3' => ['width' => 3328, 'height' => 4992],
  5362. '3:2' => ['width' => 4992, 'height' => 3328],
  5363. '21:9' => ['width' => 6240, 'height' => 2656],
  5364. ],
  5365. ];
  5366. // 参数验证
  5367. $resolution = strtolower($resolution);
  5368. if (!isset($sizeMap[$resolution])) {
  5369. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  5370. }
  5371. if (!isset($sizeMap[$resolution][$ratio])) {
  5372. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  5373. }
  5374. // 根据 ratio 和 resolution 确定宽高
  5375. $width = $sizeMap[$resolution][$ratio]['width'];
  5376. $height = $sizeMap[$resolution][$ratio]['height'];
  5377. if (!is_array($ref_img_urls) && !empty($ref_img_urls)) {
  5378. if (is_json($ref_img_urls)) {
  5379. $ref_img_urls = json_decode($ref_img_urls, true);
  5380. }else {
  5381. $ref_img_urls = explode(',', $ref_img_urls);
  5382. }
  5383. }
  5384. // 处理图片模型
  5385. $model = getProp($data, 'model');
  5386. if (!$model) {
  5387. // 用户没有输入,从episode表获取
  5388. if ($episode_id) {
  5389. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  5390. $model = getProp($episode, 'image_model');
  5391. }
  5392. if (!$model) {
  5393. // episode表也没有,使用默认值
  5394. $model = 'doubao-seedream-5-0-lite-260128';
  5395. }
  5396. }
  5397. // 验证模型是否在可用模型表中
  5398. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5399. // $model = 'doubao-seedream-5-0-lite-260128';
  5400. Utils::throwError('20003:该模型已不可用,请更换!');
  5401. }
  5402. // 保存到episode表
  5403. if ($episode_id) {
  5404. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  5405. 'image_model' => $model,
  5406. 'updated_at' => date('Y-m-d H:i:s')
  5407. ]);
  5408. }
  5409. // 参数验证
  5410. if (!$prompt) Utils::throwError('20003:请提供提示词');
  5411. // 根据 inner_prompt_type 附加内置提示词并确定生成图片数量
  5412. $prompt = self::appendInnerPrompt($prompt, $inner_prompt_type);
  5413. $imageNum = self::getInnerImageNum($inner_prompt_type, $imageNum);
  5414. try {
  5415. // 创建图片生成任务
  5416. $params = [
  5417. 'prompt' => $prompt,
  5418. 'model' => $model,
  5419. 'ref_img_urls' => '',
  5420. 'width' => $width,
  5421. 'height' => $height,
  5422. 'image_num' => $imageNum
  5423. ];
  5424. if ($ref_img_urls) $params['ref_img_urls'] = is_array($ref_img_urls) ? $ref_img_urls : [$ref_img_urls];
  5425. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5426. $task_id = $task->id;
  5427. if (!$task_id) {
  5428. Utils::throwError('20003:创建图片生成任务失败');
  5429. }
  5430. // 创建任务中心记录并关联图片任务ID
  5431. $taskCenter = $this->taskCenterService->createTask('image', [
  5432. 'title' => '文生图',
  5433. 'ref_task_id' => $task_id,
  5434. // 'prompt' => $prompt,
  5435. // 'params' => json_encode($data, JSON_UNESCAPED_UNICODE),
  5436. ]);
  5437. $taskCenterId = $taskCenter->id;
  5438. // 组装本次任务信息(用于init消息,类似generateVideo)
  5439. $taskInfo = [
  5440. 'task_id' => $task_id,
  5441. 'status' => getProp($task, 'status', 'processing'),
  5442. 'model' => $model,
  5443. 'ratio' => $ratio,
  5444. 'resolution' => $resolution,
  5445. 'image_num' => $imageNum,
  5446. ];
  5447. // 创建图片任务后立即回调(类似generateVideo的init消息,返回任务中心ID和任务信息)
  5448. if (is_callable($onTaskCreated)) {
  5449. $onTaskCreated($taskCenterId, $taskInfo);
  5450. }
  5451. // 检查任务模型类型(火山模型和GPT模型都支持直接检查任务状态)
  5452. $model = getProp($task, 'model');
  5453. $isVolcModel = in_array($model, \App\Consts\BaseConst::VOLC_PIC_MODELS);
  5454. $isGptModel = in_array($model, \App\Consts\BaseConst::GPT_IMAGE2_MODELS);
  5455. $isSyncModel = $isVolcModel || $isGptModel;
  5456. // 即梦AI需要轮询获取结果(5分钟超时,每3秒查询一次)
  5457. $start_time = time();
  5458. $timeout = 300; // 5分钟
  5459. $img_url = '';
  5460. $img_urls = [];
  5461. $lastQueueMessageTime = $start_time; // 记录上次发送队列消息的时间
  5462. $queueMessageInterval = 60; // 队列消息发送间隔(秒)
  5463. while (time() - $start_time < $timeout) {
  5464. sleep(3);
  5465. // 每分钟发送一次队列状态消息(仅流式模式)
  5466. if (is_callable($onPoll)) {
  5467. $currentTime = time();
  5468. if ($currentTime - $lastQueueMessageTime >= $queueMessageInterval) {
  5469. $onPoll($taskCenterId, $task_id, $currentTime - $start_time);
  5470. $lastQueueMessageTime = $currentTime;
  5471. }
  5472. }
  5473. // 火山API和GPT-Image2 API是同步返回结果的,直接检查任务状态
  5474. if ($isSyncModel) {
  5475. // 刷新任务状态
  5476. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5477. if ($task->status === 'success' && $task->result_url) {
  5478. $resultUrls = is_array($task->result_url) ? $task->result_url : json_decode((string)$task->result_url, true);
  5479. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5480. if (!empty($resultUrls)) {
  5481. $img_urls = $resultUrls;
  5482. $img_url = $resultUrls[0];
  5483. } else {
  5484. $img_url = (string)$task->result_url;
  5485. }
  5486. break;
  5487. } elseif ($task->status === 'failed') {
  5488. $errorMsg = mapErrorMessage($task->error_message ?? '');
  5489. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5490. }
  5491. // // 如果还在处理中,提示用户稍后查看
  5492. // Utils::throwError('20003:图片生成中,请稍后刷新查看结果');
  5493. }else {
  5494. $task = MpGeneratePicTask::where('id', $task_id)->first();
  5495. $statusInfo = $this->aiImageGenerationService->queryTaskStatus($task);
  5496. if ($statusInfo['status'] === 'success') {
  5497. $task->updateStatus('success', [
  5498. 'result_url' => $statusInfo['result_url'],
  5499. 'result_json' => $statusInfo['result_json'] ?? []
  5500. ]);
  5501. $resultUrls = is_array($statusInfo['result_url']) ? $statusInfo['result_url'] : json_decode((string)$statusInfo['result_url'], true);
  5502. $resultUrls = is_array($resultUrls) ? array_values(array_filter($resultUrls)) : [];
  5503. if (!empty($resultUrls)) {
  5504. $img_urls = $resultUrls;
  5505. $img_url = $resultUrls[0];
  5506. } else {
  5507. $img_url = (string)$statusInfo['result_url'];
  5508. }
  5509. break;
  5510. } elseif ($statusInfo['status'] === 'failed') {
  5511. $task->updateStatus('failed', [
  5512. 'error_message' => $statusInfo['error_message'],
  5513. 'result_json' => $statusInfo['result_json'] ?? []
  5514. ]);
  5515. dLog('anime')->error('图片生成失败,', [
  5516. 'error' => $statusInfo['error_message'] ?? '未知错误'
  5517. ]);
  5518. $errorMsg = mapErrorMessage($statusInfo['error_message'] ?? '');
  5519. Utils::throwError('20003:图片生成失败,' . $errorMsg);
  5520. }
  5521. }
  5522. }
  5523. if (empty($img_url)) {
  5524. Utils::throwError('20003:图片生成超时,请稍后重试');
  5525. }
  5526. // 多张图片返回全部URL数组(配合控制器输出image_urls字段)
  5527. if (count($img_urls) > 1) {
  5528. return [
  5529. 'img_url' => $img_url,
  5530. 'image_urls' => $img_urls,
  5531. 'task_id' => $taskCenterId,
  5532. ];
  5533. }
  5534. return [
  5535. 'img_url' => $img_url,
  5536. 'task_id' => $taskCenterId,
  5537. ];
  5538. } catch (\Exception $e) {
  5539. dLog('anime')->error('更新角色或场景失败', [
  5540. 'error' => $e->getMessage()
  5541. ]);
  5542. logDB('anime', 'error', '更新角色或场景失败', ['error' => $e->getMessage()]);
  5543. Utils::throwError('20003:' . $e->getMessage());
  5544. }
  5545. }
  5546. /**
  5547. * 使用文生文模型解析分镜内容
  5548. */
  5549. private function parseSegmentContentWithAI($segment_content) {
  5550. try {
  5551. // 使用DeepSeek服务的公开方法解析分镜内容
  5552. return $this->DeepSeekService->parseSegmentContent($segment_content);
  5553. } catch (\Exception $e) {
  5554. // 如果AI解析失败,记录日志并返回原内容
  5555. dLog('anime')->error('AI解析分镜内容失败: ' . $e->getMessage());
  5556. return $segment_content;
  5557. }
  5558. }
  5559. /**
  5560. * 处理分集的角色和场景数据(继承全局数据或创建新任务)
  5561. *
  5562. * @param int $episode_id 分集ID
  5563. * @param int $anime_id 动漫ID
  5564. * @param array $roles 分集角色数组(引用传递)
  5565. * @param array $scenes 分集场景数组(引用传递)
  5566. * @param array $episode 分集数据
  5567. */
  5568. private function processEpisodeRolesAndScenes($episode_id, $anime_id, &$roles, &$scenes, $episode) {
  5569. // 获取全局动漫的角色和场景数据
  5570. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5571. if (!$anime) return;
  5572. $art_style_type = getProp($anime, 'art_style_type');
  5573. $character_prefix = '';
  5574. $scene_prefix = '';
  5575. if ($art_style_type) {
  5576. $art_style_arr = $this->DeepSeekService->getArtStyleShortPromptByInput($art_style_type);
  5577. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  5578. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  5579. }
  5580. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  5581. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  5582. $roles_updated = false;
  5583. $scenes_updated = false;
  5584. // 处理角色
  5585. foreach ($roles as &$role) {
  5586. $role_name = getProp($role, 'role');
  5587. $role_description = getProp($role, 'description');
  5588. $role_pic_prompt = getProp($role, 'pic_prompt');
  5589. $role_url = getProp($role, 'url');
  5590. $role_task_id = getProp($role, 'task_id');
  5591. // 如果已有URL或已有任务ID,跳过
  5592. if (!empty($role_url) || !empty($role_task_id) || $role_name === '旁白') {
  5593. continue;
  5594. }
  5595. $url_inherited = false;
  5596. // 尝试从全局数据中继承
  5597. foreach ($global_roles as $global_role) {
  5598. $global_role_name = getProp($global_role, 'role');
  5599. $global_role_description = getProp($global_role, 'description');
  5600. $global_role_pic_prompt = getProp($global_role, 'pic_prompt');
  5601. $global_role_url = getProp($global_role, 'url');
  5602. $global_role_task_id = getProp($global_role, 'task_id');
  5603. $global_role_task_status = getProp($global_role, 'task_status');
  5604. // 满足条件:角色名相同、描述相同、pic_prompt相同、全局有URL
  5605. if ($role_name === $global_role_name
  5606. && $role_description === $global_role_description
  5607. && $role_pic_prompt === $global_role_pic_prompt
  5608. && !empty($global_role_url)) {
  5609. // 继承 task_id、task_status 和 url
  5610. $role['task_id'] = $global_role_task_id;
  5611. $role['task_status'] = $global_role_task_status;
  5612. $role['url'] = $global_role_url;
  5613. $roles_updated = true;
  5614. $url_inherited = true;
  5615. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 继承全局数据");
  5616. break;
  5617. }
  5618. }
  5619. // 如果无法继承且没有任务ID,创建新任务
  5620. if (!$url_inherited && empty($role_task_id)) {
  5621. try {
  5622. $art_style = getProp($episode, 'art_style');
  5623. // 优先使用 pic_prompt,如果没有则使用 description
  5624. $description = !empty($role_pic_prompt) ? trim((string)$role_pic_prompt) : $role_description;
  5625. // if ($art_style) {
  5626. // // $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5627. // $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  5628. // }
  5629. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5630. $params = [
  5631. 'prompt' => $description,
  5632. 'ref_img_urls' => []
  5633. ];
  5634. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5635. $task_id = $task->id;
  5636. if ($task_id) {
  5637. $role['task_id'] = $task_id;
  5638. $role['task_status'] = 'processing';
  5639. $roles_updated = true;
  5640. dLog('anime')->info("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务,任务ID:{$task_id}");
  5641. }
  5642. } catch (\Exception $e) {
  5643. dLog('anime')->error("分集ID:{$episode_id} 角色:{$role_name} 创建图片生成任务失败: " . $e->getMessage());
  5644. }
  5645. }
  5646. }
  5647. // 处理场景
  5648. foreach ($scenes as &$scene) {
  5649. $scene_name = getProp($scene, 'scene');
  5650. $scene_description = getProp($scene, 'description');
  5651. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  5652. $scene_url = getProp($scene, 'url');
  5653. $scene_task_id = getProp($scene, 'task_id');
  5654. // 如果已有URL或已有任务ID,跳过
  5655. if (!empty($scene_url) || !empty($scene_task_id)) {
  5656. continue;
  5657. }
  5658. $url_inherited = false;
  5659. // 尝试从全局数据中继承
  5660. foreach ($global_scenes as $global_scene) {
  5661. $global_scene_name = getProp($global_scene, 'scene');
  5662. $global_scene_description = getProp($global_scene, 'description');
  5663. $global_scene_pic_prompt = getProp($global_scene, 'pic_prompt');
  5664. $global_scene_url = getProp($global_scene, 'url');
  5665. $global_scene_task_id = getProp($global_scene, 'task_id');
  5666. $global_scene_task_status = getProp($global_scene, 'task_status');
  5667. // 满足条件:场景名相同、描述相同、pic_prompt相同、全局有URL
  5668. if ($scene_name === $global_scene_name
  5669. && $scene_description === $global_scene_description
  5670. && $scene_pic_prompt === $global_scene_pic_prompt
  5671. && !empty($global_scene_url)) {
  5672. // 继承 task_id、task_status 和 url
  5673. $scene['task_id'] = $global_scene_task_id;
  5674. $scene['task_status'] = $global_scene_task_status;
  5675. $scene['url'] = $global_scene_url;
  5676. $scenes_updated = true;
  5677. $url_inherited = true;
  5678. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 继承全局数据");
  5679. break;
  5680. }
  5681. }
  5682. // 如果无法继承且没有任务ID,创建新任务
  5683. if (!$url_inherited && empty($scene_task_id)) {
  5684. try {
  5685. $art_style = getProp($episode, 'art_style');
  5686. // 优先使用 pic_prompt,如果没有则使用 description
  5687. $description = !empty($scene_pic_prompt) ? trim((string)$scene_pic_prompt) : $scene_description;
  5688. // if ($art_style) {
  5689. // // $description = "美术风格:\n{$art_style}\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5690. // $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  5691. // }
  5692. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  5693. $params = [
  5694. 'prompt' => $description,
  5695. 'ref_img_urls' => []
  5696. ];
  5697. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5698. $task_id = $task->id;
  5699. if ($task_id) {
  5700. $scene['task_id'] = $task_id;
  5701. $scene['task_status'] = 'processing';
  5702. $scenes_updated = true;
  5703. dLog('anime')->info("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务,任务ID:{$task_id}");
  5704. }
  5705. } catch (\Exception $e) {
  5706. dLog('anime')->error("分集ID:{$episode_id} 场景:{$scene_name} 创建图片生成任务失败: " . $e->getMessage());
  5707. }
  5708. }
  5709. }
  5710. // 如果有更新,保存到数据库
  5711. if ($roles_updated || $scenes_updated) {
  5712. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  5713. if ($roles_updated) {
  5714. $update_data['roles'] = json_encode($roles, JSON_UNESCAPED_UNICODE);
  5715. }
  5716. if ($scenes_updated) {
  5717. $update_data['scenes'] = json_encode($scenes, JSON_UNESCAPED_UNICODE);
  5718. }
  5719. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  5720. dLog('anime')->info("分集ID:{$episode_id} 角色和场景数据已更新");
  5721. }
  5722. }
  5723. /**
  5724. * 根据图片URL使用AI反推图片提示词
  5725. *
  5726. * @param string $img_url 图片URL
  5727. * @return string 反推的提示词
  5728. */
  5729. private function generateImagePromptFromUrl($img_url) {
  5730. try {
  5731. // 获取默认模型
  5732. $model = 'doubao-seed-2-0-mini-260215';
  5733. // 构建messages参数
  5734. $messages = [
  5735. [
  5736. 'role' => 'user',
  5737. 'content' => [
  5738. [
  5739. 'type' => 'text',
  5740. 'text' => '请解析这张参考图,并直接输出一段专业中文反推提示词。提示词用于短剧分镜图片生成,必须聚焦角色和场景本身,可包含姿态、镜头视角、构图、画风、色彩氛围、光线、景深或光圈质感等要素。不要输出解释、标题、列表或无关背景,只输出可直接用于文生图的分镜图片提示词'
  5741. ],
  5742. [
  5743. 'type' => 'image_url',
  5744. 'image_url' => [
  5745. 'url' => $img_url
  5746. ]
  5747. ]
  5748. ]
  5749. ]
  5750. ];
  5751. // 构建请求参数
  5752. $params = [
  5753. 'model' => $model,
  5754. 'messages' => $messages,
  5755. 'stream' => false,
  5756. 'thinking' => ['type' => 'disabled'] // 不使用思考模式
  5757. ];
  5758. // 调用DeepSeek服务的volcEngineChatCompletion方法(非流式)
  5759. $result = $this->DeepSeekService->volcEngineChatCompletion($params);
  5760. // 仅记录 token 使用明细(不扣积分)
  5761. $uid = 0;
  5762. try {
  5763. $uid = (int)Site::getUid();
  5764. } catch (\Throwable $e) {
  5765. // 非请求上下文(如命令行)下可能无法获取用户ID,置为0跳过记录
  5766. }
  5767. $this->pointsService->recordTokenOnlyDetail(
  5768. $uid,
  5769. $this->pointsService->getTokensFromUsage($result['usage'] ?? []),
  5770. [
  5771. 'model' => $model,
  5772. 'img_url' => $img_url,
  5773. 'source' => 'generateImagePromptFromUrl',
  5774. ],
  5775. 'chat',
  5776. $model,
  5777. ''
  5778. );
  5779. // 返回生成的内容
  5780. return getProp($result, 'fullContent', '图片描述生成失败');
  5781. } catch (\Exception $e) {
  5782. dLog('anime')->error('AI反推图片提示词失败: ' . $e->getMessage(), [
  5783. 'img_url' => $img_url
  5784. ]);
  5785. logDB('anime', 'error', 'AI反推图片提示词失败', [
  5786. 'error' => $e->getMessage(),
  5787. 'img_url' => $img_url
  5788. ]);
  5789. return '图片描述生成失败: ' . $e->getMessage();
  5790. }
  5791. }
  5792. /**
  5793. * 音频试听接口
  5794. * 创建音频任务并轮询获取结果
  5795. *
  5796. * @param array $data 参数数组
  5797. * @return array 返回音频URL或错误信息
  5798. */
  5799. public function previewAudio($data) {
  5800. $dialogue = getProp($data, 'dialogue');
  5801. // 必填参数验证
  5802. if (!$dialogue) Utils::throwError('20003:dialogue不能为空');
  5803. // 获取参数,优先使用传入的参数,否则使用分镜中的参数
  5804. $voice_type = getProp($data, 'voice_type');
  5805. $voice_name = getProp($data, 'voice_name');
  5806. $voice_actor = getProp($data, 'voice_actor');
  5807. $emotion_type = getProp($data, 'emotion_type');
  5808. $gender = getProp($data, 'gender', 0);
  5809. $emotion = getProp($data, 'emotion');
  5810. $speed_ratio = getProp($data, 'speed_ratio', 0);
  5811. $loudness_ratio = getProp($data, 'loudness_ratio', 0);
  5812. $emotion_scale = getProp($data, 'emotion_scale', 0);
  5813. $pitch = getProp($data, 'pitch', 0);
  5814. try {
  5815. $now = date('Y-m-d H:i:s');
  5816. // 构建生成参数
  5817. $generate_json = json_encode([
  5818. 'text' => $dialogue,
  5819. 'role' => $voice_actor,
  5820. 'voice_type' => $voice_type,
  5821. 'voice_name' => $voice_name,
  5822. 'emotion' => $emotion,
  5823. 'emotion_type' => $emotion_type,
  5824. 'gender' => $gender,
  5825. 'speed_ratio' => $speed_ratio,
  5826. 'loudness_ratio' => $loudness_ratio,
  5827. 'emotion_scale' => $emotion_scale,
  5828. 'pitch' => $pitch,
  5829. ], 256);
  5830. // 请求远程服务器执行生成
  5831. $client = new Client(['timeout' => 600, 'verify' => false]);
  5832. $result = $client->get("http://122.9.129.83:5000/api/anime/audioPreview?generateJson={$generate_json}");
  5833. $response = $result->getBody()->getContents();
  5834. $response_arr = json_decode($response, true);
  5835. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  5836. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  5837. dLog('anime')->error('音频试听任务创建失败', ['error' => $error_msg, 'response_arr' => $response_arr]);
  5838. Utils::throwError('20003:音频试听任务创建失败: ' . $error_msg);
  5839. }
  5840. $arr = $response_arr['data'];
  5841. $subtitle_info = $arr['subtitle_info'];
  5842. $audio_duration = json_decode($subtitle_info, true)['duration'];
  5843. if (!isset($arr['url']) || !$audio_duration || !$subtitle_info) Utils::throwError('20003:音频参数生成异常');
  5844. return [
  5845. 'audio_url' => $arr['url'],
  5846. 'subtitle_info' => $subtitle_info,
  5847. 'audio_duration' => round($audio_duration, 2)
  5848. ];
  5849. } catch (\Exception $e) {
  5850. dLog('anime')->error('音频试听失败', ['error' => $e->getMessage()]);
  5851. Utils::throwError('20003:' . $e->getMessage());
  5852. }
  5853. }
  5854. /**
  5855. * 获取角色库列表(支持文件夹递归查询)
  5856. * @param array $data 包含 parent_id(父文件夹ID,默认0表示最外层)、role(搜索关键词)、is_public(筛选类型)
  5857. * @return array 返回当前目录下的所有子目录和角色列表(递归)
  5858. */
  5859. public function globalProducts($data) {
  5860. $uid = Site::getUid();
  5861. $cpid = Site::getCpid();
  5862. $role = Site::getRole();
  5863. $id = getProp($data, 'id', 0);
  5864. $parent_id = getProp($data, 'parent_id', 0);
  5865. $product_name = getProp($data, 'product_name');
  5866. $product = getProp($data, 'product'); // 1.角色 2.场景 3.道具
  5867. $is_public = getProp($data, 'public_type', 2); // 0=仅个人库 1=仅公共库 2=个人库+公共库
  5868. if (!$product) {
  5869. Utils::throwError('20003:请选择产品类型');
  5870. }
  5871. // 根据角色和is_public参数确定查询范围
  5872. // admin角色:获取所有个人库+公共库(忽略is_public参数)
  5873. // user角色:根据is_public参数筛选
  5874. $query_user_ids = [];
  5875. if ($role === 'admin') {
  5876. // admin获取所有个人库和公共库
  5877. $query_user_ids = [$uid, 0];
  5878. } else {
  5879. // user角色根据is_public参数筛选
  5880. if ($is_public == 2) {
  5881. // 个人库+公共库
  5882. $query_user_ids = [$uid, 0];
  5883. } elseif ($is_public == 0) {
  5884. // 仅个人库
  5885. $query_user_ids = [$uid];
  5886. } elseif ($is_public == 1) {
  5887. // 仅公共库
  5888. $query_user_ids = [0];
  5889. }
  5890. }
  5891. // 如果有搜索条件(product_name 或 id),按条件搜索文件夹和产品
  5892. if ($id || $product_name) {
  5893. $query = DB::table('mp_products')
  5894. ->where('cpid', $cpid)
  5895. ->whereIn('user_id', $query_user_ids)
  5896. ->where('is_deleted', 0);
  5897. // 如果指定了 id,按 id 精确查询
  5898. if ($id) {
  5899. $query->where('id', $id);
  5900. }
  5901. // 如果指定了 product_name,按名称模糊查询
  5902. if ($product_name) {
  5903. $query->where('product_name', 'like', "%{$product_name}%");
  5904. }
  5905. // 如果指定了 product,添加筛选条件
  5906. if ($product) {
  5907. $query->where('product', $product);
  5908. }
  5909. $result = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5910. ->orderByRaw('type DESC, CASE WHEN user_id = '.$uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5911. ->get()
  5912. ->map(function($value) {
  5913. $value = (array)$value;
  5914. $value['created_at'] = transDate($value['created_at'], 'Y-m-d');
  5915. $value['type'] = (int)$value['type'];
  5916. $value['parent_id'] = (int)$value['parent_id'];
  5917. $value['level'] = (int)$value['level'];
  5918. $value['product'] = (int)($value['product'] ?? 1);
  5919. $value['is_public'] = (int)$value['user_id'] === 0 ? 1 : 0;
  5920. $value['versions'] = json_decode($value['versions'], true) ?: [];
  5921. unset($value['user_id']);
  5922. return $value;
  5923. })
  5924. ->toArray();
  5925. return $result;
  5926. }
  5927. // 递归获取所有子目录和角色
  5928. return $this->getChildrenRecursive($cpid, $parent_id, $product, $query_user_ids, $uid);
  5929. }
  5930. /**
  5931. * 递归获取指定目录下的所有子目录和角色
  5932. * @param int $cpid 公司ID
  5933. * @param int $parent_id 父目录ID
  5934. * @param int|null $product 产品类型筛选 1.角色 2.场景 3.道具
  5935. * @param array $query_user_ids 用户ID数组(支持多个)
  5936. * @param int $current_uid 当前用户ID(用于排序)
  5937. * @return array
  5938. */
  5939. private function getChildrenRecursive($cpid, $parent_id, $product = null, $query_user_ids = [], $current_uid = 0) {
  5940. // 查询当前层级的所有项(文件夹和角色)
  5941. $query = DB::table('mp_products')
  5942. ->where('cpid', $cpid)
  5943. ->where('is_deleted', 0)
  5944. ->where('parent_id', $parent_id);
  5945. // 添加用户ID验证(支持多个user_id)
  5946. if (!empty($query_user_ids)) {
  5947. $query->whereIn('user_id', $query_user_ids);
  5948. }
  5949. // 如果指定了 product,添加筛选条件(文件夹和角色都需要筛选)
  5950. if ($product) {
  5951. $query->where('product', $product);
  5952. }
  5953. // 排序规则:
  5954. // 1. 文件夹在前(type DESC)
  5955. // 2. 个人库在前,公共库在后(CASE WHEN user_id = current_uid)
  5956. // 3. 其他排序规则
  5957. $items = $query->select('id', 'type', 'parent_id', 'level', 'product_name', 'url', 'pic_prompt', 'three_view_image_url', 'versions', 'product', 'user_id', 'created_at')
  5958. ->orderByRaw('type DESC, CASE WHEN user_id = '.$current_uid.' THEN 0 ELSE 1 END ASC, sort_order DESC, created_at DESC')
  5959. ->get();
  5960. $result = [];
  5961. foreach ($items as $item) {
  5962. $itemArray = [
  5963. 'id' => $item->id,
  5964. 'type' => (int)$item->type,
  5965. 'parent_id' => (int)$item->parent_id,
  5966. 'level' => (int)$item->level,
  5967. 'product_name' => $item->product_name,
  5968. 'url' => $item->url,
  5969. 'pic_prompt' => $item->pic_prompt ?? '',
  5970. 'three_view_image_url' => $item->three_view_image_url,
  5971. 'product' => (int)($item->product ?? 1),
  5972. 'is_public' => (int)$item->user_id === 0 ? 1 : 0,
  5973. 'created_at' => transDate($item->created_at, 'Y-m-d')
  5974. ];
  5975. $itemArray['versions'] = json_decode($item->versions, true) ?: [];
  5976. // 如果是文件夹,递归获取其子项
  5977. if ($item->type == 2) {
  5978. $children = $this->getChildrenRecursive($cpid, $item->id, $product, $query_user_ids, $current_uid);
  5979. if (!empty($children)) {
  5980. $itemArray['children'] = $children;
  5981. }
  5982. }
  5983. $result[] = $itemArray;
  5984. }
  5985. return $result;
  5986. }
  5987. /**
  5988. * 创建文件夹
  5989. * @param array $data 包含 parent_id(父文件夹ID)、product_name(文件夹名称)、product(产品类型)
  5990. * @return int 返回新建文件夹ID
  5991. */
  5992. public function createFolder($data) {
  5993. $uid = Site::getUid();
  5994. $cpid = Site::getCpid();
  5995. $role = Site::getRole();
  5996. $parent_id = getProp($data, 'parent_id', 0);
  5997. $folder_name = getProp($data, 'product_name', '新建文件夹');
  5998. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  5999. // 如果是公共库操作,需要admin权限
  6000. if ($is_public && $role !== 'admin') {
  6001. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6002. }
  6003. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6004. $store_uid = $is_public ? 0 : $uid;
  6005. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6006. $product = getProp($data, 'product');
  6007. if (!in_array($product, [1, 2, 3])) {
  6008. // Utils::throwError('20003:product 参数错误,只能是 1(角色)、2(场景) 或 3(道具)');
  6009. }
  6010. // 验证父文件夹
  6011. $parent_level = 0;
  6012. if ($parent_id > 0) {
  6013. $parent = DB::table('mp_products')
  6014. ->where('id', $parent_id)
  6015. ->where('cpid', $cpid)
  6016. ->where('user_id', $store_uid)
  6017. ->where('type', 2)
  6018. ->where('is_deleted', 0)
  6019. ->first();
  6020. if (!$parent) {
  6021. Utils::throwError('20003:父文件夹不存在');
  6022. }
  6023. // 检查父文件夹的 product 类型是否一致
  6024. if ($parent->product != $product) {
  6025. Utils::throwError('20003:文件夹类型必须与父文件夹一致');
  6026. }
  6027. $parent_level = $parent->level;
  6028. // 检查层级限制(最多3层)
  6029. if ($parent_level >= 3) {
  6030. Utils::throwError('20003:文件夹层级不能超过3层');
  6031. }
  6032. }
  6033. // 检查当前目录下是否已存在空白文件夹
  6034. $empty_folder_exists = DB::table('mp_products')
  6035. ->where('parent_id', $parent_id)
  6036. ->where('cpid', $cpid)
  6037. ->where('user_id', $store_uid)
  6038. ->where('type', 2)
  6039. ->where('product', $product)
  6040. ->where('product_name', '新建文件夹')
  6041. ->where('is_deleted', 0)
  6042. ->exists();
  6043. if ($empty_folder_exists && $folder_name == '新建文件夹') {
  6044. Utils::throwError('20003:不允许创建多个空白文件夹,请先重命名现有文件夹');
  6045. }
  6046. // 创建文件夹
  6047. $folder_id = DB::table('mp_products')->insertGetId([
  6048. 'user_id' => $store_uid,
  6049. 'cpid' => $cpid,
  6050. 'type' => 2,
  6051. 'parent_id' => $parent_id,
  6052. 'level' => $parent_level + 1,
  6053. 'product_name' => $folder_name,
  6054. 'product' => $product,
  6055. 'sort_order' => time(), // 使用时间戳作为排序权重
  6056. 'is_deleted' => 0,
  6057. 'created_at' => date('Y-m-d H:i:s'),
  6058. 'updated_at' => date('Y-m-d H:i:s')
  6059. ]);
  6060. return [
  6061. 'id' => $folder_id,
  6062. 'type' => 2,
  6063. 'parent_id' => $parent_id,
  6064. 'level' => $parent_level + 1,
  6065. 'product_name' => $folder_name,
  6066. 'product' => $product,
  6067. ];
  6068. }
  6069. /**
  6070. * 重命名文件夹或角色
  6071. * @param array $data 包含 id、product_name(新名称)
  6072. * @return bool
  6073. */
  6074. public function renameFolder($data) {
  6075. $uid = Site::getUid();
  6076. $cpid = Site::getCpid();
  6077. $role = Site::getRole();
  6078. $id = getProp($data, 'id');
  6079. $new_name = getProp($data, 'product_name');
  6080. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6081. if (!$id || !$new_name) {
  6082. Utils::throwError('20003:参数不完整');
  6083. }
  6084. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6085. $query_uid = $is_public ? 0 : $uid;
  6086. // 如果是公共库操作,需要admin权限
  6087. if ($is_public && $role !== 'admin') {
  6088. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6089. }
  6090. // 检查是否存在
  6091. $item = DB::table('mp_products')
  6092. ->where('id', $id)
  6093. ->where('cpid', $cpid)
  6094. ->where('user_id', $query_uid)
  6095. ->where('is_deleted', 0)
  6096. ->first();
  6097. if (!$item) {
  6098. Utils::throwError('20003:项目不存在');
  6099. }
  6100. return DB::table('mp_products')
  6101. ->where('id', $id)
  6102. ->where('cpid', $cpid)
  6103. ->where('user_id', $query_uid)
  6104. ->update([
  6105. 'product_name' => $new_name,
  6106. 'updated_at' => date('Y-m-d H:i:s')
  6107. ]);
  6108. }
  6109. /**
  6110. * 移动角色或文件夹到指定文件夹
  6111. * @param array $data 包含 id(要移动的项目ID)、target_parent_id(目标父文件夹ID)
  6112. * @return bool
  6113. */
  6114. public function moveProductOrFolder($data) {
  6115. $uid = Site::getUid();
  6116. $cpid = Site::getCpid();
  6117. $role = Site::getRole();
  6118. $id = getProp($data, 'id');
  6119. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6120. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6121. if (!$id) {
  6122. Utils::throwError('20003:请选择要移动的项目');
  6123. }
  6124. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6125. $query_uid = $is_public ? 0 : $uid;
  6126. // 如果是公共库操作,需要admin权限
  6127. if ($is_public && $role !== 'admin') {
  6128. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6129. }
  6130. // 检查要移动的项目
  6131. $item = DB::table('mp_products')
  6132. ->where('id', $id)
  6133. ->where('cpid', $cpid)
  6134. ->where('user_id', $query_uid)
  6135. ->where('is_deleted', 0)
  6136. ->first();
  6137. if (!$item) {
  6138. Utils::throwError('20003:项目不存在');
  6139. }
  6140. // 验证目标文件夹
  6141. $target_level = 0;
  6142. $target_product = $item->product; // 默认使用当前项目的 product
  6143. if ($target_parent_id > 0) {
  6144. $target_parent = DB::table('mp_products')
  6145. ->where('id', $target_parent_id)
  6146. ->where('cpid', $cpid)
  6147. ->where('user_id', $query_uid)
  6148. ->where('type', 2)
  6149. ->where('is_deleted', 0)
  6150. ->first();
  6151. if (!$target_parent) {
  6152. Utils::throwError('20003:目标文件夹不存在');
  6153. }
  6154. // 检查 product 类型是否一致
  6155. if ($target_parent->product != $item->product) {
  6156. Utils::throwError('20003:不能移动到不同类型的文件夹下');
  6157. }
  6158. $target_level = $target_parent->level;
  6159. $target_product = $target_parent->product;
  6160. // 如果移动的是文件夹,需要检查层级
  6161. if ($item->type == 2) {
  6162. // 计算移动后的最大层级
  6163. $max_child_level = $this->getMaxChildLevel($id);
  6164. $depth = $max_child_level - $item->level;
  6165. if ($target_level + 1 + $depth > 3) {
  6166. Utils::throwError('20003:移动后文件夹层级将超过3层限制');
  6167. }
  6168. // 不能移动到自己或自己的子文件夹下
  6169. if ($this->isDescendant($target_parent_id, $id)) {
  6170. Utils::throwError('20003:不能移动到自己或子文件夹下');
  6171. }
  6172. }
  6173. }
  6174. // 更新父文件夹和层级
  6175. $new_level = $target_level + 1;
  6176. DB::table('mp_products')
  6177. ->where('id', $id)
  6178. ->update([
  6179. 'parent_id' => $target_parent_id,
  6180. 'level' => $new_level,
  6181. 'updated_at' => date('Y-m-d H:i:s')
  6182. ]);
  6183. // 如果是文件夹,需要递归更新所有子项的层级
  6184. if ($item->type == 2) {
  6185. $this->updateChildrenLevel($id, $new_level);
  6186. }
  6187. return true;
  6188. }
  6189. /**
  6190. * 获取文件夹下最大子层级
  6191. * @param int $folder_id
  6192. * @return int
  6193. */
  6194. private function getMaxChildLevel($folder_id) {
  6195. $max_level = DB::table('mp_products')
  6196. ->where('parent_id', $folder_id)
  6197. ->where('is_deleted', 0)
  6198. ->max('level');
  6199. if (!$max_level) {
  6200. return DB::table('mp_products')->where('id', $folder_id)->value('level');
  6201. }
  6202. // 递归查找子文件夹
  6203. $children = DB::table('mp_products')
  6204. ->where('parent_id', $folder_id)
  6205. ->where('type', 2)
  6206. ->where('is_deleted', 0)
  6207. ->pluck('id');
  6208. foreach ($children as $child_id) {
  6209. $child_max = $this->getMaxChildLevel($child_id);
  6210. if ($child_max > $max_level) {
  6211. $max_level = $child_max;
  6212. }
  6213. }
  6214. return $max_level;
  6215. }
  6216. /**
  6217. * 检查 target_id 是否是 folder_id 的后代
  6218. * @param int $target_id
  6219. * @param int $folder_id
  6220. * @return bool
  6221. */
  6222. private function isDescendant($target_id, $folder_id) {
  6223. if ($target_id == $folder_id) {
  6224. return true;
  6225. }
  6226. $parent = DB::table('mp_products')
  6227. ->where('id', $target_id)
  6228. ->where('is_deleted', 0)
  6229. ->first();
  6230. if (!$parent || $parent->parent_id == 0) {
  6231. return false;
  6232. }
  6233. return $this->isDescendant($parent->parent_id, $folder_id);
  6234. }
  6235. /**
  6236. * 递归更新子项层级
  6237. * @param int $parent_id
  6238. * @param int $parent_level
  6239. */
  6240. private function updateChildrenLevel($parent_id, $parent_level) {
  6241. $children = DB::table('mp_products')
  6242. ->where('parent_id', $parent_id)
  6243. ->where('is_deleted', 0)
  6244. ->get();
  6245. foreach ($children as $child) {
  6246. $new_level = $parent_level + 1;
  6247. DB::table('mp_products')
  6248. ->where('id', $child->id)
  6249. ->update([
  6250. 'level' => $new_level,
  6251. 'updated_at' => date('Y-m-d H:i:s')
  6252. ]);
  6253. // 如果是文件夹,继续递归
  6254. if ($child->type == 2) {
  6255. $this->updateChildrenLevel($child->id, $new_level);
  6256. }
  6257. }
  6258. }
  6259. /**
  6260. * 获取文件夹路径(面包屑导航)
  6261. * @param array $data 包含 folder_id
  6262. * @return array 返回路径数组
  6263. */
  6264. public function getFolderPath($data) {
  6265. $uid = Site::getUid();
  6266. $cpid = Site::getCpid();
  6267. $folder_id = getProp($data, 'id', 0);
  6268. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6269. if ($folder_id == 0) {
  6270. return [
  6271. ['id' => 0, 'name' => '根目录']
  6272. ];
  6273. }
  6274. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6275. $query_uid = $is_public ? 0 : $uid;
  6276. $path = [];
  6277. $current_id = $folder_id;
  6278. while ($current_id > 0) {
  6279. $folder = DB::table('mp_products')
  6280. ->where('id', $current_id)
  6281. ->where('cpid', $cpid)
  6282. ->where('user_id', $query_uid)
  6283. ->where('type', 2)
  6284. ->where('is_deleted', 0)
  6285. ->first();
  6286. if (!$folder) {
  6287. break;
  6288. }
  6289. array_unshift($path, [
  6290. 'id' => $folder->id,
  6291. 'name' => $folder->product_name
  6292. ]);
  6293. $current_id = $folder->parent_id;
  6294. }
  6295. // 添加根目录
  6296. array_unshift($path, ['id' => 0, 'name' => '根目录']);
  6297. return $path;
  6298. }
  6299. public function createProduct($data) {
  6300. $uid = Site::getUid();
  6301. $cpid = Site::getCpid();
  6302. $role = Site::getRole();
  6303. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6304. // 如果是公共库操作,需要admin权限
  6305. if ($is_public && $role !== 'admin') {
  6306. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6307. }
  6308. // 根据is_public参数确定存储的user_id(公共库user_id=0,cpid保持不变)
  6309. $store_uid = $is_public ? 0 : $uid;
  6310. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6311. $script_id = (int)getProp($data, 'script_id', 0);
  6312. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6313. if ($script_id && empty($episode_numbers)) {
  6314. Utils::throwError('20003:剧集序号不能为空');
  6315. }
  6316. if (!$script_id && !empty($episode_numbers)) {
  6317. Utils::throwError('20003:请提供剧本ID');
  6318. }
  6319. $product_name = trim(getProp($data, 'product_name'));
  6320. if (!$product_name) Utils::throwError('20003:名称不能为空');
  6321. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6322. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6323. // if ($exists_id) Utils::throwError('20003:名称不能重复,请修改');
  6324. $url = trim(getProp($data, 'url'));
  6325. if (!$url) Utils::throwError('20003:图片地址不能为空');
  6326. $versions = getProp($data, 'versions');
  6327. // 检查是否是正确的图片格式
  6328. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6329. $urlPath = parse_url($url, PHP_URL_PATH);
  6330. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6331. if (!in_array($extension, $allowedExtensions)) {
  6332. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6333. }
  6334. // 选填三视图图片地址,格式校验与 url 一致
  6335. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6336. if ($three_view_image_url) {
  6337. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6338. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6339. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6340. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6341. }
  6342. }
  6343. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6344. if (!$pic_prompt) Utils::throwError('20003:提示词不能为空');
  6345. // 获取 product 字段:1.角色 2.场景 3.道具,默认为1
  6346. $product = getProp($data, 'product');
  6347. if (!in_array($product, [1, 2, 3])) {
  6348. // Utils::throwError('20003:产品类型只能是 1(角色)、2(场景) 或 3(道具)');
  6349. }
  6350. // 获取父文件夹ID和层级
  6351. $parent_id = getProp($data, 'parent_id', 0);
  6352. $parent_level = 0;
  6353. if ($parent_id > 0) {
  6354. $parent = DB::table('mp_products')
  6355. ->where('id', $parent_id)
  6356. ->where('cpid', $cpid)
  6357. ->where('user_id', $store_uid)
  6358. ->where('type', 2)
  6359. ->where('is_deleted', 0)
  6360. ->first();
  6361. if (!$parent) {
  6362. Utils::throwError('20003:父文件夹不存在');
  6363. }
  6364. $parent_level = $parent->level;
  6365. }
  6366. // 创建资产并保存剧本资产关联关系(同一事务)
  6367. DB::beginTransaction();
  6368. try {
  6369. $id = DB::table('mp_products')->insertGetId([
  6370. 'user_id' => $store_uid,
  6371. 'cpid' => $cpid,
  6372. 'type' => 1, // 1=角色图片
  6373. 'parent_id' => $parent_id,
  6374. 'level' => $parent_level + 1,
  6375. 'product_name' => $product_name,
  6376. 'url' => $url,
  6377. 'three_view_image_url' => $three_view_image_url,
  6378. 'pic_prompt' => $pic_prompt,
  6379. 'product' => $product,
  6380. 'versions' => json_encode($versions, 256),
  6381. 'sort_order' => time(), // 使用时间戳作为排序权重
  6382. 'created_at' => date('Y-m-d H:i:s'),
  6383. 'updated_at' => date('Y-m-d H:i:s')
  6384. ]);
  6385. if (!$id) Utils::throwError('20003:创建失败');
  6386. // 保存剧本资产关联关系
  6387. if ($script_id) {
  6388. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6389. }
  6390. DB::commit();
  6391. } catch (\Exception $e) {
  6392. DB::rollback();
  6393. throw $e;
  6394. }
  6395. return [
  6396. 'id' => $id,
  6397. 'type' => 1,
  6398. 'parent_id' => $parent_id,
  6399. 'level' => $parent_level + 1,
  6400. 'product_name' => $product_name,
  6401. 'url' => $url,
  6402. 'three_view_image_url' => $three_view_image_url,
  6403. 'pic_prompt' => $pic_prompt,
  6404. 'product' => $product,
  6405. 'versions' => $versions
  6406. ];
  6407. }
  6408. public function editProduct($data) {
  6409. $uid = Site::getUid();
  6410. $cpid = Site::getCpid();
  6411. $role = Site::getRole();
  6412. $id = getProp($data, 'id');
  6413. if (!$id) Utils::throwError('20003:ID不能为空');
  6414. $versions = getProp($data, 'versions');
  6415. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6416. // 新增参数:剧本ID和剧集序号(支持数组传参,多个序号也可用英文逗号隔开)
  6417. $script_id = (int)getProp($data, 'script_id', 0);
  6418. $episode_numbers = $this->normalizeEpisodeNumbers(getProp($data, 'episode_number', []));
  6419. if ($script_id && empty($episode_numbers)) {
  6420. Utils::throwError('20003:剧集序号不能为空');
  6421. }
  6422. if (!$script_id && !empty($episode_numbers)) {
  6423. Utils::throwError('20003:请提供剧本ID');
  6424. }
  6425. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6426. $query_uid = $is_public ? 0 : $uid;
  6427. // 如果是公共库操作,需要admin权限
  6428. if ($is_public && $role !== 'admin') {
  6429. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6430. }
  6431. // 检查是否存在且属于当前用户或公共库
  6432. $role = DB::table('mp_products')
  6433. ->where('id', $id)
  6434. ->where('cpid', $cpid)
  6435. ->where('user_id', $query_uid)
  6436. ->where('type', 1)->first();
  6437. if (!$role) Utils::throwError('20003:记录不存在');
  6438. $updateData = [];
  6439. // $needVersionRecord = false; // 是否需要记录版本
  6440. // 名称
  6441. $product_name = trim(getProp($data, 'product_name'));
  6442. if ($product_name) {
  6443. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6444. $updateData['product_name'] = $product_name;
  6445. }
  6446. // $exists_id = DB::table('mp_products')->where('cpid', $cpid)->where('type', 1)->where('product_name', $product_name)->where('is_deleted', 0)->value('id');
  6447. // if ($exists_id && $exists_id != $id) Utils::throwError('20003:名称不能重复,请修改');
  6448. // 图片地址
  6449. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6450. $url = trim(getProp($data, 'url'));
  6451. if ($url) {
  6452. // 检查是否是正确的图片格式
  6453. $urlPath = parse_url($url, PHP_URL_PATH);
  6454. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6455. if (!in_array($extension, $allowedExtensions)) {
  6456. Utils::throwError('20003:图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6457. }
  6458. // // 如果 url 有变更,记录版本
  6459. // if ($url !== $role->url) {
  6460. // $needVersionRecord = true;
  6461. // }
  6462. $updateData['url'] = $url;
  6463. }
  6464. // 三视图图片地址(选填),格式校验与 url 一致
  6465. $three_view_image_url = trim(getProp($data, 'three_view_image_url', ''));
  6466. if ($three_view_image_url) {
  6467. $threeViewPath = parse_url($three_view_image_url, PHP_URL_PATH);
  6468. $threeViewExtension = strtolower(pathinfo($threeViewPath, PATHINFO_EXTENSION));
  6469. if (!in_array($threeViewExtension, $allowedExtensions)) {
  6470. Utils::throwError('20003:三视图图片格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6471. }
  6472. $updateData['three_view_image_url'] = $three_view_image_url;
  6473. }
  6474. // 提示词
  6475. $pic_prompt = trim(getProp($data, 'pic_prompt'));
  6476. if ($pic_prompt) {
  6477. // // 如果 pic_prompt 有变更,记录版本
  6478. // if ($pic_prompt !== $role->pic_prompt) {
  6479. // $needVersionRecord = true;
  6480. // }
  6481. $updateData['pic_prompt'] = $pic_prompt;
  6482. }
  6483. if (empty($updateData) && !$script_id) {
  6484. Utils::throwError('20003:没有需要更新的数据');
  6485. }
  6486. // // 如果需要记录版本,将数据添加到 versions 数组
  6487. // if ($needVersionRecord) {
  6488. // // 获取现有的 versions 数据
  6489. // $versions = json_decode($role->versions, true) ?: [];
  6490. // $isFirstVersion = empty($versions); // 判断是否是第一次记录版本
  6491. // // 如果是第一次记录版本,先添加旧版本(变更前)
  6492. // if ($isFirstVersion) {
  6493. // $oldVersion = [
  6494. // 'url' => $role->url,
  6495. // 'description' => $role->pic_prompt,
  6496. // ];
  6497. // // 旧版本添加到数组末尾
  6498. // $versions[] = $oldVersion;
  6499. // }
  6500. // // 构建新版本(变更后)
  6501. // $newVersion = [
  6502. // 'url' => isset($updateData['url']) ? $updateData['url'] : $role->url,
  6503. // 'description' => isset($updateData['pic_prompt']) ? $updateData['pic_prompt'] : $role->pic_prompt,
  6504. // ];
  6505. // // 检查新版本是否已存在于历史版本中
  6506. // $existingIndex = -1;
  6507. // foreach ($versions as $index => $version) {
  6508. // if ($version['url'] === $newVersion['url'] && $version['description'] === $newVersion['description']) {
  6509. // $existingIndex = $index;
  6510. // break;
  6511. // }
  6512. // }
  6513. // if ($existingIndex !== -1) {
  6514. // // 如果已存在,移除旧的位置
  6515. // array_splice($versions, $existingIndex, 1);
  6516. // }
  6517. // // 新版本添加到数组开头(最新的在前)
  6518. // array_unshift($versions, $newVersion);
  6519. // // // 限制版本数量(可选,例如只保留最近10个版本)
  6520. // // if (count($versions) > 10) {
  6521. // // $versions = array_slice($versions, 0, 10);
  6522. // // }
  6523. // $updateData['versions'] = json_encode($versions, 256);
  6524. // }
  6525. if ($versions) {
  6526. $updateData['versions'] = json_encode($versions, 256);
  6527. }
  6528. if (!empty($updateData)) {
  6529. $updateData['updated_at'] = date('Y-m-d H:i:s');
  6530. }
  6531. // 更新资产并保存剧本资产关联关系(同一事务)
  6532. DB::beginTransaction();
  6533. try {
  6534. $updated = true;
  6535. if (!empty($updateData)) {
  6536. $updated = DB::table('mp_products')
  6537. ->where('cpid', $cpid)
  6538. ->where('id', $id)
  6539. ->update($updateData);
  6540. }
  6541. // 保存剧本资产关联关系
  6542. if ($script_id) {
  6543. $this->saveProductScriptMapping($id, $script_id, $episode_numbers);
  6544. }
  6545. DB::commit();
  6546. } catch (\Exception $e) {
  6547. DB::rollback();
  6548. throw $e;
  6549. }
  6550. return $updated;
  6551. }
  6552. /**
  6553. * 保存单一资产与剧本剧集的关联关系
  6554. *
  6555. * @param int $product_id 资产ID
  6556. * @param int $script_id 剧本ID
  6557. * @param array $episode_numbers 剧集序号数组(序号从1开始)
  6558. * @return int 新增关联数量
  6559. */
  6560. private function saveProductScriptMapping($product_id, $script_id, $episode_numbers) {
  6561. $uid = Site::getUid();
  6562. // 验证剧本是否存在
  6563. $script = DB::table('mp_scripts')
  6564. ->where('id', $script_id)
  6565. ->where('is_deleted', 0)
  6566. ->first();
  6567. if (!$script) {
  6568. Utils::throwError('20003:剧本不存在');
  6569. }
  6570. // 验证剧本归属:只能关联自己的剧本
  6571. if ((int)$script->user_id !== (int)$uid) {
  6572. Utils::throwError('20003:只能添加到自己的剧本');
  6573. }
  6574. // 使用 splitContent 拆分剧本内容获取总集数
  6575. $totalEpisodes = $this->getScriptTotalEpisodeCount($script);
  6576. // 解析剧集序号(数组)
  6577. $episodes = [];
  6578. foreach ($episode_numbers as $item) {
  6579. if (is_array($item)) {
  6580. continue;
  6581. }
  6582. $item = trim((string)$item);
  6583. if ($item === '' || !is_numeric($item)) {
  6584. Utils::throwError('20003:剧集序号格式不正确,仅支持数字数组或英文逗号分隔的数字');
  6585. }
  6586. $episodes[] = (int)$item;
  6587. }
  6588. // 去重并校验序号范围(序号从1开始)
  6589. $episodes = array_values(array_unique($episodes));
  6590. if (empty($episodes)) {
  6591. Utils::throwError('20003:剧集序号不能为空');
  6592. }
  6593. foreach ($episodes as $episode) {
  6594. if ($episode < 1 || $episode > $totalEpisodes) {
  6595. Utils::throwError('20003:剧集序号 ' . $episode . ' 超出范围,剧本共 ' . $totalEpisodes . ' 集(序号从1开始)');
  6596. }
  6597. }
  6598. $now = now();
  6599. // 过滤已存在的关联,避免重复
  6600. $existingEpisodes = DB::table('mp_script_product_mappings')
  6601. ->where('script_id', $script_id)
  6602. ->where('product_id', $product_id)
  6603. ->whereIn('episode_number', $episodes)
  6604. ->pluck('episode_number')
  6605. ->all();
  6606. $mappingRecords = [];
  6607. foreach ($episodes as $episode) {
  6608. if (in_array($episode, $existingEpisodes)) {
  6609. continue;
  6610. }
  6611. $mappingRecords[] = [
  6612. 'script_id' => $script_id,
  6613. 'product_id' => $product_id,
  6614. 'episode_number' => $episode,
  6615. 'created_at' => $now,
  6616. 'updated_at' => $now,
  6617. ];
  6618. }
  6619. $insertedCount = 0;
  6620. if (!empty($mappingRecords)) {
  6621. $insertedCount = DB::table('mp_script_product_mappings')->insert($mappingRecords) ? count($mappingRecords) : 0;
  6622. }
  6623. return $insertedCount;
  6624. }
  6625. /**
  6626. * 规范化剧集序号参数,统一为数组
  6627. * 兼容传入数组(如 [1, 3, 5])、逗号分隔字符串(如 "1,3,5")以及字符串数组(如 ["1,3", 5])
  6628. *
  6629. * @param mixed $episode_number 剧集序号参数
  6630. * @return array
  6631. */
  6632. private function normalizeEpisodeNumbers($episode_number) {
  6633. if (!is_array($episode_number)) {
  6634. $episode_number = explode(',', (string)$episode_number);
  6635. }
  6636. $items = [];
  6637. foreach ($episode_number as $item) {
  6638. if (is_array($item)) {
  6639. continue;
  6640. }
  6641. foreach (explode(',', (string)$item) as $part) {
  6642. $part = trim($part);
  6643. if ($part !== '') {
  6644. $items[] = $part;
  6645. }
  6646. }
  6647. }
  6648. return $items;
  6649. }
  6650. /**
  6651. * 获取剧本总集数(通过 splitContent 拆分剧本内容)
  6652. *
  6653. * @param object $script 剧本记录
  6654. * @return int 总集数
  6655. */
  6656. private function getScriptTotalEpisodeCount($script) {
  6657. if (empty($script->content)) {
  6658. Utils::throwError('20003:剧本内容为空,无法确定剧集数量');
  6659. }
  6660. $totalEpisodes = count(splitContent($script->content));
  6661. if ($totalEpisodes < 1) {
  6662. Utils::throwError('20003:剧本内容无法拆分出剧集');
  6663. }
  6664. return $totalEpisodes;
  6665. }
  6666. /**
  6667. * 获取剧本总集数
  6668. *
  6669. * @param array $data 包含 script_id(剧本ID)
  6670. * @return array
  6671. */
  6672. public function getScriptTotalEpisodes($data) {
  6673. $script_id = (int)getProp($data, 'script_id', 0);
  6674. if (!$script_id) {
  6675. Utils::throwError('20003:请提供剧本ID');
  6676. }
  6677. // 验证剧本是否存在
  6678. $script = DB::table('mp_scripts')
  6679. ->where('id', $script_id)
  6680. ->where('is_deleted', 0)
  6681. ->first();
  6682. if (!$script) {
  6683. Utils::throwError('20003:剧本不存在');
  6684. }
  6685. return [
  6686. 'script_id' => $script_id,
  6687. 'script_name' => $script->script_name ?? 'script_' . $script_id,
  6688. 'episode_num' => $this->getScriptTotalEpisodeCount($script),
  6689. ];
  6690. }
  6691. /**
  6692. * 获取角色版本历史
  6693. * @param array $data 包含 id(角色ID)
  6694. * @return array 返回版本历史列表
  6695. */
  6696. public function getProductVersions($data) {
  6697. $cpid = Site::getCpid();
  6698. $id = getProp($data, 'id');
  6699. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6700. $role = DB::table('mp_products')
  6701. ->where('id', $id)
  6702. ->where('cpid', $cpid)
  6703. ->where('type', 1)
  6704. ->first();
  6705. if (!$role) Utils::throwError('20003:角色不存在');
  6706. // 获取版本历史
  6707. $versions = json_decode($role->versions, true) ?: [];
  6708. // 添加当前版本作为最新版本
  6709. $currentVersion = [
  6710. 'version' => 0, // 0 表示当前版本
  6711. 'url' => $role->url,
  6712. 'pic_prompt' => $role->pic_prompt,
  6713. 'updated_at' => $role->updated_at,
  6714. 'is_current' => true
  6715. ];
  6716. array_unshift($versions, $currentVersion);
  6717. return $versions;
  6718. }
  6719. /**
  6720. * 恢复到指定版本
  6721. * @param array $data 包含 id(角色ID)、version(版本号)
  6722. * @return bool
  6723. */
  6724. public function restoreProductVersion($data) {
  6725. $uid = Site::getUid();
  6726. $cpid = Site::getCpid();
  6727. $id = getProp($data, 'id');
  6728. $version = getProp($data, 'version');
  6729. if (!$id) Utils::throwError('20003:角色ID不能为空');
  6730. if (!$version) Utils::throwError('20003:版本号不能为空');
  6731. $role = DB::table('mp_products')
  6732. ->where('id', $id)
  6733. ->where('cpid', $cpid)
  6734. ->where('type', 1)
  6735. ->first();
  6736. if (!$role) Utils::throwError('20003:角色不存在');
  6737. // 获取版本历史
  6738. $versions = json_decode($role->versions, true) ?: [];
  6739. // 查找指定版本
  6740. $targetVersion = null;
  6741. foreach ($versions as $v) {
  6742. if ($v['version'] == $version) {
  6743. $targetVersion = $v;
  6744. break;
  6745. }
  6746. }
  6747. if (!$targetVersion) Utils::throwError('20003:版本不存在');
  6748. // 先将当前版本保存到历史
  6749. $newVersion = [
  6750. 'version' => count($versions) + 1,
  6751. 'url' => $role->url,
  6752. 'pic_prompt' => $role->pic_prompt,
  6753. 'updated_at' => date('Y-m-d H:i:s'),
  6754. 'updated_by' => $uid
  6755. ];
  6756. array_unshift($versions, $newVersion);
  6757. // 限制版本数量
  6758. if (count($versions) > 10) {
  6759. $versions = array_slice($versions, 0, 10);
  6760. }
  6761. // 恢复到指定版本
  6762. return DB::table('mp_products')
  6763. ->where('id', $id)
  6764. ->where('cpid', $cpid)
  6765. ->update([
  6766. 'url' => $targetVersion['url'],
  6767. 'pic_prompt' => $targetVersion['pic_prompt'],
  6768. 'versions' => json_encode($versions, JSON_UNESCAPED_UNICODE),
  6769. 'updated_at' => date('Y-m-d H:i:s')
  6770. ]);
  6771. }
  6772. public function deleteProduct($data) {
  6773. $uid = Site::getUid();
  6774. $cpid = Site::getCpid();
  6775. $role = Site::getRole();
  6776. $id = getProp($data, 'id');
  6777. if (!$id) Utils::throwError('20003:ID不能为空');
  6778. $ids = explode(',', $id);
  6779. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6780. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6781. $query_uid = $is_public ? 0 : $uid;
  6782. // 如果是公共库操作,需要admin权限
  6783. if ($is_public && $role !== 'admin') {
  6784. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6785. }
  6786. // 检查是否存在且属于当前用户或公共库
  6787. $role = DB::table('mp_products')
  6788. ->whereIn('id', $ids)
  6789. ->where('cpid', $cpid)
  6790. ->where('user_id', $query_uid)
  6791. ->get();
  6792. if (!$role) Utils::throwError('20003:记录不存在');
  6793. return DB::table('mp_products')
  6794. ->where('cpid', $cpid)
  6795. ->where('user_id', $query_uid)
  6796. ->whereIn('id', $ids)
  6797. ->update([
  6798. 'is_deleted' => 1,
  6799. 'updated_at' => date('Y-m-d H:i:s')
  6800. ]);
  6801. }
  6802. public function generateThreeView($data) {
  6803. $uid = Site::getUid();
  6804. $cpid = Site::getCpid();
  6805. $role = Site::getRole();
  6806. $id = getProp($data, 'id');
  6807. if (!$id) Utils::throwError('20003:ID不能为空');
  6808. $is_public = getProp($data, 'is_public', 0); // 0=个人资产库 1=公共资产库
  6809. // 根据is_public参数确定查询的user_id(公共库user_id=0,cpid保持不变)
  6810. $query_uid = $is_public ? 0 : $uid;
  6811. // 如果是公共库操作,需要admin权限
  6812. if ($is_public && $role !== 'admin') {
  6813. Utils::throwError('20003:只有管理员才能操作公共资产库');
  6814. }
  6815. // 检查是否存在且属于当前用户或公共库
  6816. $product = DB::table('mp_products')
  6817. ->where('id', $id)
  6818. ->where('cpid', $cpid)
  6819. ->where('user_id', $query_uid)
  6820. ->where('type', 1)->first();
  6821. if (!$product) Utils::throwError('20003:资产不存在');
  6822. $prompt = trim(getProp($data, 'prompt', '基于参考图生成主体的标准正面、侧面、后面三视图,主体完整。在最左侧添加主体正视图的特写,主体清晰完整。背景修改成纯白色,整体保持与参考图一致的美术风格和色彩搭配。画面无说明文字'));
  6823. $ref_img_url = trim(getProp($data, 'ref_img_url'));
  6824. if (!$ref_img_url) {
  6825. // 如果没有传入参考图,使用角色表中的图片
  6826. $ref_img_url = $product->url ?? '';
  6827. if (!$ref_img_url) {
  6828. Utils::throwError('20003:参考图不能为空');
  6829. }
  6830. }
  6831. $pic_prompt = getProp($product, 'pic_prompt');
  6832. if ($pic_prompt) {
  6833. $prompt .= '\n参考图原始提示词: '.$pic_prompt;
  6834. }
  6835. // 检查参考图是否是正确的图片格式
  6836. $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
  6837. $urlPath = parse_url($ref_img_url, PHP_URL_PATH);
  6838. $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
  6839. if (!in_array($extension, $allowedExtensions)) {
  6840. Utils::throwError('20003:参考图格式不正确,仅支持 jpg、jpeg、png、gif、webp、bmp 格式');
  6841. }
  6842. // 处理图片模型
  6843. $model = getProp($data, 'model');
  6844. if (!$model) {
  6845. // 使用默认模型
  6846. $model = 'doubao-seedream-5-0-lite-260128';
  6847. }
  6848. // 验证模型是否在可用模型表中
  6849. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6850. Utils::throwError('20003:该模型已不可用,请更换!');
  6851. }
  6852. $ratio = getProp($data, 'ratio', '16:9');
  6853. $resolution = getProp($data, 'resolution', '2k');
  6854. // 定义分辨率和宽高比对应的尺寸映射表
  6855. $sizeMap = [
  6856. '2k' => [
  6857. '1:1' => ['width' => 2048, 'height' => 2048],
  6858. '4:3' => ['width' => 2304, 'height' => 1728],
  6859. '3:4' => ['width' => 1728, 'height' => 2304],
  6860. '16:9' => ['width' => 2848, 'height' => 1600],
  6861. '9:16' => ['width' => 1600, 'height' => 2848],
  6862. '3:2' => ['width' => 2496, 'height' => 1664],
  6863. '2:3' => ['width' => 1664, 'height' => 2496],
  6864. '21:9' => ['width' => 3136, 'height' => 1344],
  6865. ],
  6866. '3k' => [
  6867. '1:1' => ['width' => 3072, 'height' => 3072],
  6868. '4:3' => ['width' => 3456, 'height' => 2592],
  6869. '3:4' => ['width' => 2592, 'height' => 3456],
  6870. '16:9' => ['width' => 4096, 'height' => 2304],
  6871. '9:16' => ['width' => 2304, 'height' => 4096],
  6872. '2:3' => ['width' => 2496, 'height' => 3744],
  6873. '3:2' => ['width' => 3744, 'height' => 2496],
  6874. '21:9' => ['width' => 4704, 'height' => 2016],
  6875. ],
  6876. '4k' => [
  6877. '1:1' => ['width' => 4096, 'height' => 4096],
  6878. '3:4' => ['width' => 3520, 'height' => 4704],
  6879. '4:3' => ['width' => 4704, 'height' => 3520],
  6880. '16:9' => ['width' => 5504, 'height' => 3040],
  6881. '9:16' => ['width' => 3040, 'height' => 5504],
  6882. '2:3' => ['width' => 3328, 'height' => 4992],
  6883. '3:2' => ['width' => 4992, 'height' => 3328],
  6884. '21:9' => ['width' => 6240, 'height' => 2656],
  6885. ],
  6886. ];
  6887. // 参数验证
  6888. $resolution = strtolower($resolution);
  6889. if (!isset($sizeMap[$resolution])) {
  6890. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  6891. }
  6892. if (!isset($sizeMap[$resolution][$ratio])) {
  6893. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  6894. }
  6895. // 根据 ratio 和 resolution 确定宽高
  6896. $width = $sizeMap[$resolution][$ratio]['width'];
  6897. $height = $sizeMap[$resolution][$ratio]['height'];
  6898. try {
  6899. // 创建图片生成任务
  6900. $params = [
  6901. 'prompt' => $prompt,
  6902. 'model' => $model,
  6903. 'ref_img_urls' => [$ref_img_url],
  6904. 'width' => $width,
  6905. 'height' => $height
  6906. ];
  6907. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  6908. $task_id = $task->id;
  6909. if (!$task_id) {
  6910. Utils::throwError('20003:创建图片生成任务失败');
  6911. }
  6912. // 轮询获取结果
  6913. // 只查询数据库,不调用API,不更新任务表
  6914. $start_time = time();
  6915. $timeout = 1800;
  6916. $img_url = '';
  6917. while (time() - $start_time < $timeout) {
  6918. sleep(5);
  6919. // 只查询数据库中的任务状态,不调用API,不更新任务表
  6920. $task = DB::table('mp_generate_pic_tasks')
  6921. ->where('id', $task_id)
  6922. ->first();
  6923. if (!$task) {
  6924. Utils::throwError('20003:任务不存在');
  6925. }
  6926. if ($task->status === 'success' && $task->result_url) {
  6927. $result_urls = is_string($task->result_url)
  6928. ? json_decode($task->result_url, true)
  6929. : $task->result_url;
  6930. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  6931. break;
  6932. } elseif ($task->status === 'failed') {
  6933. Utils::throwError('20003:三视图生成失败,' . ($task->error_message ?? '未知错误'));
  6934. }
  6935. // 其他状态继续轮询
  6936. }
  6937. if (empty($img_url)) {
  6938. Utils::throwError('20003:三视图生成超时,请稍后重试');
  6939. }
  6940. // 更新 mp_products 表(不是任务表)
  6941. DB::table('mp_products')
  6942. ->where('id', $id)
  6943. ->where('cpid', $cpid)
  6944. ->update([
  6945. 'three_view_image_url' => $img_url,
  6946. 'updated_at' => date('Y-m-d H:i:s')
  6947. ]);
  6948. return ['three_view_image_url' => $img_url];
  6949. } catch (\Exception $e) {
  6950. dLog('anime')->error('生成三视图失败', [
  6951. 'error' => $e->getMessage()
  6952. ]);
  6953. logDB('anime', 'error', '生成三视图失败', ['error' => $e->getMessage()]);
  6954. Utils::throwError('20003:' . $e->getMessage());
  6955. }
  6956. }
  6957. /**
  6958. * 推送(复制)资产或文件夹到目标位置
  6959. * @param array $data 包含 product_id(要推送的资产或文件夹ID)、target_parent_id(目标父文件夹ID,0表示根目录)
  6960. * @return array 返回推送结果
  6961. */
  6962. public function pushProductOrFolder($data) {
  6963. $uid = Site::getUid();
  6964. $cpid = Site::getCpid();
  6965. $role = Site::getRole();
  6966. $product_id = getProp($data, 'product_id');
  6967. $target_parent_id = getProp($data, 'target_parent_id', 0);
  6968. $target_product = getProp($data, 'product'); // 目标 product 类型,用于跨类型推送
  6969. if (!$product_id) {
  6970. Utils::throwError('20003:请选择要推送的项目');
  6971. }
  6972. // 查询源项目(只通过cpid查询,不限制user_id)
  6973. $sourceItem = DB::table('mp_products')
  6974. ->where('id', $product_id)
  6975. ->where('cpid', $cpid)
  6976. ->where('is_deleted', 0)
  6977. ->first();
  6978. if (!$sourceItem) {
  6979. Utils::throwError('20003:要推送的项目不存在');
  6980. }
  6981. // 通过user_id判断源是公共库还是个人库
  6982. $source_uid = $sourceItem->user_id;
  6983. $source_is_public = ($source_uid == 0) ? 1 : 0;
  6984. // 验证目标文件夹并确定目标是公共库还是个人库
  6985. $target_level = 0;
  6986. $target_uid = $uid; // 默认推送到个人库
  6987. $target_is_public = 0;
  6988. $final_product_type = $sourceItem->product; // 默认使用源的 product 类型
  6989. if ($target_parent_id > 0) {
  6990. // 查询目标文件夹(只通过cpid查询,不限制user_id)
  6991. $targetParent = DB::table('mp_products')
  6992. ->where('id', $target_parent_id)
  6993. ->where('cpid', $cpid)
  6994. ->where('type', 2)
  6995. ->where('is_deleted', 0)
  6996. ->first();
  6997. if (!$targetParent) {
  6998. Utils::throwError('20003:目标文件夹不存在');
  6999. }
  7000. // 通过user_id判断目标是公共库还是个人库
  7001. $target_level = $targetParent->level;
  7002. $target_uid = $targetParent->user_id;
  7003. $target_is_public = ($target_uid == 0) ? 1 : 0;
  7004. // 使用目标文件夹的 product 类型
  7005. $final_product_type = $targetParent->product;
  7006. }
  7007. // 如果 target_parent_id = 0(推送到根目录),需要通过参数判断推送到个人库还是公共库
  7008. else {
  7009. $push_to_public = getProp($data, 'push_to_public');
  7010. if ($push_to_public === '') {
  7011. Utils::throwError('20003:请选择是否推送到公共库');
  7012. }
  7013. if ($push_to_public) {
  7014. $target_uid = 0;
  7015. $target_is_public = 1;
  7016. }
  7017. // 推送到根目录时,必须指定 product 类型
  7018. if ($target_product === null || $target_product === '') {
  7019. Utils::throwError('20003:推送到根目录时必须指定目标类型(product)');
  7020. }
  7021. $final_product_type = $target_product;
  7022. }
  7023. // 如果目标是公共库,需要admin权限
  7024. if ($target_is_public && $role !== 'admin') {
  7025. Utils::throwError('20003:只有管理员才能推送到公共资产库');
  7026. }
  7027. // 权限验证:验证是否符合允许的推送规则
  7028. $this->validatePushPermission($source_uid, $target_uid, $uid);
  7029. try {
  7030. DB::beginTransaction();
  7031. // 如果是资产,直接复制(支持跨类型推送,更新 product 字段)
  7032. if ($sourceItem->type == 1) {
  7033. $newId = $this->copyProduct($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $final_product_type);
  7034. DB::commit();
  7035. return [
  7036. 'product_id' => $newId,
  7037. ];
  7038. }
  7039. // 如果是文件夹,递归复制(支持跨类型推送)
  7040. $newFolderId = $this->copyFolderRecursive($sourceItem, $target_parent_id, $target_level + 1, $cpid, $target_uid, $source_uid, $final_product_type);
  7041. DB::commit();
  7042. return [
  7043. 'product_id' => $newFolderId,
  7044. ];
  7045. } catch (\Exception $e) {
  7046. DB::rollBack();
  7047. dLog('anime')->error('推送失败', [
  7048. 'error' => $e->getMessage(),
  7049. 'product_id' => $product_id
  7050. ]);
  7051. Utils::throwError('20003:' . $e->getMessage());
  7052. }
  7053. }
  7054. /**
  7055. * 验证推送权限
  7056. * 允许的推送规则:
  7057. * 1. 自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7058. * 2. 公共库推送给自己的个人库(公共库 → 个人库)
  7059. * 3. 公共库推送给公共库(公共库 → 公共库)
  7060. *
  7061. * @param int $source_uid 源的user_id
  7062. * @param int $target_uid 目标的user_id
  7063. * @param int $current_uid 当前用户ID
  7064. * @throws \Exception
  7065. */
  7066. private function validatePushPermission($source_uid, $target_uid, $current_uid) {
  7067. // 规则1:自己推送给自己的个人库(个人库 → 个人库,同一用户)
  7068. if ($source_uid == $current_uid && $target_uid == $current_uid) {
  7069. return; // 允许
  7070. }
  7071. // 规则2:公共库推送给自己的个人库(公共库 → 个人库)
  7072. if ($source_uid == 0 && $target_uid == $current_uid) {
  7073. return; // 允许
  7074. }
  7075. // 规则3:公共库推送给公共库(公共库 → 公共库)
  7076. if ($source_uid == 0 && $target_uid == 0) {
  7077. return; // 允许
  7078. }
  7079. // 其他情况都不允许
  7080. if ($source_uid != 0 && $source_uid != $current_uid) {
  7081. // 源是别人的个人库
  7082. Utils::throwError('20003:无权限访问该资产');
  7083. } elseif ($source_uid == $current_uid && $target_uid == 0) {
  7084. // 个人库推送给公共库(不允许)
  7085. Utils::throwError('20003:不允许将个人资产推送到公共库');
  7086. } elseif ($source_uid != 0 && $target_uid != 0 && $source_uid != $target_uid) {
  7087. // 不同用户的个人库之间推送(不允许)
  7088. Utils::throwError('20003:不允许推送到其他用户的个人库');
  7089. } else {
  7090. // 其他未知情况
  7091. Utils::throwError('20003:不允许的推送操作');
  7092. }
  7093. }
  7094. /**
  7095. * 复制单个资产
  7096. * @param object $sourceProduct 源资产对象
  7097. * @param int $targetParentId 目标父文件夹ID
  7098. * @param int $targetLevel 目标层级
  7099. * @param int $cpid 公司ID
  7100. * @param int $targetUid 目标用户ID
  7101. * @return int 返回新资产ID
  7102. */
  7103. private function copyProduct($sourceProduct, $targetParentId, $targetLevel, $cpid, $targetUid, $productType = null) {
  7104. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7105. $finalProductType = ($productType !== null) ? $productType : $sourceProduct->product;
  7106. $newProductData = [
  7107. 'user_id' => $targetUid,
  7108. 'cpid' => $cpid,
  7109. 'type' => 1,
  7110. 'parent_id' => $targetParentId,
  7111. 'level' => $targetLevel,
  7112. 'product_name' => $sourceProduct->product_name,
  7113. 'url' => $sourceProduct->url,
  7114. 'pic_prompt' => $sourceProduct->pic_prompt ?? '',
  7115. 'three_view_image_url' => $sourceProduct->three_view_image_url ?? '',
  7116. 'product' => $finalProductType,
  7117. 'versions' => $sourceProduct->versions ?? '',
  7118. 'sort_order' => time(),
  7119. 'is_deleted' => 0,
  7120. 'created_at' => date('Y-m-d H:i:s'),
  7121. 'updated_at' => date('Y-m-d H:i:s')
  7122. ];
  7123. return DB::table('mp_products')->insertGetId($newProductData);
  7124. }
  7125. /**
  7126. * 递归复制文件夹及其子项
  7127. * @param object $sourceFolder 源文件夹对象
  7128. * @param int $targetParentId 目标父文件夹ID
  7129. * @param int $targetLevel 目标层级
  7130. * @param int $cpid 公司ID
  7131. * @param int $targetUid 目标用户ID
  7132. * @param int $sourceUid 源用户ID
  7133. * @return int 返回新文件夹ID
  7134. */
  7135. private function copyFolderRecursive($sourceFolder, $targetParentId, $targetLevel, $cpid, $targetUid, $sourceUid, $productType = null) {
  7136. // 如果指定了 productType,使用指定的;否则使用源的 product 类型
  7137. $finalProductType = ($productType !== null) ? $productType : $sourceFolder->product;
  7138. // 创建新文件夹
  7139. $newFolderData = [
  7140. 'user_id' => $targetUid,
  7141. 'cpid' => $cpid,
  7142. 'type' => 2,
  7143. 'parent_id' => $targetParentId,
  7144. 'level' => $targetLevel,
  7145. 'product_name' => $sourceFolder->product_name,
  7146. 'product' => $finalProductType,
  7147. 'sort_order' => time(),
  7148. 'is_deleted' => 0,
  7149. 'created_at' => date('Y-m-d H:i:s'),
  7150. 'updated_at' => date('Y-m-d H:i:s')
  7151. ];
  7152. $newFolderId = DB::table('mp_products')->insertGetId($newFolderData);
  7153. // 获取源文件夹下的所有子项
  7154. $children = DB::table('mp_products')
  7155. ->where('parent_id', $sourceFolder->id)
  7156. ->where('cpid', $cpid)
  7157. ->where('user_id', $sourceUid)
  7158. ->where('is_deleted', 0)
  7159. ->orderByRaw('type DESC, sort_order DESC, created_at DESC')
  7160. ->get();
  7161. // 递归复制子项(子项继承目标文件夹的 product 类型)
  7162. foreach ($children as $child) {
  7163. if ($child->type == 1) {
  7164. // 资产
  7165. $this->copyProduct($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $finalProductType);
  7166. } else {
  7167. // 文件夹
  7168. $this->copyFolderRecursive($child, $newFolderId, $targetLevel + 1, $cpid, $targetUid, $sourceUid, $finalProductType);
  7169. }
  7170. }
  7171. return $newFolderId;
  7172. }
  7173. /**
  7174. * 保存剧本资产关联关系
  7175. * @param array $data 请求参数
  7176. * @return bool
  7177. */
  7178. public function saveScriptProducts($data) {
  7179. $uid = Site::getUid();
  7180. $cpid = Site::getCpid();
  7181. $script_id = getProp($data, 'script_id');
  7182. $products = getProp($data, 'products', []);
  7183. $auto_generate_images = getProp($data, 'auto_generate_images', true); // 是否自动生成图片,默认true
  7184. if (!$script_id) {
  7185. Utils::throwError('20003:请提供剧本ID');
  7186. }
  7187. // 验证剧本是否存在
  7188. $script = DB::table('mp_scripts')
  7189. ->where('id', $script_id)
  7190. ->where('is_deleted', 0)
  7191. ->first();
  7192. if (!$script) {
  7193. Utils::throwError('20003:剧本不存在');
  7194. }
  7195. // 处理图片模型
  7196. $model = getProp($data, 'model');
  7197. if (!$model) {
  7198. // 使用默认模型
  7199. $model = 'doubao-seedream-5-0-lite-260128';
  7200. }
  7201. // 验证模型是否在可用模型表中
  7202. if (!DB::table('mp_image_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7203. Utils::throwError('20003:该模型已不可用,请更换!');
  7204. }
  7205. $ratio = getProp($data, 'ratio', '9:16');
  7206. $resolution = getProp($data, 'resolution', '2k');
  7207. // 定义分辨率和宽高比对应的尺寸映射表
  7208. $sizeMap = [
  7209. '2k' => [
  7210. '1:1' => ['width' => 2048, 'height' => 2048],
  7211. '4:3' => ['width' => 2304, 'height' => 1728],
  7212. '3:4' => ['width' => 1728, 'height' => 2304],
  7213. '16:9' => ['width' => 2848, 'height' => 1600],
  7214. '9:16' => ['width' => 1600, 'height' => 2848],
  7215. '3:2' => ['width' => 2496, 'height' => 1664],
  7216. '2:3' => ['width' => 1664, 'height' => 2496],
  7217. '21:9' => ['width' => 3136, 'height' => 1344],
  7218. ],
  7219. '3k' => [
  7220. '1:1' => ['width' => 3072, 'height' => 3072],
  7221. '4:3' => ['width' => 3456, 'height' => 2592],
  7222. '3:4' => ['width' => 2592, 'height' => 3456],
  7223. '16:9' => ['width' => 4096, 'height' => 2304],
  7224. '9:16' => ['width' => 2304, 'height' => 4096],
  7225. '2:3' => ['width' => 2496, 'height' => 3744],
  7226. '3:2' => ['width' => 3744, 'height' => 2496],
  7227. '21:9' => ['width' => 4704, 'height' => 2016],
  7228. ],
  7229. '4k' => [
  7230. '1:1' => ['width' => 4096, 'height' => 4096],
  7231. '3:4' => ['width' => 3520, 'height' => 4704],
  7232. '4:3' => ['width' => 4704, 'height' => 3520],
  7233. '16:9' => ['width' => 5504, 'height' => 3040],
  7234. '9:16' => ['width' => 3040, 'height' => 5504],
  7235. '2:3' => ['width' => 3328, 'height' => 4992],
  7236. '3:2' => ['width' => 4992, 'height' => 3328],
  7237. '21:9' => ['width' => 6240, 'height' => 2656],
  7238. ],
  7239. ];
  7240. // 参数验证
  7241. $resolution = strtolower($resolution);
  7242. if (!isset($sizeMap[$resolution])) {
  7243. Utils::throwError('20003:分辨率参数错误,仅支持 2k、3k、4k');
  7244. }
  7245. if (!isset($sizeMap[$resolution][$ratio])) {
  7246. Utils::throwError('20003:宽高比参数错误,该分辨率下不支持 ' . $ratio . ' 比例');
  7247. }
  7248. // 根据 ratio 和 resolution 确定宽高
  7249. $width = $sizeMap[$resolution][$ratio]['width'];
  7250. $height = $sizeMap[$resolution][$ratio]['height'];
  7251. $script_name = $script->script_name ?? 'script_' . $script_id;
  7252. // 根据入参创建/复用任务中心记录(params md5 验重,避免重复任务)
  7253. $taskCenterId = $this->createScriptProductTaskCenter(
  7254. $uid,
  7255. $cpid,
  7256. $script_id,
  7257. $products,
  7258. $model,
  7259. $ratio,
  7260. $resolution,
  7261. $auto_generate_images
  7262. );
  7263. // 检查是否已经有该剧本的资产数据
  7264. $existingMappings = DB::table('mp_script_product_mappings')
  7265. ->where('script_id', $script_id)
  7266. ->get();
  7267. if ($existingMappings->isNotEmpty()) {
  7268. // 已存在资产映射,检查是否所有资产都有图片生成任务
  7269. $productIds = $existingMappings->pluck('product_id')->unique()->toArray();
  7270. // 查询这些资产的图片生成任务状态
  7271. $productsWithTasks = DB::table('mp_products')
  7272. ->whereIn('id', $productIds)
  7273. ->where('is_deleted', 0)
  7274. ->get();
  7275. $productTaskMap = [];
  7276. $typeFolderIds = [];
  7277. $hasAllTasks = true;
  7278. foreach ($productsWithTasks as $product) {
  7279. // 收集类型文件夹ID
  7280. if ($product->parent_id > 0 && !in_array($product->parent_id, $typeFolderIds)) {
  7281. $parentFolder = DB::table('mp_products')
  7282. ->where('id', $product->parent_id)
  7283. ->where('type', 2)
  7284. ->first();
  7285. if ($parentFolder) {
  7286. $typeFolderIds[$parentFolder->product] = $parentFolder->id;
  7287. }
  7288. }
  7289. // 检查是否有图片生成任务
  7290. if (!empty($product->pic_task_id)) {
  7291. $productTaskMap[$product->id] = $product->pic_task_id;
  7292. } else if($product->url && $product->pic_task_status == '生成成功') {
  7293. continue;
  7294. } else {
  7295. // 有资产没有图片任务
  7296. $hasAllTasks = false;
  7297. }
  7298. }
  7299. // 如果所有资产都有任务ID,直接轮询返回结果
  7300. if ($hasAllTasks && !empty($productTaskMap)) {
  7301. dLog('anime')->info('剧本资产已存在且都有图片任务,直接轮询结果', [
  7302. 'script_id' => $script_id,
  7303. 'script_name' => $script_name,
  7304. 'product_count' => count($productTaskMap)
  7305. ]);
  7306. // 直接返回 SSE 流轮询结果
  7307. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7308. }
  7309. // 如果部分资产没有任务ID,只为这些资产创建任务
  7310. if (!$hasAllTasks && $auto_generate_images) {
  7311. dLog('anime')->info('剧本资产已存在,但部分资产没有图片任务,为缺失的资产创建任务', [
  7312. 'script_id' => $script_id,
  7313. 'script_name' => $script_name
  7314. ]);
  7315. // 开启事务
  7316. DB::beginTransaction();
  7317. try {
  7318. foreach ($productsWithTasks as $product) {
  7319. // 跳过已有任务的资产
  7320. if (!empty($product->pic_task_id)) {
  7321. continue;
  7322. }
  7323. // 跳过没有提示词的资产
  7324. if (empty($product->pic_prompt)) {
  7325. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7326. 'product_id' => $product->id,
  7327. 'product_name' => $product->product_name
  7328. ]);
  7329. continue;
  7330. }
  7331. try {
  7332. // 创建图片生成任务
  7333. $params = [
  7334. 'prompt' => $product->pic_prompt,
  7335. 'model' => $model,
  7336. 'ref_img_urls' => [],
  7337. 'width' => $width,
  7338. 'height' => $height
  7339. ];
  7340. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7341. $task_id = $task->id;
  7342. if ($task_id) {
  7343. $productTaskMap[$product->id] = $task_id;
  7344. // 在事务中更新资产表的任务ID和状态
  7345. DB::table('mp_products')
  7346. ->where('id', $product->id)
  7347. ->update([
  7348. 'pic_task_id' => $task_id,
  7349. 'pic_task_status' => '生成中',
  7350. 'updated_at' => now()
  7351. ]);
  7352. dLog('anime')->info('为已存在资产创建图片生成任务', [
  7353. 'product_id' => $product->id,
  7354. 'task_id' => $task_id
  7355. ]);
  7356. }
  7357. } catch (\Exception $e) {
  7358. dLog('anime')->error('创建资产图片生成任务失败', [
  7359. 'product_id' => $product->id,
  7360. 'error' => $e->getMessage()
  7361. ]);
  7362. // 标记为失败(仍在事务中)
  7363. DB::table('mp_products')
  7364. ->where('id', $product->id)
  7365. ->update([
  7366. 'pic_task_status' => '生成失败',
  7367. 'updated_at' => now()
  7368. ]);
  7369. }
  7370. }
  7371. // 提交事务
  7372. DB::commit();
  7373. // 如果有新创建的任务,返回 SSE 流
  7374. if (!empty($productTaskMap)) {
  7375. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7376. }
  7377. } catch (\Exception $e) {
  7378. // 回滚事务
  7379. DB::rollback();
  7380. dLog('anime')->error('为已存在资产创建图片任务失败', [
  7381. 'script_id' => $script_id,
  7382. 'error' => $e->getMessage()
  7383. ]);
  7384. Utils::throwError('20003:创建图片任务失败:' . $e->getMessage());
  7385. }
  7386. }
  7387. // 如果不需要生成图片,返回已存在的信息
  7388. $resultData = [
  7389. 'success' => true,
  7390. 'message' => '剧本资产已存在',
  7391. 'script_id' => $script_id,
  7392. 'script_name' => $script_name,
  7393. 'type_folder_ids' => $typeFolderIds,
  7394. 'existing_products' => count($productIds),
  7395. 'tasks_count' => count($productTaskMap),
  7396. 'task_center_id' => $taskCenterId
  7397. ];
  7398. // 接口已正常完成,更新任务中心状态和结果
  7399. if ($taskCenterId) {
  7400. $this->taskCenterService->updateTask($taskCenterId, [
  7401. 'status' => MpTaskCenter::STATUS_SUCCESS,
  7402. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  7403. 'error_message' => null
  7404. ]);
  7405. }
  7406. return $resultData;
  7407. }
  7408. // 解析 products(可能是 JSON 字符串或数组)
  7409. if (is_string($products)) {
  7410. $products = json_decode($products, true);
  7411. if (json_last_error() !== JSON_ERROR_NONE) {
  7412. Utils::throwError('20003:产品数据格式错误');
  7413. }
  7414. }
  7415. if (!is_array($products) || empty($products)) {
  7416. Utils::throwError('20003:产品数据不能为空');
  7417. }
  7418. // 以下是原有的创建逻辑...
  7419. // 开启事务
  7420. DB::beginTransaction();
  7421. try {
  7422. $now = now();
  7423. $mappingRecords = [];
  7424. $createdProductIds = []; // 记录所有创建的资产ID
  7425. // 获取剧本名称
  7426. $script_name = $script->script_name ?? 'script_' . $script_id;
  7427. // 存储每个类型的根文件夹ID
  7428. $typeFolderIds = [];
  7429. // 遍历每个产品类型(type: 1=角色, 2=场景, 3=道具)
  7430. foreach ($products as $productGroup) {
  7431. $type = getProp($productGroup, 'type');
  7432. $title = getProp($productGroup, 'title', '');
  7433. $content = getProp($productGroup, 'content', []);
  7434. if (!in_array($type, [1, 2, 3]) || empty($content) || count($content) < 2) {
  7435. continue;
  7436. }
  7437. // 为当前类型创建根文件夹(如果还未创建)
  7438. if (!isset($typeFolderIds[$type])) {
  7439. $typeFolderIds[$type] = DB::table('mp_products')->insertGetId([
  7440. 'user_id' => $uid,
  7441. 'cpid' => $cpid,
  7442. 'type' => 2, // 1.资产 2文件夹
  7443. 'product' => $type, // 1.主体 2.场景 3.道具
  7444. 'parent_id' => 0, // 根文件夹,parent_id=0
  7445. 'level' => 1, // 第一层级
  7446. 'product_name' => $script_name,
  7447. 'sort_order' => time() + $type,
  7448. 'is_deleted' => 0,
  7449. 'created_at' => $now,
  7450. 'updated_at' => $now
  7451. ]);
  7452. }
  7453. $folder_id = $typeFolderIds[$type];
  7454. // 获取表头(第一行)并查找关键列的位置
  7455. $headers = $content[0];
  7456. $nameColumnIndex = -1; // 资产名称列索引
  7457. $sequenceColumnIndex = -1; // 使用范围列索引
  7458. $promptColumnIndex = -1; // 参考提示词列索引
  7459. foreach ($headers as $index => $header) {
  7460. // 查找"资产名称"列
  7461. if (strpos($header, '资产名称') !== false || strpos($header, '名称') !== false) {
  7462. $nameColumnIndex = $index;
  7463. }
  7464. // 查找"使用范围"列
  7465. if (strpos($header, '使用范围') !== false || strpos($header, '范围') !== false) {
  7466. $sequenceColumnIndex = $index;
  7467. }
  7468. // 查找"参考提示词"列(可能是"干净参考图提示词"、"参考提示词"等)
  7469. if (strpos($header, '参考') !== false && strpos($header, '提示词') !== false) {
  7470. $promptColumnIndex = $index;
  7471. }
  7472. }
  7473. // 验证必要的列是否都找到了
  7474. if ($nameColumnIndex === -1) {
  7475. dLog('anime')->warning('未找到资产名称列', ['type' => $type, 'headers' => $headers]);
  7476. continue;
  7477. }
  7478. if ($sequenceColumnIndex === -1) {
  7479. dLog('anime')->warning('未找到使用范围列', ['type' => $type, 'headers' => $headers]);
  7480. continue;
  7481. }
  7482. // 跳过表头,解析每一行数据
  7483. for ($i = 1; $i < count($content); $i++) {
  7484. $row = $content[$i];
  7485. // 确保行数据有效
  7486. if (empty($row) || count($row) <= max($nameColumnIndex, $sequenceColumnIndex)) {
  7487. continue;
  7488. }
  7489. // 根据动态查找的列索引提取数据
  7490. $product_name = isset($row[$nameColumnIndex]) ? trim((string)$row[$nameColumnIndex]) : '';
  7491. $sequence_str = isset($row[$sequenceColumnIndex]) ? trim($row[$sequenceColumnIndex]) : '';
  7492. $pic_prompt = '';
  7493. // 提取参考提示词(如果找到了该列)
  7494. if ($promptColumnIndex >= 0 && isset($row[$promptColumnIndex])) {
  7495. $pic_prompt = trim($row[$promptColumnIndex]);
  7496. }
  7497. // 解析使用范围(逗号分隔的序号)
  7498. $sequences = [];
  7499. if (!empty($sequence_str)) {
  7500. $sequenceParts = array_map('trim', explode(',', $sequence_str));
  7501. foreach ($sequenceParts as $part) {
  7502. if (is_numeric($part)) {
  7503. $sequences[] = (int)$part;
  7504. }
  7505. }
  7506. }
  7507. if (empty($product_name)) {
  7508. continue;
  7509. }
  7510. // 处理product_name两边的符号
  7511. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7512. // 如果名称不存在或仅剩占位符号,则跳过
  7513. if (!$product_name || preg_match('/^[-—_]+$/u', $product_name)) {
  7514. dLog('anime')->warning('资产名称无效,跳过保存', [
  7515. 'script_id' => $script_id,
  7516. 'type' => $type,
  7517. 'product_name' => $product_name
  7518. ]);
  7519. continue;
  7520. }
  7521. // 直接插入新资产到 mp_products 表(parent_id 指向对应类型的根文件夹)
  7522. $product_id = DB::table('mp_products')->insertGetId([
  7523. 'product_name' => $product_name,
  7524. 'type' => 1, // 1=资产 2.文件夹
  7525. 'product' => $type, // 1=角色, 2=场景, 3=道具
  7526. 'parent_id' => $folder_id, // 父文件夹是该类型的根文件夹
  7527. 'level' => 2, // 第二层级
  7528. 'pic_prompt' => $pic_prompt,
  7529. 'user_id' => $uid,
  7530. 'cpid' => $cpid,
  7531. 'sort_order' => time(),
  7532. 'is_deleted' => 0,
  7533. 'created_at' => $now,
  7534. 'updated_at' => $now,
  7535. ]);
  7536. // 记录创建的资产ID
  7537. $createdProductIds[] = $product_id;
  7538. // 为每个序号创建映射记录
  7539. if (!empty($sequences)) {
  7540. foreach ($sequences as $sequence) {
  7541. $mappingRecords[] = [
  7542. 'script_id' => $script_id,
  7543. 'product_id' => $product_id,
  7544. 'episode_number' => $sequence,
  7545. 'created_at' => $now,
  7546. 'updated_at' => $now,
  7547. ];
  7548. }
  7549. } else {
  7550. // 如果没有指定序号,创建一个默认映射(序号为0)
  7551. $mappingRecords[] = [
  7552. 'script_id' => $script_id,
  7553. 'product_id' => $product_id,
  7554. 'episode_number' => 0,
  7555. 'created_at' => $now,
  7556. 'updated_at' => $now,
  7557. ];
  7558. }
  7559. }
  7560. }
  7561. if (empty($mappingRecords)) {
  7562. Utils::throwError('20003:没有有效的产品数据');
  7563. }
  7564. // 批量插入映射数据(使用 insertOrIgnore 避免重复插入)
  7565. $insertedCount = DB::table('mp_script_product_mappings')->insertOrIgnore($mappingRecords);
  7566. // 剧本已有资产,同步更新is_products标记
  7567. DB::table('mp_scripts')->where('id', $script_id)->update([
  7568. 'is_products' => 1,
  7569. 'updated_at' => $now
  7570. ]);
  7571. // 如果需要自动生成图片,在事务中创建图片生成任务
  7572. $productTaskMap = [];
  7573. if ($auto_generate_images && !empty($createdProductIds)) {
  7574. // 查询所有创建的资产
  7575. $productsToGenerate = DB::table('mp_products')
  7576. ->whereIn('id', $createdProductIds)
  7577. ->where('is_deleted', 0)
  7578. ->get();
  7579. foreach ($productsToGenerate as $product) {
  7580. if (empty($product->pic_prompt)) {
  7581. dLog('anime')->warning('资产没有提示词,跳过图片生成', [
  7582. 'product_id' => $product->id,
  7583. 'product_name' => $product->product_name
  7584. ]);
  7585. continue;
  7586. }
  7587. try {
  7588. // 创建图片生成任务
  7589. $params = [
  7590. 'prompt' => $product->pic_prompt,
  7591. 'model' => $model,
  7592. 'ref_img_urls' => [],
  7593. 'width' => $width,
  7594. 'height' => $height
  7595. ];
  7596. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7597. $task_id = $task->id;
  7598. if ($task_id) {
  7599. $productTaskMap[$product->id] = $task_id;
  7600. // 在事务中更新资产表的任务ID和状态
  7601. DB::table('mp_products')
  7602. ->where('id', $product->id)
  7603. ->update([
  7604. 'pic_task_id' => $task_id,
  7605. 'pic_task_status' => '生成中',
  7606. 'updated_at' => now()
  7607. ]);
  7608. dLog('anime')->info('创建资产图片生成任务', [
  7609. 'product_id' => $product->id,
  7610. 'task_id' => $task_id
  7611. ]);
  7612. }
  7613. } catch (\Exception $e) {
  7614. dLog('anime')->error('创建资产图片生成任务失败', [
  7615. 'product_id' => $product->id,
  7616. 'error' => $e->getMessage()
  7617. ]);
  7618. // 标记为失败(仍在事务中)
  7619. DB::table('mp_products')
  7620. ->where('id', $product->id)
  7621. ->update([
  7622. 'pic_task_status' => '生成失败',
  7623. 'updated_at' => now()
  7624. ]);
  7625. }
  7626. }
  7627. }
  7628. // 提交事务
  7629. DB::commit();
  7630. // 事务提交成功后,如果有图片生成任务,则返回 SSE 流
  7631. if ($auto_generate_images && !empty($productTaskMap)) {
  7632. // 返回 SSE 流(事务外轮询)
  7633. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $typeFolderIds, $taskCenterId);
  7634. }
  7635. // 如果不需要生成图片,返回普通结果
  7636. $resultData = [
  7637. 'success' => true,
  7638. 'type_folder_ids' => $typeFolderIds,
  7639. 'inserted_count' => $insertedCount,
  7640. 'total_records' => count($mappingRecords),
  7641. 'created_products' => count($createdProductIds),
  7642. 'image_tasks_created' => count($productTaskMap),
  7643. 'task_center_id' => $taskCenterId
  7644. ];
  7645. // 接口已正常完成,更新任务中心状态和结果
  7646. if ($taskCenterId) {
  7647. $this->taskCenterService->updateTask($taskCenterId, [
  7648. 'status' => MpTaskCenter::STATUS_SUCCESS,
  7649. 'result' => json_encode($resultData, JSON_UNESCAPED_UNICODE),
  7650. 'error_message' => null
  7651. ]);
  7652. }
  7653. return $resultData;
  7654. } catch (\Exception $e) {
  7655. // 回滚事务
  7656. DB::rollback();
  7657. // 更新任务中心状态为失败
  7658. if (!empty($taskCenterId)) {
  7659. $this->taskCenterService->updateTask($taskCenterId, [
  7660. 'status' => MpTaskCenter::STATUS_FAILED,
  7661. 'error_message' => $e->getMessage()
  7662. ]);
  7663. }
  7664. // 记录错误日志
  7665. dLog('anime')->error('保存剧本资产失败: ' . $e->getMessage(), [
  7666. 'script_id' => $script_id,
  7667. 'error' => $e->getMessage(),
  7668. 'trace' => $e->getTraceAsString()
  7669. ]);
  7670. // 统一使用 Utils::throwError 抛出错误
  7671. Utils::throwError('20003:保存剧本资产失败:' . $e->getMessage());
  7672. }
  7673. }
  7674. /**
  7675. * 根据入参创建或复用任务中心记录
  7676. *
  7677. * 以规范化入参计算 md5 并保存到任务中心 params 字段中用于验重:
  7678. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  7679. * 避免生成重复任务。
  7680. *
  7681. * @param int|string $uid
  7682. * @param int|string $cpid
  7683. * @param int|string $script_id
  7684. * @param mixed $products
  7685. * @param string $model
  7686. * @param string $ratio
  7687. * @param string $resolution
  7688. * @param mixed $auto_generate_images
  7689. * @return int 任务中心ID
  7690. */
  7691. private function createScriptProductTaskCenter($uid, $cpid, $script_id, $products, $model, $ratio, $resolution, $auto_generate_images) {
  7692. // 规范化 products(兼容 JSON 字符串和数组),保证 md5 稳定
  7693. if (is_string($products)) {
  7694. $decoded = json_decode($products, true);
  7695. if (json_last_error() === JSON_ERROR_NONE) {
  7696. $products = $decoded;
  7697. }
  7698. }
  7699. $params = [
  7700. 'script_id' => (int)$script_id,
  7701. 'products' => $products,
  7702. 'model' => $model,
  7703. 'ratio' => $ratio,
  7704. 'resolution' => $resolution,
  7705. 'auto_generate_images' => (bool)$auto_generate_images,
  7706. ];
  7707. $paramsMd5 = md5(json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  7708. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  7709. $existing = DB::table('mp_task_center')
  7710. ->where('uid', (int)$uid)
  7711. ->where('cpid', (int)$cpid)
  7712. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  7713. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  7714. ->where('params_md5', $paramsMd5)
  7715. ->orderBy('id', 'desc')
  7716. ->first();
  7717. if ($existing) {
  7718. dLog('anime')->info('复用已有任务中心记录,避免重复任务', [
  7719. 'script_id' => $script_id,
  7720. 'task_center_id' => $existing->id,
  7721. 'params_md5' => $paramsMd5,
  7722. ]);
  7723. return (int)$existing->id;
  7724. }
  7725. // 唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复,冲突时静默忽略
  7726. $now = date('Y-m-d H:i:s');
  7727. DB::table('mp_task_center')->insertOrIgnore([
  7728. 'uid' => (int)$uid,
  7729. 'cpid' => (int)$cpid,
  7730. 'task_type' => MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS,
  7731. 'title' => '剧本资产图片生成',
  7732. 'ref_task_id' => 0,
  7733. 'status' => MpTaskCenter::STATUS_PROCESSING,
  7734. 'result' => null,
  7735. 'error_message' => null,
  7736. 'prompt' => null,
  7737. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  7738. 'params_md5' => $paramsMd5,
  7739. 'created_at' => $now,
  7740. 'updated_at' => $now,
  7741. ]);
  7742. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  7743. $taskId = (int)DB::table('mp_task_center')
  7744. ->where('uid', (int)$uid)
  7745. ->where('cpid', (int)$cpid)
  7746. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  7747. ->where('params_md5', $paramsMd5)
  7748. ->orderBy('id', 'desc')
  7749. ->value('id');
  7750. dLog('anime')->info('创建任务中心记录', [
  7751. 'script_id' => $script_id,
  7752. 'task_center_id' => $taskId,
  7753. 'params_md5' => $paramsMd5,
  7754. ]);
  7755. return $taskId;
  7756. }
  7757. /**
  7758. * 任务结束时更新任务中心记录的状态和结果
  7759. *
  7760. * result 字段保存与 saveScriptProducts 接口返回给客户端一致的结果数据
  7761. * (普通数组返回为完整返回数组,SSE 轮询为 complete/timeout 事件载荷)。
  7762. *
  7763. * @param int|null $taskCenterId
  7764. * @param array $resultData 接口返回结果数组
  7765. * @param bool $timeout 是否超时未完成
  7766. */
  7767. private function finishScriptProductTask($taskCenterId, array $resultData, $timeout = false) {
  7768. if (!$taskCenterId) {
  7769. return;
  7770. }
  7771. $stats = $resultData['stats'] ?? [];
  7772. $successCount = (int)array_sum(array_column((array)$stats, 'success'));
  7773. $completedCount = (int)array_sum(array_column((array)$stats, 'completed'));
  7774. $failedCount = $completedCount - $successCount;
  7775. // 与接口返回给客户端的结果保持一致
  7776. $result = json_encode($resultData, JSON_UNESCAPED_UNICODE);
  7777. if ($timeout) {
  7778. $this->taskCenterService->updateTask((int)$taskCenterId, [
  7779. 'status' => MpTaskCenter::STATUS_FAILED,
  7780. 'result' => $result,
  7781. 'error_message' => '部分任务超时,请稍后查看结果',
  7782. ]);
  7783. return;
  7784. }
  7785. $this->taskCenterService->updateTask((int)$taskCenterId, [
  7786. 'status' => $failedCount > 0 ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  7787. 'result' => $result,
  7788. 'error_message' => $failedCount > 0 ? ('有 ' . $failedCount . ' 个资产生成失败') : null,
  7789. ]);
  7790. }
  7791. /**
  7792. * 批量为剧本资产生成图片
  7793. *
  7794. * @param array $data 请求参数
  7795. * @return \Generator 返回 SSE 流
  7796. */
  7797. public function batchGenerateProductImages($data) {
  7798. $script_id = getProp($data, 'script_id');
  7799. $type_folder_ids = getProp($data, 'type_folder_ids', []); // {1: 角色文件夹ID, 2: 场景文件夹ID, 3: 道具文件夹ID}
  7800. if (!$script_id) {
  7801. Utils::throwError('20003:请提供剧本ID');
  7802. }
  7803. // 验证剧本是否存在
  7804. $script = DB::table('mp_scripts')
  7805. ->where('id', $script_id)
  7806. ->where('is_deleted', 0)
  7807. ->first();
  7808. if (!$script) {
  7809. Utils::throwError('20003:剧本不存在');
  7810. }
  7811. $script_name = $script->script_name ?? 'script_' . $script_id;
  7812. // 获取需要生成图片的所有资产
  7813. $products = DB::table('mp_products')
  7814. ->whereIn('parent_id', array_values($type_folder_ids))
  7815. ->where('is_deleted', 0)
  7816. ->whereIn('type', [1, 2, 3]) // 只处理资产,不处理文件夹
  7817. ->get();
  7818. if ($products->isEmpty()) {
  7819. Utils::throwError('20003:没有找到需要生成图片的资产');
  7820. }
  7821. // 默认参数
  7822. $model = 'doubao-seedream-5-0-lite-260128';
  7823. $width = 1600;
  7824. $height = 2848;
  7825. // 开始为每个资产创建图片生成任务
  7826. $taskIds = [];
  7827. $productTaskMap = []; // 资产ID到任务ID的映射
  7828. foreach ($products as $product) {
  7829. if (empty($product->pic_prompt)) {
  7830. dLog('anime')->warning('资产没有提示词,跳过', ['product_id' => $product->id, 'product_name' => $product->product_name]);
  7831. continue;
  7832. }
  7833. try {
  7834. // 创建图片生成任务
  7835. $params = [
  7836. 'prompt' => $product->pic_prompt,
  7837. 'model' => $model,
  7838. 'ref_img_urls' => [],
  7839. 'width' => $width,
  7840. 'height' => $height
  7841. ];
  7842. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  7843. $task_id = $task->id;
  7844. if ($task_id) {
  7845. $taskIds[] = $task_id;
  7846. $productTaskMap[$product->id] = $task_id;
  7847. // 更新资产表的任务ID和状态
  7848. DB::table('mp_products')
  7849. ->where('id', $product->id)
  7850. ->update([
  7851. 'pic_task_id' => $task_id,
  7852. 'pic_task_status' => '生成中',
  7853. 'updated_at' => now()
  7854. ]);
  7855. dLog('anime')->info('创建资产图片生成任务', ['product_id' => $product->id, 'task_id' => $task_id]);
  7856. }
  7857. } catch (\Exception $e) {
  7858. dLog('anime')->error('创建资产图片生成任务失败', [
  7859. 'product_id' => $product->id,
  7860. 'error' => $e->getMessage()
  7861. ]);
  7862. // 标记为失败
  7863. DB::table('mp_products')
  7864. ->where('id', $product->id)
  7865. ->update([
  7866. 'pic_task_status' => '生成失败',
  7867. 'updated_at' => now()
  7868. ]);
  7869. }
  7870. }
  7871. if (empty($taskIds)) {
  7872. Utils::throwError('20003:没有成功创建任何图片生成任务');
  7873. }
  7874. // 返回 SSE 流
  7875. return $this->pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids);
  7876. }
  7877. /**
  7878. * 轮询资产图片生成任务状态(SSE流式返回)
  7879. * 只通过查询数据库获取任务状态,不主动调用API
  7880. *
  7881. * @param int $script_id 剧本ID
  7882. * @param string $script_name 剧本名称
  7883. * @param array $productTaskMap 资产ID到任务ID的映射
  7884. * @param array $type_folder_ids 类型文件夹ID映射
  7885. * @return \Generator
  7886. */
  7887. private function pollProductImageTasks($script_id, $script_name, $productTaskMap, $type_folder_ids, $taskCenterId = null) {
  7888. $startTime = time();
  7889. $timeout = 1800; // 30分钟超时
  7890. $pollInterval = 10; // 10秒轮询一次
  7891. $lastStatus = []; // 记录上次的状态,用于判断是否有变化
  7892. // 流一开始即返回 init 事件(saveScriptProducts 场景下携带任务中心ID)
  7893. if ($taskCenterId) {
  7894. $initResponse = [
  7895. 'type' => 'init',
  7896. 'script_id' => $script_id,
  7897. 'script_name' => $script_name,
  7898. 'timestamp' => date('Y-m-d H:i:s'),
  7899. 'task_center_id' => (int)$taskCenterId,
  7900. ];
  7901. yield "data: " . json_encode($initResponse, JSON_UNESCAPED_UNICODE) . "\n\n";
  7902. }
  7903. // 定义类型名称映射
  7904. $typeNames = [
  7905. 1 => 'roles', // 角色
  7906. 2 => 'scenes', // 场景
  7907. 3 => 'props' // 道具
  7908. ];
  7909. while (time() - $startTime < $timeout) {
  7910. sleep($pollInterval);
  7911. // 从 mp_script_product_mappings 表获取该剧本的所有资产ID
  7912. $mappings = DB::table('mp_script_product_mappings')
  7913. ->where('script_id', $script_id)
  7914. ->pluck('product_id')
  7915. ->unique()
  7916. ->toArray();
  7917. if (empty($mappings)) {
  7918. dLog('anime')->warning('该剧本没有关联的资产', [
  7919. 'script_id' => $script_id,
  7920. 'script_name' => $script_name
  7921. ]);
  7922. break;
  7923. }
  7924. // 查询所有资产的当前状态
  7925. $products = DB::table('mp_products')
  7926. ->whereIn('id', $mappings)
  7927. ->where('is_deleted', 0)
  7928. ->get();
  7929. // 统计各类型的状态(使用类型名称作为键名)
  7930. $stats = [
  7931. 'character' => ['total' => 0, 'success' => 0, 'completed' => 0], // 角色
  7932. 'scene' => ['total' => 0, 'success' => 0, 'completed' => 0], // 场景
  7933. 'prop' => ['total' => 0, 'success' => 0, 'completed' => 0], // 道具
  7934. ];
  7935. $allCompleted = true;
  7936. $hasStatusChange = false;
  7937. foreach ($products as $product) {
  7938. $type = $product->product;
  7939. $typeName = $typeNames[$type] ?? 'unknown'; // 使用 unknown 作为未知类型
  7940. // 如果类型名称不在 stats 中,初始化
  7941. if (!isset($stats[$typeName])) {
  7942. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  7943. }
  7944. $stats[$typeName]['total']++;
  7945. $task_id = $product->pic_task_id;
  7946. $currentStatus = $product->pic_task_status;
  7947. // 检查状态是否有变化
  7948. if (!isset($lastStatus[$product->id]) || $lastStatus[$product->id] !== $currentStatus) {
  7949. $hasStatusChange = true;
  7950. $lastStatus[$product->id] = $currentStatus;
  7951. }
  7952. // 如果是生成中,查询任务表状态
  7953. if ($currentStatus === '生成中' && $task_id) {
  7954. // 只查询数据库,不调用API
  7955. $task = DB::table('mp_generate_pic_tasks')
  7956. ->where('id', $task_id)
  7957. ->first();
  7958. if ($task) {
  7959. // 检查任务状态
  7960. if ($task->status === 'success' && $task->result_url) {
  7961. // 解析图片URL
  7962. $result_urls = $task->result_url;
  7963. if (is_string($result_urls)) {
  7964. $result_urls = json_decode($result_urls, true);
  7965. }
  7966. $img_url = is_array($result_urls) ? $result_urls[0] : $task->result_url;
  7967. // 更新资产表状态
  7968. DB::table('mp_products')
  7969. ->where('id', $product->id)
  7970. ->update([
  7971. 'pic_task_status' => '生成成功',
  7972. 'url' => $img_url,
  7973. 'updated_at' => now()
  7974. ]);
  7975. $stats[$typeName]['success']++;
  7976. $stats[$typeName]['completed']++;
  7977. $hasStatusChange = true;
  7978. dLog('anime')->info('资产图片生成成功', [
  7979. 'product_id' => $product->id,
  7980. 'task_id' => $task_id,
  7981. 'img_url' => $img_url
  7982. ]);
  7983. } elseif ($task->status === 'failed') {
  7984. // 更新资产表状态
  7985. DB::table('mp_products')
  7986. ->where('id', $product->id)
  7987. ->update([
  7988. 'pic_task_status' => '生成失败',
  7989. 'updated_at' => now()
  7990. ]);
  7991. $stats[$typeName]['completed']++;
  7992. $hasStatusChange = true;
  7993. dLog('anime')->warning('资产图片生成失败', [
  7994. 'product_id' => $product->id,
  7995. 'task_id' => $task_id,
  7996. 'error' => $task->error_message ?? '未知错误'
  7997. ]);
  7998. } else {
  7999. // 任务还在处理中
  8000. $allCompleted = false;
  8001. }
  8002. } else {
  8003. // 任务不存在,标记为失败
  8004. DB::table('mp_products')
  8005. ->where('id', $product->id)
  8006. ->update([
  8007. 'pic_task_status' => '生成失败',
  8008. 'updated_at' => now()
  8009. ]);
  8010. $stats[$type]['completed']++;
  8011. $hasStatusChange = true;
  8012. dLog('anime')->error('图片生成任务不存在', [
  8013. 'product_id' => $product->id,
  8014. 'task_id' => $task_id
  8015. ]);
  8016. }
  8017. } elseif ($currentStatus === '生成成功') {
  8018. $stats[$typeName]['success']++;
  8019. $stats[$typeName]['completed']++;
  8020. } elseif ($currentStatus === '生成失败') {
  8021. $stats[$typeName]['completed']++;
  8022. } else {
  8023. // 其他状态也认为未完成
  8024. $allCompleted = false;
  8025. }
  8026. }
  8027. // 移除没有数据的类型(total=0)
  8028. foreach ($stats as $typeName => $stat) {
  8029. if ($stat['total'] === 0) {
  8030. unset($stats[$typeName]);
  8031. }
  8032. }
  8033. // 如果有状态变化,发送 SSE 更新
  8034. if ($hasStatusChange) {
  8035. $eventType = $allCompleted ? 'complete' : 'update';
  8036. $response = [
  8037. 'type' => $eventType,
  8038. 'script_id' => $script_id,
  8039. 'script_name' => $script_name,
  8040. 'stats' => $stats,
  8041. 'timestamp' => date('Y-m-d H:i:s')
  8042. ];
  8043. if ($taskCenterId) {
  8044. $response['task_center_id'] = $taskCenterId;
  8045. }
  8046. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  8047. dLog('anime')->info('SSE更新', [
  8048. 'event_type' => $eventType,
  8049. 'script_id' => $script_id,
  8050. 'script_name' => $script_name,
  8051. 'stats' => $stats
  8052. ]);
  8053. if ($allCompleted) {
  8054. dLog('anime')->info('所有资产图片生成任务已完成', [
  8055. 'script_id' => $script_id,
  8056. 'script_name' => $script_name,
  8057. 'stats' => $stats
  8058. ]);
  8059. // 全部任务完成,更新任务中心状态和结果
  8060. $this->finishScriptProductTask($taskCenterId, $response);
  8061. break;
  8062. }
  8063. }
  8064. }
  8065. // 超时处理
  8066. if (time() - $startTime >= $timeout && !$allCompleted) {
  8067. $response = [
  8068. 'type' => 'timeout',
  8069. 'message' => '部分任务超时,请稍后查看结果',
  8070. 'script_id' => $script_id,
  8071. 'script_name' => $script_name,
  8072. 'timestamp' => date('Y-m-d H:i:s')
  8073. ];
  8074. if ($taskCenterId) {
  8075. $response['task_center_id'] = $taskCenterId;
  8076. }
  8077. yield "data: " . json_encode($response, JSON_UNESCAPED_UNICODE) . "\n\n";
  8078. dLog('anime')->warning('资产图片生成任务超时', [
  8079. 'script_id' => $script_id,
  8080. 'script_name' => $script_name,
  8081. 'timeout' => $timeout
  8082. ]);
  8083. // 超时未完成,更新任务中心状态和结果
  8084. $this->finishScriptProductTask($taskCenterId, $response, true);
  8085. }
  8086. }
  8087. /**
  8088. * 定时任务:检查产品图片生成任务状态并更新产品记录
  8089. * 扫描 mp_products 中 pic_task_id 非空且 pic_task_status 为生成中的记录,
  8090. * 通过 pic_task_id 查询 mp_generate_pic_tasks 获取生成结果,按结果更新状态
  8091. *
  8092. * @return array ['total' => 总数, 'success' => 成功数, 'failed' => 失败数, 'pending' => 待处理数]
  8093. */
  8094. public function checkProductPicTasks() {
  8095. // 查询所有生成中的产品图片任务
  8096. $products = DB::table('mp_products')
  8097. ->whereNotNull('pic_task_id')
  8098. ->where('pic_task_status', '生成中')
  8099. ->where('is_deleted', 0)
  8100. ->get();
  8101. $stats = [
  8102. 'total' => $products->count(),
  8103. 'success' => 0,
  8104. 'failed' => 0,
  8105. 'pending' => 0,
  8106. ];
  8107. foreach ($products as $product) {
  8108. try {
  8109. $task_id = $product->pic_task_id;
  8110. // 通过 pic_task_id 查询图片生成任务结果
  8111. $task = DB::table('mp_generate_pic_tasks')
  8112. ->where('id', $task_id)
  8113. ->first();
  8114. if ($task) {
  8115. if ($task->status === 'success' && $task->result_url) {
  8116. // 解析图片URL
  8117. $result_urls = $task->result_url;
  8118. if (is_string($result_urls)) {
  8119. $result_urls = json_decode($result_urls, true);
  8120. }
  8121. $img_url = is_array($result_urls) ? ($result_urls[0] ?? $task->result_url) : $task->result_url;
  8122. // 更新资产表状态
  8123. DB::table('mp_products')
  8124. ->where('id', $product->id)
  8125. ->update([
  8126. 'pic_task_status' => '生成成功',
  8127. 'url' => $img_url,
  8128. 'updated_at' => now()
  8129. ]);
  8130. $stats['success']++;
  8131. dLog('anime')->info('资产图片生成成功', [
  8132. 'product_id' => $product->id,
  8133. 'task_id' => $task_id,
  8134. 'img_url' => $img_url
  8135. ]);
  8136. } elseif ($task->status === 'failed') {
  8137. // 更新资产表状态
  8138. DB::table('mp_products')
  8139. ->where('id', $product->id)
  8140. ->update([
  8141. 'pic_task_status' => '生成失败',
  8142. 'updated_at' => now()
  8143. ]);
  8144. $stats['failed']++;
  8145. dLog('anime')->warning('资产图片生成失败', [
  8146. 'product_id' => $product->id,
  8147. 'task_id' => $task_id,
  8148. 'error' => $task->error_message ?? '未知错误'
  8149. ]);
  8150. } else {
  8151. // 任务还在处理中
  8152. $stats['pending']++;
  8153. }
  8154. } else {
  8155. // 任务不存在,标记为失败
  8156. DB::table('mp_products')
  8157. ->where('id', $product->id)
  8158. ->update([
  8159. 'pic_task_status' => '生成失败',
  8160. 'updated_at' => now()
  8161. ]);
  8162. $stats['failed']++;
  8163. dLog('anime')->error('图片生成任务不存在', [
  8164. 'product_id' => $product->id,
  8165. 'task_id' => $task_id
  8166. ]);
  8167. }
  8168. } catch (\Exception $e) {
  8169. dLog('anime')->error('检查产品图片生成任务异常', [
  8170. 'product_id' => $product->id,
  8171. 'task_id' => $product->pic_task_id ?? null,
  8172. 'error' => $e->getMessage()
  8173. ]);
  8174. }
  8175. }
  8176. return $stats;
  8177. }
  8178. /**
  8179. * 定时任务:检查任务中心中 saveScriptProducts 类型的任务是否已完成
  8180. *
  8181. * 当保存剧本资产的 SSE 连接中断等原因导致任务中心记录未及时更新时,
  8182. * 通过关联资产的图片生成状态兜底判断任务是否全部完成;
  8183. * 全部完成后更新任务中心的状态和结果(result 与 saveScriptProducts 接口返回保持一致)。
  8184. *
  8185. * @return int 更新的任务中心记录数
  8186. */
  8187. public function checkSaveScriptProductTaskCenters() {
  8188. $updated = 0;
  8189. // 只扫描尚未结束的 saveScriptProducts 任务
  8190. $tasks = DB::table('mp_task_center')
  8191. ->where('task_type', MpTaskCenter::TYPE_SAVE_SCRIPT_PRODUCTS)
  8192. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  8193. ->orderBy('id', 'desc')
  8194. ->limit(500)
  8195. ->get();
  8196. // 与 pollProductImageTasks 保持一致的类型名称映射
  8197. $typeNames = [
  8198. 1 => 'roles', // 角色
  8199. 2 => 'scenes', // 场景
  8200. 3 => 'props', // 道具
  8201. ];
  8202. foreach ($tasks as $task) {
  8203. try {
  8204. $taskParams = json_decode((string)$task->params, true);
  8205. $script_id = is_array($taskParams) ? (int)($taskParams['script_id'] ?? 0) : 0;
  8206. if (!$script_id) {
  8207. dLog('command')->warning('saveScriptProducts任务缺少script_id,跳过', [
  8208. 'task_center_id' => $task->id,
  8209. ]);
  8210. continue;
  8211. }
  8212. // 获取该剧本关联的全部资产ID
  8213. $productIds = DB::table('mp_script_product_mappings')
  8214. ->where('script_id', $script_id)
  8215. ->pluck('product_id')
  8216. ->unique()
  8217. ->toArray();
  8218. if (empty($productIds)) {
  8219. // 剧本没有关联资产,不视为完成,等待下一次检查
  8220. continue;
  8221. }
  8222. $products = DB::table('mp_products')
  8223. ->whereIn('id', $productIds)
  8224. ->where('is_deleted', 0)
  8225. ->get();
  8226. $stats = [];
  8227. $allCompleted = true;
  8228. foreach ($products as $product) {
  8229. $typeName = $typeNames[$product->product] ?? 'unknown';
  8230. if (!isset($stats[$typeName])) {
  8231. $stats[$typeName] = ['total' => 0, 'success' => 0, 'completed' => 0];
  8232. }
  8233. $stats[$typeName]['total']++;
  8234. if ($product->pic_task_status === '生成成功') {
  8235. $stats[$typeName]['success']++;
  8236. $stats[$typeName]['completed']++;
  8237. } elseif ($product->pic_task_status === '生成失败') {
  8238. $stats[$typeName]['completed']++;
  8239. } else {
  8240. // 仍有资产在生成中或未生成,任务未完成
  8241. $allCompleted = false;
  8242. }
  8243. }
  8244. if (!$allCompleted) {
  8245. continue;
  8246. }
  8247. // 全部完成,更新任务中心状态和结果(与接口返回结果保持一致)
  8248. $script = DB::table('mp_scripts')
  8249. ->where('id', $script_id)
  8250. ->where('is_deleted', 0)
  8251. ->first();
  8252. $script_name = $script->script_name ?? 'script_' . $script_id;
  8253. $this->finishScriptProductTask($task->id, [
  8254. 'type' => 'complete',
  8255. 'script_id' => $script_id,
  8256. 'script_name' => $script_name,
  8257. 'stats' => $stats,
  8258. 'timestamp' => date('Y-m-d H:i:s'),
  8259. 'task_center_id' => (int)$task->id,
  8260. ]);
  8261. $updated++;
  8262. dLog('command')->info('saveScriptProducts任务已完成,更新任务中心', [
  8263. 'task_center_id' => $task->id,
  8264. 'script_id' => $script_id,
  8265. 'stats' => $stats,
  8266. ]);
  8267. } catch (\Exception $e) {
  8268. dLog('command')->error('检查saveScriptProducts任务中心状态异常', [
  8269. 'task_center_id' => $task->id,
  8270. 'error' => $e->getMessage(),
  8271. ]);
  8272. }
  8273. }
  8274. return $updated;
  8275. }
  8276. /**
  8277. * 获取剧本关联的资产列表
  8278. * @param array $data 请求参数
  8279. * @return array
  8280. */
  8281. public function getScriptProducts($data) {
  8282. $uid = Site::getUid();
  8283. $cpid = Site::getCpid();
  8284. $script_id = getProp($data, 'script_id');
  8285. $episode_number = getProp($data, 'episode_number');
  8286. if (!$script_id) {
  8287. Utils::throwError('20003:请提供剧本ID');
  8288. }
  8289. // 验证剧本是否存在
  8290. $script = DB::table('mp_scripts')
  8291. ->where('id', $script_id)
  8292. ->where('is_deleted', 0)
  8293. ->first();
  8294. if (!$script) {
  8295. Utils::throwError('20003:剧本不存在');
  8296. }
  8297. // 联表查询资产信息
  8298. $query = DB::table('mp_script_product_mappings as mapping')
  8299. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8300. ->where('mapping.script_id', $script_id)
  8301. ->where('product.cpid', $cpid)
  8302. ->where('product.is_deleted', 0);
  8303. // 如果提供了 episode_number,则过滤指定集数
  8304. if ($episode_number !== null && $episode_number !== '') {
  8305. $query->where('mapping.episode_number', $episode_number);
  8306. }
  8307. $mappings = $query->select(
  8308. 'mapping.script_id',
  8309. 'mapping.product_id',
  8310. 'mapping.episode_number',
  8311. 'product.product_name',
  8312. 'product.type',
  8313. 'product.product',
  8314. 'product.pic_prompt',
  8315. 'product.url',
  8316. 'product.pic_task_id',
  8317. 'product.pic_task_status',
  8318. 'product.three_view_image_url',
  8319. 'mapping.created_at'
  8320. )
  8321. ->orderBy('mapping.product_id', 'asc')
  8322. ->orderBy('mapping.episode_number', 'asc')
  8323. ->get();
  8324. // 按 product_id 分组,合并 episode_number
  8325. $productMap = [];
  8326. foreach ($mappings as $item) {
  8327. $product_id = $item->product_id;
  8328. if (!isset($productMap[$product_id])) {
  8329. $productMap[$product_id] = [
  8330. 'product_id' => $product_id,
  8331. 'product_name' => $item->product_name,
  8332. 'type' => (int)$item->type,
  8333. 'product' => (int)$item->product,
  8334. 'pic_prompt' => $item->pic_prompt,
  8335. 'url' => $item->url,
  8336. 'pic_task_id' => $item->pic_task_id,
  8337. 'pic_task_status' => $item->pic_task_status,
  8338. 'episode_numbers' => [],
  8339. 'created_at' => $item->created_at,
  8340. ];
  8341. }
  8342. // 添加 episode_number(去重)
  8343. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8344. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8345. }
  8346. }
  8347. // 按类型分组
  8348. $roles = []; // type=1 角色/主体
  8349. $scenes = []; // type=2 场景
  8350. $props = []; // type=3 道具
  8351. foreach ($productMap as $product) {
  8352. // 将 episode_numbers 数组转换为逗号分隔的字符串
  8353. $episodeNumbersStr = implode(',', $product['episode_numbers']);
  8354. // 构造返回数据
  8355. $productData = [
  8356. 'product_id' => $product['product_id'],
  8357. 'product_name' => $product['product_name'],
  8358. 'product' => $product['product'],
  8359. 'pic_prompt' => $product['pic_prompt'],
  8360. 'url' => $product['url'],
  8361. 'pic_task_id' => $product['pic_task_id'],
  8362. 'pic_task_status' => $product['pic_task_status'],
  8363. 'episode_numbers' => $episodeNumbersStr,
  8364. 'created_at' => $product['created_at'],
  8365. ];
  8366. // 根据 type 分类(注意:type 字段表示资产类型,不是文件夹)
  8367. // 根据 product 字段分类(1=角色, 2=场景, 3=道具)
  8368. switch ($product['product']) {
  8369. case 1:
  8370. $roles[] = $productData;
  8371. break;
  8372. case 2:
  8373. $scenes[] = $productData;
  8374. break;
  8375. case 3:
  8376. $props[] = $productData;
  8377. break;
  8378. }
  8379. }
  8380. return [
  8381. 'script_id' => $script_id,
  8382. 'script_name' => $script->script_name ?? '',
  8383. 'roles' => $roles, // 主体
  8384. 'scenes' => $scenes, // 场景
  8385. 'props' => $props, // 道具
  8386. ];
  8387. }
  8388. /**
  8389. * 处理act_content中的{}标记,替换为product_name(图+序号)格式,并收集参考图片
  8390. * @param string $actContent 原始内容
  8391. * @param array $products 产品数组(包含product_name和url)
  8392. * @return array ['content' => 处理后的内容, 'reference_images' => 参考图片数组]
  8393. */
  8394. public function processActContentWithProducts($actContent, $products) {
  8395. if (empty($actContent) || empty($products)) {
  8396. return [
  8397. 'content' => $actContent,
  8398. 'reference_images' => []
  8399. ];
  8400. }
  8401. // 构建产品名称到产品信息的映射
  8402. $product_dict = [];
  8403. foreach ($products as $product) {
  8404. $product_name = getProp($product, 'product_name');
  8405. if ($product_name) {
  8406. $product_dict[$product_name] = [
  8407. // 优先使用三视图图片作为素材/参考图,否则使用原图 url
  8408. 'url' => getProp($product, 'three_view_image_url') ?: getProp($product, 'url'),
  8409. 'voice_prompt' => getProp($product, 'voice_prompt')
  8410. ];
  8411. }
  8412. }
  8413. // 第一步:查找内容中所有 {产品名称} 格式的标记(按出现顺序,去重)
  8414. preg_match_all('/\{([^}]+)\}/u', $actContent, $matches);
  8415. $reference_images = [];
  8416. $product_index_map = []; // 产品名称 => 图片序号的映射
  8417. $voice_prompts = []; // 存储需要添加到开头的voice_prompt信息
  8418. $narrator_voice_prompt = ''; // 单独存储旁白的voice_prompt
  8419. $current_index = 1;
  8420. if (!empty($matches[1])) {
  8421. // 按照在内容中第一次出现的顺序,为每个产品分配序号
  8422. $seen_products = []; // 用于去重
  8423. foreach ($matches[1] as $product_name) {
  8424. // 跳过已处理的产品
  8425. if (isset($seen_products[$product_name])) {
  8426. continue;
  8427. }
  8428. $seen_products[$product_name] = true;
  8429. // 检查产品是否在字典中
  8430. if (isset($product_dict[$product_name])) {
  8431. $url = $product_dict[$product_name]['url'];
  8432. $voice_prompt = $product_dict[$product_name]['voice_prompt'];
  8433. // 处理voice_prompt(旁白不在这里处理,旁白是公共的在后面单独处理)
  8434. if (!empty($voice_prompt) && $product_name !== '旁白') {
  8435. $voice_prompts[] = $product_name . ':' . $voice_prompt . "\n";
  8436. }
  8437. // 只有URL非空才分配序号和添加到参考图片
  8438. if (!empty($url)) {
  8439. // 检查URL是否已经在reference_images中(去重)
  8440. if (!in_array($url, $reference_images)) {
  8441. $reference_images[] = $url;
  8442. $product_index_map[$product_name] = $current_index;
  8443. $current_index++;
  8444. } else {
  8445. // URL重复,找到已有的序号
  8446. $existing_index = array_search($url, $reference_images) + 1;
  8447. $product_index_map[$product_name] = $existing_index;
  8448. }
  8449. } else {
  8450. // URL为空,不分配序号(后续直接去掉{})
  8451. $product_index_map[$product_name] = 0;
  8452. }
  8453. } else {
  8454. // 产品不在字典中,不分配序号
  8455. $product_index_map[$product_name] = 0;
  8456. }
  8457. }
  8458. }
  8459. // 第二步:替换内容中的 {产品名称}
  8460. $processedContent = $actContent;
  8461. foreach ($product_index_map as $product_name => $index) {
  8462. $escaped_name = preg_quote($product_name, '/');
  8463. if ($index > 0) {
  8464. // 有图片,替换为:产品名称(图X)
  8465. $replacement = $product_name . '<图片' . $index . '>';
  8466. } else {
  8467. // 无图片,只保留产品名称
  8468. $replacement = $product_name;
  8469. }
  8470. // 替换所有 {产品名称} 为处理后的格式
  8471. $processedContent = preg_replace('/\{' . $escaped_name . '\}/u', $replacement, $processedContent);
  8472. }
  8473. // 第三步:单独处理旁白的voice_prompt(旁白是公共的,不依赖product_dict)
  8474. foreach ($products as $product) {
  8475. $product_name = getProp($product, 'product_name');
  8476. $voice_prompt = getProp($product, 'voice_prompt');
  8477. if ($product_name === '旁白' && !empty($voice_prompt)) {
  8478. $narrator_voice_prompt = $product_name . ':' . $voice_prompt . "\n";
  8479. break; // 找到旁白后退出循环
  8480. }
  8481. }
  8482. // 第四步:将voice_prompt信息添加到内容最前面
  8483. $voice_prompt_prefix = '';
  8484. if (!empty($voice_prompts)) {
  8485. $voice_prompt_prefix .= implode('', $voice_prompts);
  8486. }
  8487. // 旁白的voice_prompt放在最后
  8488. if (!empty($narrator_voice_prompt)) {
  8489. $voice_prompt_prefix .= $narrator_voice_prompt;
  8490. }
  8491. // 如果有voice_prompt信息,添加到内容开头
  8492. if (!empty($voice_prompt_prefix)) {
  8493. $processedContent = "人物音色:\n" . $voice_prompt_prefix . "\n" . $processedContent;
  8494. }
  8495. return [
  8496. 'content' => $processedContent,
  8497. 'reference_images' => $reference_images
  8498. ];
  8499. }
  8500. public function saveActVideoGenerateParams($data) {
  8501. $episode_id = getProp($data, 'episode_id');
  8502. $model = getProp($data, 'video_model');
  8503. $valid_models = DB::table('mp_video_models')->where('ace_mode', 1)->select('model')->pluck('model')->toArray();
  8504. if (!in_array($model, $valid_models)) {
  8505. Utils::throwError('20003:该模型不可用');
  8506. }
  8507. // 验证模型是否在可用模型表中
  8508. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8509. Utils::throwError('20003:该模型已不可用,请更换!');
  8510. }
  8511. $video_resolution = getProp($data, 'video_resolution', '720p');
  8512. $ratio = getProp($data, 'ratio');
  8513. if (!$ratio) $ratio = '9:16';
  8514. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first(['anime_id']);
  8515. if (!$episode) {
  8516. Utils::throwError('20003:分集不存在');
  8517. }
  8518. dLog('anime')->info('保存分集视频参数', $data);
  8519. try {
  8520. DB::beginTransaction();
  8521. $result = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8522. 'video_model' => $model,
  8523. 'video_resolution' => $video_resolution,
  8524. 'ratio' => $ratio,
  8525. 'updated_at' => date('Y-m-d H:i:s')
  8526. ]);
  8527. if ($result === false) {
  8528. Utils::throwError('20003:分集视频参数保存失败');
  8529. }
  8530. // 同步更新mp_animes表
  8531. $anime_result = DB::table('mp_animes')->where('id', $episode->anime_id)->update([
  8532. 'video_model' => $model,
  8533. 'video_resolution' => $video_resolution,
  8534. 'video_ratio' => $ratio,
  8535. 'updated_at' => date('Y-m-d H:i:s')
  8536. ]);
  8537. if ($anime_result === false) {
  8538. Utils::throwError('20003:动漫视频参数保存失败');
  8539. }
  8540. } catch (\Exception $e) {
  8541. DB::rollBack();
  8542. Utils::throwError('20003:'.$e->getMessage());
  8543. }
  8544. DB::commit();
  8545. return $result;
  8546. }
  8547. public function confirmActs($data) {
  8548. $episode_id = getProp($data, 'episode_id');
  8549. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  8550. if (!$episode) {
  8551. Utils::throwError('20003:分集不存在');
  8552. }
  8553. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  8554. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  8555. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  8556. // 确认前校验并等待角色、场景、道具图片全部生成(参照 episodePicsInfo 更新与监控逻辑),未全部生成不得继续后续逻辑
  8557. $this->waitForEpisodeAssetsImagesReady($episode_id, $roles, $scenes, $props);
  8558. // 获取所有片段数据
  8559. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8560. // 收集所有资产名称(角色、场景、道具)
  8561. $product_names = [];
  8562. // 收集角色名称
  8563. foreach ($roles as $role) {
  8564. $role_name = getProp($role, 'role');
  8565. if ($role_name && $role_name != '旁白') {
  8566. $product_names[] = $role_name;
  8567. }
  8568. }
  8569. // 收集场景名称
  8570. foreach ($scenes as $scene) {
  8571. $scene_name = getProp($scene, 'scene');
  8572. if ($scene_name) {
  8573. $product_names[] = $scene_name;
  8574. }
  8575. }
  8576. // 收集道具名称
  8577. foreach ($props as $prop) {
  8578. $prop_name = getProp($prop, 'prop');
  8579. if ($prop_name) {
  8580. $product_names[] = $prop_name;
  8581. }
  8582. }
  8583. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  8584. $product_names = array_unique($product_names);
  8585. usort($product_names, function($a, $b) {
  8586. return mb_strlen($b) - mb_strlen($a);
  8587. });
  8588. try {
  8589. DB::beginTransaction();
  8590. // 处理每个片段
  8591. foreach ($acts as $act) {
  8592. $act_content = getProp($act, 'act_content');
  8593. if (!$act_content) continue;
  8594. $processed_content = $act_content;
  8595. // 统一替换所有资产名称为 {资产名} 格式
  8596. // 使用占位符避免嵌套替换问题
  8597. $placeholder_map = [];
  8598. $placeholder_index = 0;
  8599. foreach ($product_names as $product_name) {
  8600. // 转义特殊字符
  8601. $escaped_product = preg_quote($product_name, '/');
  8602. // 检查是否匹配且未被 {} 包裹
  8603. $processed_content = preg_replace_callback(
  8604. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  8605. function($matches) use (&$placeholder_map, &$placeholder_index) {
  8606. // 使用唯一占位符
  8607. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  8608. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  8609. $placeholder_index++;
  8610. return $placeholder;
  8611. },
  8612. $processed_content
  8613. );
  8614. }
  8615. // 将所有占位符替换回实际内容
  8616. foreach ($placeholder_map as $placeholder => $replacement) {
  8617. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  8618. }
  8619. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  8620. $shot_counter = 0;
  8621. $processed_content = preg_replace_callback(
  8622. '/【(?:镜头|分镜)(\d+)】/u',
  8623. function($matches) use (&$shot_counter) {
  8624. $shot_counter++;
  8625. return '【镜头' . $shot_counter . '】';
  8626. },
  8627. $processed_content
  8628. );
  8629. // 更新数据库
  8630. $boolen = DB::table('mp_episode_segments')
  8631. ->where('id', $act->id)
  8632. ->update([
  8633. 'act_show_content' => $processed_content,
  8634. 'updated_at' => date('Y-m-d H:i:s')
  8635. ]);
  8636. if (!$boolen) {
  8637. Utils::throwError('20003:片段处理失败');
  8638. }
  8639. }
  8640. }catch (\Exception $e) {
  8641. DB::rollBack();
  8642. Utils::throwError('20003:'.$e->getMessage());
  8643. }
  8644. $boolen1 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8645. 'is_generated' => 1,
  8646. 'updated_at' => date('Y-m-d H:i:s')
  8647. ]);
  8648. if (!$boolen1) {
  8649. DB::rollBack();
  8650. Utils::throwError('20003:分集处理失败!');
  8651. }
  8652. DB::commit();
  8653. // 重新查询更新后的片段数据
  8654. $acts = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->get();
  8655. // 合并角色、场景、道具和extra_products作为products,统一字段名为product_name
  8656. // extra_products优先级更高,会覆盖同名的roles、scenes和props
  8657. $products = [];
  8658. // 先处理角色数组
  8659. foreach ($roles as $role) {
  8660. $product = $role;
  8661. // 将role字段重命名为product_name
  8662. if (isset($product['role'])) {
  8663. $product['product_name'] = $product['role'];
  8664. unset($product['role']);
  8665. $product['product'] = 1; // 标记类型为角色
  8666. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8667. }
  8668. }
  8669. // 处理场景数组
  8670. foreach ($scenes as $scene) {
  8671. $product = $scene;
  8672. // 将scene字段重命名为product_name
  8673. if (isset($product['scene'])) {
  8674. $product['product_name'] = $product['scene'];
  8675. unset($product['scene']);
  8676. $product['product'] = 2; // 标记类型为场景
  8677. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8678. }
  8679. }
  8680. // 处理道具数组(逻辑与场景一致)
  8681. foreach ($props as $prop) {
  8682. $product = $prop;
  8683. // 将prop字段重命名为product_name
  8684. if (isset($product['prop'])) {
  8685. $product['product_name'] = $product['prop'];
  8686. unset($product['prop']);
  8687. $product['product'] = 3; // 标记类型为道具
  8688. $products[$product['product_name']] = $product; // 使用product_name作为key便于后续覆盖
  8689. }
  8690. }
  8691. // extra_products优先级更高,直接覆盖同名的roles和scenes
  8692. $extra_products = json_decode(getProp($episode, 'extra_products', '[]'), true) ?: [];
  8693. foreach ($extra_products as $extra_product) {
  8694. $product_name = getProp($extra_product, 'product_name');
  8695. if ($product_name) {
  8696. $products[$product_name] = $extra_product; // 覆盖同名数据
  8697. }
  8698. }
  8699. // 兼容返回 three_view_image_url 字段(旧数据可能没有该键,统一补空值)
  8700. foreach ($products as &$product) {
  8701. if (!isset($product['three_view_image_url'])) {
  8702. $product['three_view_image_url'] = '';
  8703. }
  8704. }
  8705. unset($product);
  8706. // 重新索引数组(去除key)
  8707. $products = array_values($products);
  8708. // 构建返回的acts数组
  8709. $return_acts = [];
  8710. foreach ($acts as $act) {
  8711. $return_acts[] = [
  8712. 'act_id' => getProp($act, 'id'),
  8713. 'act_number' => getProp($act, 'act_number'),
  8714. 'act_duration' => getProp($act, 'video_duration') ? getProp($act, 'video_duration') : getProp($act, 'act_duration'),
  8715. 'act_show_content' => getProp($act, 'act_show_content'),
  8716. 'video_url' => getProp($act, 'video_url'),
  8717. 'video_duration' => getProp($act, 'video_duration'),
  8718. 'video_time_point_start' => getProp($act, 'video_time_point_start'),
  8719. 'video_time_point_end' => getProp($act, 'video_time_point_end'),
  8720. ];
  8721. }
  8722. return [
  8723. 'anime_id' => getProp($episode, 'anime_id'),
  8724. 'episode_id' => $episode_id,
  8725. 'title' => getProp($episode, 'title'),
  8726. 'episode_number' => getProp($episode, 'episode_number'),
  8727. 'is_generated' => getProp($episode, 'is_generated'),
  8728. 'video_params' => [
  8729. 'video_model' => getProp($episode, 'video_model'),
  8730. 'video_resolution' => getProp($episode, 'video_resolution'),
  8731. 'ratio' => getProp($episode, 'ratio'),
  8732. ],
  8733. 'products' => $products,
  8734. 'acts' => $return_acts
  8735. ];
  8736. }
  8737. /**
  8738. * 参照 episodePicsInfo 的更新与监控逻辑:
  8739. * 每5秒查询一次角色/场景/道具的图片任务状态,任务成功后将图片URL回填到对应资产并写回分集表。
  8740. * 所有需要图片的资产均已生成(url 非空)才返回;最多等待1分钟,仍有图片未生成则直接报错。
  8741. */
  8742. private function waitForEpisodeAssetsImagesReady($episode_id, &$roles, &$scenes, &$props) {
  8743. $pollInterval = 5; // 每5秒查询一次
  8744. $maxWaitSeconds = 60; // 最多持续1分钟
  8745. $startTime = time();
  8746. while (true) {
  8747. // 从数据库读取最新数据,兼容后台 Anime:checkImgUrl 等任务对角色/场景/道具图片URL的更新
  8748. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  8749. if (!$episode) {
  8750. Utils::throwError('20003:分集不存在');
  8751. }
  8752. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  8753. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  8754. $props = json_decode(getProp($episode, 'props'), true) ?: [];
  8755. $updated = false;
  8756. $waitingAssets = []; // 任务仍在处理中,可等待后续轮询
  8757. $missingAssets = []; // 无任务或任务已失败/不存在,无法通过等待自动恢复
  8758. $this->refreshEpisodeAssetsImageTasks($roles, 'role', '旁白', $waitingAssets, $missingAssets, $updated);
  8759. $this->refreshEpisodeAssetsImageTasks($scenes, 'scene', '', $waitingAssets, $missingAssets, $updated);
  8760. $this->refreshEpisodeAssetsImageTasks($props, 'prop', '', $waitingAssets, $missingAssets, $updated);
  8761. // 有图片任务结果更新时写回分集表
  8762. if ($updated) {
  8763. DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8764. 'roles' => json_encode($roles, JSON_UNESCAPED_UNICODE),
  8765. 'scenes' => json_encode($scenes, JSON_UNESCAPED_UNICODE),
  8766. 'props' => json_encode($props, JSON_UNESCAPED_UNICODE),
  8767. 'updated_at' => date('Y-m-d H:i:s')
  8768. ]);
  8769. }
  8770. // 所有需要图片的资产都已生成,允许继续 confirmActs 后续逻辑
  8771. if (empty($waitingAssets) && empty($missingAssets)) {
  8772. return;
  8773. }
  8774. // 其他任务都已处理完毕,仍有角色、场景或道具图片未生成,统一报错阻止后续逻辑
  8775. if (empty($waitingAssets)) {
  8776. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  8777. }
  8778. // 超过1分钟仍未生成完毕,阻止 confirmActs 后续逻辑
  8779. if (time() - $startTime >= $maxWaitSeconds) {
  8780. Utils::throwError('20003:还有主体、场景或道具图片未生成,请等待图片生成后重试');
  8781. }
  8782. sleep($pollInterval);
  8783. }
  8784. }
  8785. /**
  8786. * 参照 episodePicsInfo:遍历单个资产列表,对有图片任务但还没有图片URL的资产查询图片任务结果并回填。
  8787. * 无任务、任务不存在或生成失败的资产记录为缺失项,不在此处直接报错;
  8788. * 仍在处理中的任务记录为等待项,由外层统一等待所有任务完成后,再对缺失资产统一报错。
  8789. */
  8790. private function refreshEpisodeAssetsImageTasks(&$assets, $nameKey, $skipName, &$waitingAssets, &$missingAssets, &$updated) {
  8791. foreach ($assets as &$asset) {
  8792. $assetName = getProp($asset, $nameKey);
  8793. if ($assetName === '' || ($skipName !== '' && $assetName === $skipName)) {
  8794. continue;
  8795. }
  8796. // 已有图片URL的资产视为已生成
  8797. if (getProp($asset, 'url')) {
  8798. continue;
  8799. }
  8800. $task_id = getProp($asset, 'task_id');
  8801. // 没有图片任务且没有图片URL:记录为缺失项,继续遍历其他资产,待其他任务都完成后再统一报错
  8802. if (!$task_id) {
  8803. $missingAssets[] = $assetName;
  8804. continue;
  8805. }
  8806. $task = DB::table('mp_generate_pic_tasks')
  8807. ->where('id', $task_id)
  8808. ->select('status', 'result_url')
  8809. ->first();
  8810. // 任务不存在:同样记录为缺失项,不在此处直接报错
  8811. if (!$task) {
  8812. $missingAssets[] = $assetName;
  8813. continue;
  8814. }
  8815. if ($task->status === 'success') {
  8816. $result_url = getProp($task, 'result_url');
  8817. if ($result_url) {
  8818. $result_urls = is_json($result_url) ? json_decode($result_url, true) : [$result_url];
  8819. if (is_array($result_urls) && !empty($result_urls[0])) {
  8820. $asset['url'] = $result_urls[0];
  8821. $asset['task_status'] = 'success';
  8822. $updated = true;
  8823. continue;
  8824. }
  8825. }
  8826. // 任务成功但没有可用的结果URL,仍视为未生成,继续等待后续轮询结果
  8827. $waitingAssets[] = $assetName;
  8828. } elseif ($task->status === 'failed') {
  8829. // 生成失败:记录为缺失项,待其他任务处理完后统一报错
  8830. $missingAssets[] = $assetName;
  8831. } else {
  8832. // 任务仍在生成中,等待下一次轮询
  8833. $waitingAssets[] = $assetName;
  8834. }
  8835. }
  8836. unset($asset);
  8837. }
  8838. /**
  8839. * 导出动漫剧本为PDF(参照示例PDF版式)
  8840. * @param int $animeId 动漫ID
  8841. * @param int $episodeCount 导出集数,默认8,传-1表示全部
  8842. * @param string|null $savePath 指定保存路径(为空则直接下载输出)
  8843. * @return string|null
  8844. */
  8845. public function exportAnimeScriptAsPdf($animeId, $episodeCount = 8, $savePath = null) {
  8846. // 图片下载与转换可能占用较多内存
  8847. ini_set('memory_limit', '512M');
  8848. $anime = DB::table('mp_animes')->where('id', $animeId)->where('is_deleted', 0)->first();
  8849. if (!$anime) Utils::throwError('20003:该动漫不存在!');
  8850. $anime = (array)$anime;
  8851. // 剧本名去掉末尾"_数字"标识后缀,只保留剧名本身
  8852. $anime['anime_name'] = trim((string)preg_replace('/_\d+$/u', '', getProp($anime, 'anime_name', '')));
  8853. // 获取分集(默认展示版本,按集数升序)
  8854. $episodeQuery = DB::table('mp_anime_episodes')
  8855. ->where('anime_id', $animeId)
  8856. ->where('is_default', 1)
  8857. ->orderBy('episode_number')
  8858. ->orderBy('id');
  8859. if ($episodeCount > 0) {
  8860. $episodeQuery->limit($episodeCount);
  8861. }
  8862. $episodes = $episodeQuery->get()->map(function ($value) {
  8863. return (array)$value;
  8864. })->toArray();
  8865. if (!$episodes) Utils::throwError('20003:该动漫暂无分集数据');
  8866. // 聚合主体/场景/道具列表(前N集内容,按名称去重)
  8867. $roles = $this->mergeEpisodeItems($episodes, 'role');
  8868. $scenes = $this->mergeEpisodeItems($episodes, 'scene');
  8869. $props = $this->mergeEpisodeItems($episodes, 'prop');
  8870. // 组装分集剧本数据
  8871. $episodeScripts = [];
  8872. foreach ($episodes as $episode) {
  8873. $segments = DB::table('mp_episode_segments')
  8874. ->where('anime_id', $animeId)
  8875. ->where('episode_id', $episode['id'])
  8876. ->get();
  8877. // 按act_number分组,同一片段多版本时取最新一条(id最大)
  8878. $acts = [];
  8879. foreach ($segments as $segment) {
  8880. $segment = (array)$segment;
  8881. $actNumber = (int)getProp($segment, 'act_number', 0);
  8882. if ($actNumber <= 0) continue;
  8883. if (!isset($acts[$actNumber]) || (int)$segment['id'] > (int)$acts[$actNumber]['id']) {
  8884. $acts[$actNumber] = [
  8885. 'id' => (int)$segment['id'],
  8886. 'act_number' => $actNumber,
  8887. 'duration' => getProp($segment, 'act_duration', ''),
  8888. 'content' => getProp($segment, 'act_content', ''),
  8889. ];
  8890. }
  8891. }
  8892. ksort($acts);
  8893. // 分镜序号按出现先后重新编号(整集范围内保持连续,兼容【镜头N】/【分镜N】两种格式)
  8894. $segmentCounter = 0;
  8895. foreach ($acts as &$act) {
  8896. $act['content'] = $this->renumberSegmentBlocks($act['content'], $segmentCounter);
  8897. }
  8898. unset($act);
  8899. // 旁白音色:优先取分集roles中"旁白"的voice_prompt,否则从片段内容解析
  8900. $narratorVoice = '';
  8901. $episodeRoles = json_decode(getProp($episode, 'roles', ''), true) ?: [];
  8902. foreach ($episodeRoles as $role) {
  8903. if (getProp($role, 'role') === '旁白') {
  8904. $narratorVoice = trim((string)getProp($role, 'voice_prompt', ''));
  8905. break;
  8906. }
  8907. }
  8908. if ($narratorVoice === '') {
  8909. foreach ($acts as $act) {
  8910. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $act['content'], $match)) {
  8911. $narratorVoice = trim($match[1]);
  8912. break;
  8913. }
  8914. }
  8915. }
  8916. $episodeScripts[] = [
  8917. 'episode_number' => getProp($episode, 'episode_number'),
  8918. 'title' => getProp($episode, 'title', ''),
  8919. 'act_count' => count($acts),
  8920. 'narrator_voice' => $narratorVoice,
  8921. 'acts' => array_values($acts),
  8922. ];
  8923. }
  8924. // 并发下载列表图片(主体/场景/道具),url => 临时文件
  8925. $imageCache = $this->downloadImagesConcurrently(array_merge($roles, $scenes, $props));
  8926. // 构建PDF
  8927. $pdf = $this->buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache);
  8928. // 图片已嵌入PDF,清理临时文件
  8929. foreach ($imageCache as $imgFile) {
  8930. @unlink($imgFile);
  8931. }
  8932. $filename = $anime['anime_name'] . '_' . date('YmdHis');
  8933. if ($savePath) {
  8934. $pdf->Output($savePath, 'F');
  8935. return $savePath;
  8936. }
  8937. // 直接下载输出
  8938. header('Content-Type: application/pdf');
  8939. header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename . '.pdf'));
  8940. $pdf->Output($filename . '.pdf', 'D');
  8941. exit();
  8942. }
  8943. /**
  8944. * 聚合分集的主体/场景/道具列表,按名称去重(保留首次出现)
  8945. * @param array $episodes 分集数据
  8946. * @param string $nameKey role|scene|prop
  8947. * @return array
  8948. */
  8949. private function mergeEpisodeItems(array $episodes, $nameKey) {
  8950. $fieldMap = [
  8951. 'role' => 'roles',
  8952. 'scene' => 'scenes',
  8953. 'prop' => 'props',
  8954. ];
  8955. $field = isset($fieldMap[$nameKey]) ? $fieldMap[$nameKey] : $nameKey;
  8956. $items = [];
  8957. foreach ($episodes as $episode) {
  8958. $list = json_decode(getProp($episode, $field, ''), true) ?: [];
  8959. foreach ($list as $item) {
  8960. if (!is_array($item)) continue;
  8961. $name = trim((string)getProp($item, $nameKey, ''));
  8962. if ($name === '') continue;
  8963. // 旁白不进入主体列表(仅作为旁白音色来源)
  8964. if ($nameKey === 'role' && $name === '旁白') continue;
  8965. if (!isset($items[$name])) {
  8966. $items[$name] = $item;
  8967. }
  8968. }
  8969. }
  8970. return array_values($items);
  8971. }
  8972. /**
  8973. * 构建动漫剧本PDF
  8974. * @param array $anime 动漫信息
  8975. * @param array $roles 主体列表
  8976. * @param array $scenes 场景列表
  8977. * @param array $props 道具列表
  8978. * @param array $episodeScripts 分集剧本数据
  8979. * @param array $imageCache 图片缓存(url => 临时文件路径)
  8980. * @return \TCPDF
  8981. */
  8982. private function buildAnimeScriptPdf($anime, $roles, $scenes, $props, $episodeScripts, $imageCache = []) {
  8983. $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
  8984. $pdf->SetCreator('动漫剧本导出系统');
  8985. $pdf->SetAuthor('系统');
  8986. $pdf->SetTitle(getProp($anime, 'anime_name', '动漫剧本'));
  8987. $pdf->SetSubject('动漫剧本导出');
  8988. $pdf->SetMargins(15, 15, 15);
  8989. $pdf->SetAutoPageBreak(true, 15);
  8990. // 剧本名
  8991. $pdf->AddPage();
  8992. $pdf->SetFont('simsun', 'B', 20);
  8993. $pdf->Cell(0, 15, getProp($anime, 'anime_name', ''), 0, 1, 'C');
  8994. $pdf->Ln(5);
  8995. // 故事梗概
  8996. $intro = trim((string)getProp($anime, 'intro', ''));
  8997. if ($intro !== '') {
  8998. $this->pdfSectionTitle($pdf, '故事梗概');
  8999. $this->pdfBody($pdf, $intro);
  9000. }
  9001. // 美术风格
  9002. $artStyle = trim((string)getProp($anime, 'art_style', ''));
  9003. if ($artStyle !== '') {
  9004. $this->pdfSectionTitle($pdf, '美术风格');
  9005. $this->pdfBody($pdf, $artStyle);
  9006. }
  9007. // 主体列表(文字+图片)
  9008. $this->pdfSectionTitle($pdf, '主体列表');
  9009. foreach ($roles as $index => $role) {
  9010. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''));
  9011. }
  9012. $this->pdfItemImages($pdf, $roles, 'role', $imageCache);
  9013. // 场景列表(文字+图片)
  9014. $this->pdfSectionTitle($pdf, '场景列表');
  9015. foreach ($scenes as $index => $scene) {
  9016. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''));
  9017. }
  9018. $this->pdfItemImages($pdf, $scenes, 'scene', $imageCache);
  9019. // 道具列表(文字+图片)
  9020. $this->pdfSectionTitle($pdf, '道具列表');
  9021. foreach ($props as $index => $prop) {
  9022. $this->pdfBody($pdf, ($index + 1) . '. ' . getProp($prop, 'prop', '') . ':' . getProp($prop, 'description', ''));
  9023. }
  9024. $this->pdfItemImages($pdf, $props, 'prop', $imageCache);
  9025. // 分镜剧本
  9026. $this->pdfSectionTitle($pdf, '分镜剧本');
  9027. foreach ($episodeScripts as $episodeScript) {
  9028. $episodeTitle = '第' . getProp($episodeScript, 'episode_number') . '集';
  9029. $episodeTitleRaw = trim((string)getProp($episodeScript, 'title', ''));
  9030. if ($episodeTitleRaw !== '') {
  9031. // title 字段可能已带"第N集"前缀,避免重复
  9032. if (preg_match('/^第\d+集[::\s]/u', $episodeTitleRaw)) {
  9033. $episodeTitle = $episodeTitleRaw;
  9034. } else {
  9035. $episodeTitle .= ':' . $episodeTitleRaw;
  9036. }
  9037. }
  9038. $this->pdfSubTitle($pdf, $episodeTitle, 13);
  9039. $this->pdfBody($pdf, '片段数量:' . getProp($episodeScript, 'act_count', 0));
  9040. if (getProp($episodeScript, 'narrator_voice') !== '') {
  9041. $this->pdfBody($pdf, '旁白音色:' . getProp($episodeScript, 'narrator_voice'));
  9042. }
  9043. foreach (getProp($episodeScript, 'acts', []) as $act) {
  9044. $actTitle = '片段' . getProp($act, 'act_number');
  9045. if (getProp($act, 'duration') !== '' && getProp($act, 'duration') !== null) {
  9046. $actTitle .= ' 时长 ' . getProp($act, 'duration') . 's';
  9047. }
  9048. $this->pdfSubTitle($pdf, $actTitle, 12);
  9049. if (getProp($act, 'content') !== '') {
  9050. $this->pdfBody($pdf, getProp($act, 'content'));
  9051. }
  9052. }
  9053. }
  9054. return $pdf;
  9055. }
  9056. /**
  9057. * PDF章节标题(带分隔线)
  9058. */
  9059. private function pdfSectionTitle($pdf, $title) {
  9060. if ($pdf->GetY() > 230) {
  9061. $pdf->AddPage();
  9062. }
  9063. $pdf->SetFont('simsun', 'B', 15);
  9064. $pdf->Cell(0, 10, $title, 0, 1, 'L');
  9065. $y = $pdf->GetY();
  9066. $pdf->SetLineWidth(0.4);
  9067. $pdf->Line(15, $y, 195, $y);
  9068. $pdf->Ln(4);
  9069. }
  9070. /**
  9071. * PDF子标题(集数/片段标题)
  9072. */
  9073. private function pdfSubTitle($pdf, $title, $size = 13) {
  9074. if ($pdf->GetY() > 240) {
  9075. $pdf->AddPage();
  9076. }
  9077. $pdf->SetFont('simsun', 'B', $size);
  9078. $pdf->Cell(0, 8, $title, 0, 1, 'L');
  9079. $pdf->Ln(1);
  9080. }
  9081. /**
  9082. * PDF正文段落
  9083. */
  9084. private function pdfBody($pdf, $text) {
  9085. $pdf->SetFont('simsun', '', 11);
  9086. $pdf->MultiCell(0, 6, $text, 0, 'L');
  9087. $pdf->Ln(2);
  9088. }
  9089. /**
  9090. * 输出列表项图片(每张图单独一页,图下标注名称)
  9091. * @param \TCPDF $pdf
  9092. * @param array $items 列表项
  9093. * @param string $nameKey role|scene|prop
  9094. * @param array $imageCache 图片缓存(url => 临时文件路径)
  9095. */
  9096. private function pdfItemImages($pdf, array $items, $nameKey, array $imageCache) {
  9097. foreach ($items as $item) {
  9098. $url = trim((string)getProp($item, 'url', ''));
  9099. $name = trim((string)getProp($item, $nameKey, ''));
  9100. if ($url === '' || !isset($imageCache[$url])) continue;
  9101. $imgPath = $imageCache[$url];
  9102. $size = @getimagesize($imgPath);
  9103. if (!$size || $size[0] <= 0 || $size[1] <= 0) {
  9104. continue;
  9105. }
  9106. $pdf->AddPage();
  9107. // 图片按比例缩放,居中偏上,为底部名称标注预留空间
  9108. $maxW = 160;
  9109. $maxH = 170;
  9110. $ratio = min($maxW / $size[0], $maxH / $size[1], 1);
  9111. $drawW = $size[0] * $ratio;
  9112. $drawH = $size[1] * $ratio;
  9113. $x = (210 - $drawW) / 2;
  9114. $y = max(15, (297 - $drawH) / 2 - 10);
  9115. $pdf->Image($imgPath, $x, $y, $drawW, $drawH, '', '', '', false, 300, '', false, false, 0, false, false, false);
  9116. // 图下标注名称
  9117. $pdf->SetFont('simsun', 'B', 13);
  9118. $pdf->SetY(297 - 28);
  9119. $pdf->Cell(0, 8, $name, 0, 1, 'C');
  9120. }
  9121. }
  9122. /**
  9123. * 并发下载远程图片到临时文件,并统一缩放转为JPEG
  9124. * @param array $items 包含url字段的列表项
  9125. * @return array url => 临时文件路径
  9126. */
  9127. private function downloadImagesConcurrently(array $items) {
  9128. // 收集唯一的图片URL
  9129. $urls = [];
  9130. foreach ($items as $item) {
  9131. $url = trim((string)getProp($item, 'url', ''));
  9132. if ($url !== '') $urls[$url] = true;
  9133. }
  9134. if (!$urls) return [];
  9135. $urls = array_keys($urls);
  9136. $tmpDir = sys_get_temp_dir();
  9137. $rawFiles = [];
  9138. foreach ($urls as $url) {
  9139. $rawFile = $tmpDir . '/anime_pdf_raw_' . md5($url) . '.img';
  9140. $rawFiles[$url] = $rawFile;
  9141. }
  9142. $client = new Client(['timeout' => 180, 'verify' => false]);
  9143. // 低并发下载,sink写入文件避免大图占用内存
  9144. $generator = (function () use ($urls, $client, $rawFiles) {
  9145. foreach ($urls as $url) {
  9146. yield $url => $client->getAsync($url, ['sink' => $rawFiles[$url]]);
  9147. }
  9148. })();
  9149. $errors = [];
  9150. $each = new \GuzzleHttp\Promise\EachPromise($generator, [
  9151. 'concurrency' => 4,
  9152. 'rejected' => function ($reason, $url) use (&$errors) {
  9153. $errors[$url] = $reason ? $reason->getMessage() : 'unknown';
  9154. },
  9155. ]);
  9156. $each->promise()->wait();
  9157. // 失败的图片串行重试一次(独占带宽,提高成功率)
  9158. foreach ($urls as $url) {
  9159. if (!isset($errors[$url])) continue;
  9160. try {
  9161. $client->get($url, ['sink' => $rawFiles[$url], 'timeout' => 300]);
  9162. unset($errors[$url]);
  9163. } catch (\Throwable $e) {
  9164. // 重试仍失败
  9165. }
  9166. }
  9167. $cache = [];
  9168. foreach ($urls as $url) {
  9169. $rawFile = $rawFiles[$url];
  9170. if (isset($errors[$url])) {
  9171. dLog('anime')->error('导出PDF图片下载失败', [
  9172. 'url' => $url,
  9173. 'error' => $errors[$url],
  9174. ]);
  9175. @unlink($rawFile);
  9176. continue;
  9177. }
  9178. $converted = $this->convertImageFile($rawFile, $url);
  9179. if ($converted !== null) {
  9180. $cache[$url] = $converted;
  9181. } else {
  9182. @unlink($rawFile);
  9183. }
  9184. }
  9185. return $cache;
  9186. }
  9187. /**
  9188. * 将已下载的图片文件缩放并转为JPEG
  9189. * @param string $rawFile 原始图片临时文件
  9190. * @param string $url 图片地址(用于命名)
  9191. * @return string|null 转换后的文件路径,转换失败返回null
  9192. */
  9193. private function convertImageFile($rawFile, $url) {
  9194. $content = @file_get_contents($rawFile);
  9195. if ($content === false || $content === '') return null;
  9196. if (!function_exists('imagecreatefromstring')) return null;
  9197. $image = @imagecreatefromstring($content);
  9198. if ($image === false) return null;
  9199. $jpeg = $this->compressImageForPdf($image, $rawFile, $url);
  9200. imagedestroy($image);
  9201. if ($jpeg !== null) {
  9202. @unlink($rawFile);
  9203. }
  9204. return $jpeg;
  9205. }
  9206. /**
  9207. * 图片压缩:白底合成后转JPEG,分级缩小尺寸与降低质量,保证每张不超过2MB
  9208. * @param resource $srcImage GD图片资源
  9209. * @param string $rawFile 原始图片临时文件
  9210. * @param string $url 图片地址(用于命名)
  9211. * @return string|null 压缩后的JPEG文件路径
  9212. */
  9213. private function compressImageForPdf($srcImage, $rawFile, $url) {
  9214. $maxBytes = 2 * 1024 * 1024; // 2MB
  9215. $sizes = [2048, 1600, 1280, 1024, 800];
  9216. $qualities = [85, 70, 55, 40];
  9217. $jpeg = dirname($rawFile) . '/anime_pdf_img_' . md5($url) . '.jpg';
  9218. foreach ($sizes as $size) {
  9219. $resized = $this->copyAndResize($srcImage, $size);
  9220. $flat = $this->flattenToWhite($resized);
  9221. imagedestroy($resized);
  9222. foreach ($qualities as $quality) {
  9223. ob_start();
  9224. $saved = imagejpeg($flat, null, $quality);
  9225. $data = ob_get_clean();
  9226. if ($saved && $data !== false && $data !== '' && strlen($data) <= $maxBytes) {
  9227. file_put_contents($jpeg, $data);
  9228. imagedestroy($flat);
  9229. dLog('anime')->info('导出PDF图片压缩完成', [
  9230. 'url' => $url,
  9231. 'size' => filesize($jpeg),
  9232. 'edge' => $size,
  9233. 'quality' => $quality,
  9234. ]);
  9235. return $jpeg;
  9236. }
  9237. }
  9238. imagedestroy($flat);
  9239. }
  9240. // 兜底:最小尺寸、最低质量强制输出
  9241. $resized = $this->copyAndResize($srcImage, 800);
  9242. $flat = $this->flattenToWhite($resized);
  9243. imagedestroy($resized);
  9244. $saved = imagejpeg($flat, $jpeg, 30);
  9245. imagedestroy($flat);
  9246. if (!$saved) return null;
  9247. dLog('anime')->info('导出PDF图片压缩完成(兜底)', [
  9248. 'url' => $url,
  9249. 'size' => filesize($jpeg),
  9250. ]);
  9251. return $jpeg;
  9252. }
  9253. /**
  9254. * 等比缩放图片副本(不销毁原图)
  9255. * @param resource $srcImage GD图片资源
  9256. * @param int $maxEdge 最大边长
  9257. * @return resource
  9258. */
  9259. private function copyAndResize($srcImage, $maxEdge) {
  9260. $width = imagesx($srcImage);
  9261. $height = imagesy($srcImage);
  9262. $max = max($width, $height);
  9263. if ($max <= $maxEdge) {
  9264. $copy = imagecreatetruecolor($width, $height);
  9265. imagecopy($copy, $srcImage, 0, 0, 0, 0, $width, $height);
  9266. return $copy;
  9267. }
  9268. $ratio = $maxEdge / $max;
  9269. $newWidth = max(1, (int)round($width * $ratio));
  9270. $newHeight = max(1, (int)round($height * $ratio));
  9271. $resized = imagecreatetruecolor($newWidth, $newHeight);
  9272. imagealphablending($resized, false);
  9273. imagesavealpha($resized, true);
  9274. imagecopyresampled($resized, $srcImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  9275. return $resized;
  9276. }
  9277. /**
  9278. * 将GD图片合成到白色背景上(处理透明通道,输出RGB)
  9279. * @param resource $image GD图片资源
  9280. * @return resource
  9281. */
  9282. private function flattenToWhite($image) {
  9283. $width = imagesx($image);
  9284. $height = imagesy($image);
  9285. $flat = imagecreatetruecolor($width, $height);
  9286. $white = imagecolorallocate($flat, 255, 255, 255);
  9287. imagefill($flat, 0, 0, $white);
  9288. imagecopy($flat, $image, 0, 0, 0, 0, $width, $height);
  9289. return $flat;
  9290. }
  9291. /**
  9292. * 将片段内容中的分镜序号按出现先后重新编号(保证整集连续)
  9293. * @param string $content 片段内容
  9294. * @param int $counter 当前已编号数量(引用传递,整集累计)
  9295. * @return string
  9296. */
  9297. private function renumberSegmentBlocks($content, &$counter) {
  9298. return preg_replace_callback('/^【(分镜|镜头)\d+】/mu', function ($match) use (&$counter) {
  9299. $counter++;
  9300. return '【' . $match[1] . $counter . '】';
  9301. }, $content);
  9302. }
  9303. }