DeepSeekService.php 768 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090
  1. <?php
  2. namespace App\Services\DeepSeek;
  3. use App\Consts\ErrorConst;
  4. use App\Consts\BaseConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use GuzzleHttp\Client;
  8. use DateTime;
  9. use DateTimeZone;
  10. use App\Services\AIGeneration\AIImageGenerationService;
  11. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Log;
  13. use Illuminate\Support\Facades\Redis;
  14. use OSS\Core\OssException;
  15. use OSS\OssClient;
  16. use Smalot\PdfParser\Parser as PdfParser;
  17. use TCPDF;
  18. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  19. use Predis\Command\Traits\Get\Get;
  20. class DeepSeekService
  21. {
  22. private $url;
  23. private $api_key;
  24. private $sys_message;
  25. private $headers;
  26. private $valid_text_models;
  27. private $gpt_text_models;
  28. private $gemini_text_models;
  29. protected $aiImageGenerationService;
  30. public function __construct(AIImageGenerationService $aiImageGenerationService) {
  31. $this->aiImageGenerationService = $aiImageGenerationService;
  32. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  33. $this->api_key = env('DEEPSEEK_API_KEY');
  34. $this->headers = [
  35. 'Authorization' => 'Bearer '.$this->api_key,
  36. 'Content-Type' => 'application/json; charset=UTF-8'
  37. ];
  38. // 火山引擎模型列表
  39. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  40. // GPT文本模型列表
  41. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  42. // Gemini文本模型列表
  43. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  44. $this->sys_message = [
  45. 'role' => 'system',
  46. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  47. 强制要求:\n
  48. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  49. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  50. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  51. 普通要求:\n
  52. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  53. 2.<分集剧本>的要求如下:
  54.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  55.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  56.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  57.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  58. \n\n
  59. 示例如下:\n
  60. ###剧本名:西昆仑
  61. ###故事梗概
  62. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  63. ###剧本亮点
  64. 亮点1:绝境奇药,生死一线
  65. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  66. 亮点2:结拜兄妹,化解尴尬
  67. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  68. 亮点3:纤发夺命,情愫暗涌
  69. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  70. ###人物关系
  71. 阿雪与梁萧之间存在兄妹之情。
  72. ###核心矛盾
  73. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  74. ###主体列表
  75. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  76. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  77. 阴阳球:天地异宝,能化生精气,救人于危难。
  78. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  79. ###美术风格
  80. 基础画风风格词:厚涂古风
  81. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  82. ###场景列表
  83. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  84. ###分集剧本
  85. ##分集01
  86. 第1集: 第一集的标题
  87. 场景描述:地点、时间、场景
  88. 运镜:固定近距离
  89. 出场角色:男主、女主
  90. 台词内容:
  91. 女主: 女主对话
  92. 男主:男主对话
  93. 女主: 女主对话
  94. 男主: 男主对话
  95. ##分集02
  96. 第2集: 第二集的标题
  97. 场景描述:地点、时间、场景
  98. 运镜:固定近距离
  99. 出场角色:男主、女主
  100. 台词内容:
  101. 女主: 女主对话
  102. 男主:男主对话
  103. 女主: 女主对话
  104. 男主: 男主对话"
  105. ];
  106. }
  107. /**
  108. * 通用文生文方法 - 支持多模型流式输出和图片输入
  109. *
  110. * @param array $data 请求参数
  111. * @return \Generator 返回生成器,用于流式输出
  112. */
  113. public function generateText($data) {
  114. // 获取请求参数
  115. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  116. $messages = getProp($data, 'messages', []);
  117. $systemPrompt = getProp($data, 'system_prompt', '');
  118. $prompt = getProp($data, 'prompt', '');
  119. $images = getProp($data, 'images', []); // 支持多张图片
  120. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  121. // 如果没有提供messages,则根据system_prompt、content和images构建
  122. if (empty($messages)) {
  123. $messages = [];
  124. // 添加系统提示词
  125. if (!empty($systemPrompt)) {
  126. $messages[] = [
  127. 'role' => 'system',
  128. 'content' => $systemPrompt
  129. ];
  130. }
  131. // 构建用户消息内容(支持文本+图片)
  132. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  133. $userMessage = [
  134. 'role' => 'user',
  135. 'content' => []
  136. ];
  137. // 添加文本内容
  138. if (!empty($prompt)) {
  139. $userMessage['content'][] = [
  140. 'type' => 'text',
  141. 'text' => $prompt
  142. ];
  143. }
  144. // 处理上传的图片文件
  145. if (!empty($images)) {
  146. if (!is_array($images)) {
  147. $images = [$images];
  148. }
  149. foreach ($images as $image) {
  150. $imageBase64 = $this->processImageToBase64($image);
  151. if ($imageBase64) {
  152. $userMessage['content'][] = [
  153. 'type' => 'image_url',
  154. 'image_url' => [
  155. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  156. ]
  157. ];
  158. }
  159. }
  160. }
  161. // 处理图片URL
  162. if (!empty($imageUrls)) {
  163. if (!is_array($imageUrls)) {
  164. $imageUrls = [$imageUrls];
  165. }
  166. foreach ($imageUrls as $url) {
  167. if (!empty($url)) {
  168. $userMessage['content'][] = [
  169. 'type' => 'image_url',
  170. 'image_url' => [
  171. 'url' => $url
  172. ]
  173. ];
  174. }
  175. }
  176. }
  177. // 如果只有文本内容,简化为字符串格式
  178. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  179. $userMessage['content'] = $userMessage['content'][0]['text'];
  180. }
  181. $messages[] = $userMessage;
  182. }
  183. }
  184. // 验证messages不为空
  185. if (empty($messages)) {
  186. Utils::throwError('20003:请提供有效的对话内容');
  187. }
  188. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  189. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  190. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  191. if ($model === 'deepseek-chat') {
  192. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  193. $model = 'deepseek-v4-flash';
  194. $thinkingMode = 'disabled';
  195. } elseif ($model === 'deepseek-reasoner') {
  196. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  197. $model = 'deepseek-v4-flash';
  198. $thinkingMode = 'enabled';
  199. }
  200. // 构建请求参数
  201. $post_data = [
  202. 'model' => $model,
  203. 'messages' => $messages,
  204. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  205. 'temperature' => getProp($data, 'temperature', 1),
  206. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  207. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  208. 'thinking' => ['type' => $thinkingMode],
  209. 'stream' => true // 启用流式输出
  210. ];
  211. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  212. // 添加可选参数
  213. if (isset($data['top_p'])) {
  214. $post_data['top_p'] = $data['top_p'];
  215. }
  216. if (isset($data['response_format'])) {
  217. $post_data['response_format'] = $data['response_format'];
  218. }
  219. // 根据模型类型选择调用方法
  220. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  221. // DeepSeek 官方模型使用 DeepSeek API
  222. return $this->deepSeekStreamResponse($post_data);
  223. } else if (in_array($model, $this->gpt_text_models)) {
  224. // GPT 模型使用 TokenRouter API
  225. return $this->gpt54StreamResponse($post_data);
  226. } else if (in_array($model, $this->gemini_text_models)) {
  227. // Gemini 模型使用 Gemini API
  228. return $this->geminiStreamResponse($post_data, $model);
  229. } else if (in_array($model, $this->valid_text_models)) {
  230. // 火山引擎支持的模型使用火山引擎 API
  231. return $this->volcEngineChatCompletion($post_data);
  232. } else {
  233. Utils::throwError('20003:不支持的模型: ' . $model);
  234. }
  235. }
  236. public function createGenerateText($data) {
  237. $file = getProp($data, 'file');
  238. $uid = Site::getUid();
  239. $cpid = Site::getCpid();
  240. if (!$file) {
  241. Utils::throwError('20003:请上传文件');
  242. }
  243. // 提取文件内容
  244. $content = $this->extractFileContent($file);
  245. if (!$content) {
  246. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  247. }
  248. // 获取原始文件名(不含扩展名)作为script_name
  249. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  250. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  251. // 字节安全剥离,不依赖服务器locale设置
  252. $originalName = $file->getClientOriginalName();
  253. $extension = $file->getClientOriginalExtension();
  254. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  255. ? substr($originalName, 0, -strlen($extension) - 1)
  256. : $originalName;
  257. if ($script_name === '') {
  258. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  259. }
  260. // 如果同一用户的剧本名存在则提示
  261. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  262. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  263. }
  264. // 插入数据到mp_scripts表
  265. $script_id = DB::table('mp_scripts')->insertGetId([
  266. 'script_name' => $script_name,
  267. 'user_id' => $uid,
  268. 'cpid' => $cpid,
  269. 'content' => $content,
  270. 'created_at' => date('Y-m-d H:i:s'),
  271. 'updated_at' => date('Y-m-d H:i:s')
  272. ]);
  273. return [
  274. 'script_id' => $script_id,
  275. 'script_name' => $script_name
  276. ];
  277. }
  278. /**
  279. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  280. *
  281. * @param array $data 请求参数
  282. * @return array 返回结果数组
  283. */
  284. public function newGenerateText($data) {
  285. // 获取请求参数
  286. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  287. $messages = getProp($data, 'messages', []);
  288. $systemPrompt = getProp($data, 'system_prompt', '');
  289. $prompt = getProp($data, 'prompt', '');
  290. $images = getProp($data, 'images', []); // 支持多张图片
  291. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  292. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  293. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  294. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  295. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  296. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  297. $generateTaskId = 0;
  298. if ($script_id > 0) {
  299. $uid = Site::getUid();
  300. $existingTask = DB::table('mp_script_generate_tasks')
  301. ->where('uid', $uid)
  302. ->where('script_id', $script_id)
  303. ->orderByDesc('id')
  304. ->first();
  305. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  306. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  307. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  308. }
  309. }
  310. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  311. $originalContent = '';
  312. if ($script_id > 0) {
  313. $script = DB::table('mp_scripts')
  314. ->where('id', $script_id)
  315. ->where('is_deleted', 0)
  316. ->first();
  317. if (!$script) {
  318. Utils::throwError('20003:剧本不存在或已删除');
  319. }
  320. $originalContent = $script->content ?? '';
  321. if (empty($originalContent)) {
  322. Utils::throwError('20003:剧本内容为空');
  323. }
  324. // 将剧本内容添加到提示词前面
  325. if (!empty($originalContent)) {
  326. if (!empty($prompt)) {
  327. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  328. } else {
  329. $prompt = "原文内容:\n" . $originalContent;
  330. }
  331. }
  332. }
  333. // 新增: 如果提供了template_id,从数据库获取template_prompt
  334. if ($templateId > 0) {
  335. $template = DB::table('mp_prompt_templates')
  336. ->where('id', $templateId)
  337. ->where('is_deleted', 0)
  338. ->first();
  339. if (!$template) {
  340. Utils::throwError('20003:模板不存在或已删除');
  341. }
  342. $templatePrompt = $template->template_prompt ?? '';
  343. // 将模板提示词和用户输入的prompt组合
  344. // 模板为准,用户输入作为补充要求
  345. if (!empty($templatePrompt)) {
  346. if (!empty($prompt)) {
  347. $prompt = $templatePrompt . "\n\n" . $prompt;
  348. } else {
  349. $prompt = $templatePrompt;
  350. }
  351. }
  352. }
  353. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  354. if (empty($messages)) {
  355. $messages = [];
  356. // 添加系统提示词
  357. if (!empty($systemPrompt)) {
  358. $messages[] = [
  359. 'role' => 'system',
  360. 'content' => $systemPrompt
  361. ];
  362. }
  363. // 构建用户消息内容(支持文本+图片)
  364. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  365. $userMessage = [
  366. 'role' => 'user',
  367. 'content' => []
  368. ];
  369. // 添加文本内容
  370. if (!empty($prompt)) {
  371. $userMessage['content'][] = [
  372. 'type' => 'text',
  373. 'text' => $prompt
  374. ];
  375. }
  376. // 处理上传的图片文件
  377. if (!empty($images)) {
  378. if (!is_array($images)) {
  379. $images = [$images];
  380. }
  381. foreach ($images as $image) {
  382. $imageBase64 = $this->processImageToBase64($image);
  383. if ($imageBase64) {
  384. $userMessage['content'][] = [
  385. 'type' => 'image_url',
  386. 'image_url' => [
  387. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  388. ]
  389. ];
  390. }
  391. }
  392. }
  393. // 处理图片URL
  394. if (!empty($imageUrls)) {
  395. if (!is_array($imageUrls)) {
  396. $imageUrls = [$imageUrls];
  397. }
  398. foreach ($imageUrls as $url) {
  399. if (!empty($url)) {
  400. $userMessage['content'][] = [
  401. 'type' => 'image_url',
  402. 'image_url' => [
  403. 'url' => $url
  404. ]
  405. ];
  406. }
  407. }
  408. }
  409. // 如果只有文本内容,简化为字符串格式
  410. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  411. $userMessage['content'] = $userMessage['content'][0]['text'];
  412. }
  413. $messages[] = $userMessage;
  414. }
  415. }
  416. // 验证messages不为空
  417. if (empty($messages)) {
  418. Utils::throwError('20003:请提供有效的对话内容');
  419. }
  420. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  421. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  422. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  423. if ($model === 'deepseek-chat') {
  424. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  425. $model = 'deepseek-v4-flash';
  426. $thinkingMode = 'disabled';
  427. } elseif ($model === 'deepseek-reasoner') {
  428. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  429. $model = 'deepseek-v4-flash';
  430. $thinkingMode = 'enabled';
  431. }
  432. // 构建请求参数(非流式)
  433. $post_data = [
  434. 'model' => $model,
  435. 'messages' => $messages,
  436. 'temperature' => getProp($data, 'temperature', 1),
  437. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  438. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  439. 'thinking' => ['type' => $thinkingMode],
  440. 'stream' => false // 非流式输出
  441. ];
  442. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  443. // 添加可选参数
  444. if (isset($data['top_p'])) {
  445. $post_data['top_p'] = $data['top_p'];
  446. }
  447. // 新增: 根据response_format设置响应格式
  448. if ($responseFormat === 'json') {
  449. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  450. $hasJsonKeyword = false;
  451. foreach ($post_data['messages'] as $message) {
  452. if (isset($message['content'])) {
  453. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  454. if (stripos($content, 'json') !== false) {
  455. $hasJsonKeyword = true;
  456. break;
  457. }
  458. }
  459. }
  460. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  461. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  462. if (!$hasJsonKeyword) {
  463. $lastMessageIndex = count($post_data['messages']) - 1;
  464. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  465. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  466. // 如果content是字符串,直接追加
  467. if (is_string($lastContent)) {
  468. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  469. }
  470. // 如果content是数组(包含文本和图片),在文本部分追加
  471. else if (is_array($lastContent)) {
  472. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  473. if ($contentPart['type'] === 'text') {
  474. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  475. break;
  476. }
  477. }
  478. }
  479. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  480. }
  481. }
  482. // 设置response_format参数(所有支持的模型)
  483. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  484. // DeepSeek模型
  485. $post_data['response_format'] = ['type' => 'json_object'];
  486. } else if (in_array($model, $this->gpt_text_models)) {
  487. // GPT模型
  488. $post_data['response_format'] = ['type' => 'json_object'];
  489. } else if (in_array($model, $this->valid_text_models)) {
  490. // 火山引擎模型
  491. $post_data['response_format'] = ['type' => 'json_object'];
  492. }
  493. }
  494. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  495. if ($script_id > 0) {
  496. $uid = Site::getUid();
  497. // 创建新的生成任务
  498. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  499. 'uid' => $uid,
  500. 'script_id' => $script_id,
  501. 'sequence' => $sequence,
  502. 'status' => 'processing',
  503. 'prompt' => getProp($data, 'prompt', ''),
  504. 'started_at' => date('Y-m-d H:i:s'),
  505. 'created_at' => date('Y-m-d H:i:s'),
  506. 'updated_at' => date('Y-m-d H:i:s')
  507. ]);
  508. }
  509. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  510. try {
  511. $aiResult = null;
  512. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  513. // DeepSeek 官方模型使用现有的 chatOnly 方法
  514. $result = $this->chatOnly($post_data);
  515. // 记录实际使用的模型
  516. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  517. $aiResult = [
  518. 'content' => $result['fullContent'],
  519. 'reasoning_content' => $result['fullReasoningContent'],
  520. 'usage' => $result['usage'],
  521. 'model' => $model,
  522. 'finish_reason' => 'stop'
  523. ];
  524. } else if (in_array($model, $this->gpt_text_models)) {
  525. // GPT 模型使用现有的 gpt54ChatOnly 方法
  526. $result = $this->gpt54ChatOnly($post_data);
  527. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  528. $aiResult = [
  529. 'content' => $result['fullContent'],
  530. 'reasoning_content' => '',
  531. 'usage' => $result['usage'],
  532. 'model' => $model,
  533. 'finish_reason' => 'stop'
  534. ];
  535. } else if (in_array($model, $this->gemini_text_models)) {
  536. // Gemini 模型使用 Gemini API(非流式)
  537. $result = $this->geminiChatOnly($post_data, $model);
  538. dLog('deepseek')->info('newGenerateText使用Gemini模型', ['requested_model' => $model]);
  539. $aiResult = [
  540. 'content' => $result['fullContent'],
  541. 'reasoning_content' => $result['fullReasoningContent'] ?? '',
  542. 'usage' => $result['usage'],
  543. 'model' => $model,
  544. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  545. ];
  546. } else if (in_array($model, $this->valid_text_models)) {
  547. // 火山引擎支持的模型使用火山引擎 API(非流式)
  548. $post_data['stream'] = false;
  549. $result = $this->volcEngineChatCompletion($post_data);
  550. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  551. 'requested_model' => $model,
  552. 'result_keys' => array_keys($result),
  553. 'has_fullContent' => isset($result['fullContent']),
  554. 'has_content' => isset($result['content'])
  555. ]);
  556. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  557. $aiResult = [
  558. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  559. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  560. 'usage' => $result['usage'] ?? [],
  561. 'model' => $model,
  562. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  563. ];
  564. } else {
  565. Utils::throwError('20003:不支持的模型: ' . $model);
  566. }
  567. } catch (\Exception $e) {
  568. // 生成失败,更新任务状态
  569. if ($generateTaskId) {
  570. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  571. 'status' => 'failed',
  572. 'error_message' => $e->getMessage(),
  573. 'completed_at' => date('Y-m-d H:i:s'),
  574. 'updated_at' => date('Y-m-d H:i:s')
  575. ]);
  576. }
  577. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  578. }
  579. // 生成成功,更新任务状态
  580. if ($generateTaskId && $aiResult) {
  581. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  582. 'status' => 'success',
  583. 'result' => getProp($aiResult, 'content', ''),
  584. 'completed_at' => date('Y-m-d H:i:s'),
  585. 'updated_at' => date('Y-m-d H:i:s')
  586. ]);
  587. $aiResult['generate_task_id'] = $generateTaskId;
  588. }
  589. // 新增: 如果提供了script_id,保存对话记录
  590. if ($script_id > 0 && $aiResult) {
  591. try {
  592. $uid = Site::getUid();
  593. $now = now();
  594. // 获取用户原始的prompt(不包含剧本内容)
  595. $originalPrompt = getProp($data, 'prompt', '');
  596. $recordsToInsert = [
  597. [
  598. 'uid' => $uid,
  599. 'script_id' => $script_id,
  600. 'sequence' => $sequence,
  601. 'role' => 'user',
  602. 'content' => $originalPrompt,
  603. 'created_at' => $now,
  604. 'updated_at' => $now,
  605. ],
  606. [
  607. 'uid' => $uid,
  608. 'script_id' => $script_id,
  609. 'sequence' => $sequence,
  610. 'role' => 'assistant',
  611. 'content' => $aiResult['content'],
  612. 'created_at' => $now,
  613. 'updated_at' => $now,
  614. ]
  615. ];
  616. DB::table('mp_script_records')->insert($recordsToInsert);
  617. // 获取刚插入的记录ID(假设按插入顺序返回)
  618. $insertedRecords = DB::table('mp_script_records')
  619. ->where('uid', $uid)
  620. ->where('script_id', $script_id)
  621. ->where('sequence', $sequence)
  622. ->orderBy('id', 'desc')
  623. ->limit(2)
  624. ->get()
  625. ->map(function ($record) {
  626. return [
  627. 'rid' => $record->id,
  628. 'script_id' => $record->script_id,
  629. 'sequence' => $record->sequence,
  630. 'role' => $record->role,
  631. 'content' => $record->content,
  632. 'created_at' => $record->created_at,
  633. ];
  634. })
  635. ->reverse()
  636. ->values()
  637. ->toArray();
  638. // 将记录信息添加到返回结果中
  639. $aiResult['records'] = $insertedRecords;
  640. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  641. } catch (\Exception $e) {
  642. // 记录错误但不影响主流程
  643. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  644. }
  645. }
  646. return $aiResult;
  647. }
  648. /**
  649. * 通用 Gemini 文生文方法(支持流式和非流式)
  650. *
  651. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  652. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  653. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  654. * system_prompt 系统提示词(可选)
  655. * prompt 用户提示词(可选)
  656. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  657. * image_urls 图片/视频URL列表(可选,同上)
  658. * temperature 温度(可选,默认 1)
  659. * top_p 核采样(可选)
  660. * max_tokens 最大输出 token(可选,默认 8192)
  661. * response_format text/json(可选)
  662. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  663. * thinking_budget 思考预算(可选,默认 20)
  664. * stream 是否流式(可选,默认 false)
  665. *
  666. * @param array $data 请求参数
  667. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  668. */
  669. public function geminiGenerateText($data) {
  670. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  671. $isStream = (bool)getProp($data, 'stream', false);
  672. if (!in_array($model, $this->gemini_text_models)) {
  673. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  674. }
  675. $requestData = $this->buildGeminiRequestBody($data, $model);
  676. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  677. if ($isStream) {
  678. // 流式返回生成器
  679. return $this->geminiStreamResponse($requestData, $model);
  680. }
  681. // 非流式
  682. return $this->geminiChatOnly($requestData, $model);
  683. }
  684. /**
  685. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  686. */
  687. private function geminiMediaMaxBytes() {
  688. return 14 * 1024 * 1024;
  689. }
  690. /**
  691. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  692. */
  693. private function buildGeminiRequestBody($data, $model) {
  694. $messages = getProp($data, 'messages', []);
  695. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  696. if (empty($messages)) {
  697. $systemPrompt = getProp($data, 'system_prompt', '');
  698. $prompt = getProp($data, 'prompt', '');
  699. $images = getProp($data, 'images', []);
  700. $imageUrls = getProp($data, 'image_urls', []);
  701. $messages = [];
  702. if (!empty($systemPrompt)) {
  703. $messages[] = [
  704. 'role' => 'system',
  705. 'content' => $systemPrompt
  706. ];
  707. }
  708. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  709. $userMessage = ['role' => 'user', 'content' => []];
  710. if (!empty($prompt)) {
  711. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  712. }
  713. if (!empty($images)) {
  714. if (!is_array($images)) {
  715. $images = [$images];
  716. }
  717. foreach ($images as $image) {
  718. $inlineData = $this->processMediaToInlineData($image);
  719. if ($inlineData) {
  720. $userMessage['content'][] = [
  721. 'type' => 'image',
  722. 'inline_data' => $inlineData
  723. ];
  724. }
  725. }
  726. }
  727. if (!empty($imageUrls)) {
  728. if (!is_array($imageUrls)) {
  729. $imageUrls = [$imageUrls];
  730. }
  731. foreach ($imageUrls as $url) {
  732. if (!empty($url)) {
  733. $inlineData = $this->processMediaToInlineData($url);
  734. if ($inlineData) {
  735. $userMessage['content'][] = [
  736. 'type' => 'image',
  737. 'inline_data' => $inlineData
  738. ];
  739. }
  740. }
  741. }
  742. }
  743. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  744. $userMessage['content'] = $userMessage['content'][0]['text'];
  745. }
  746. $messages[] = $userMessage;
  747. }
  748. }
  749. if (empty($messages)) {
  750. Utils::throwError('20003:请提供有效的对话内容');
  751. }
  752. // 转换为 Gemini contents 格式
  753. $systemInstruction = '';
  754. $contents = [];
  755. foreach ($messages as $message) {
  756. $role = getProp($message, 'role', 'user');
  757. $content = getProp($message, 'content', '');
  758. if ($role === 'system') {
  759. if (is_array($content)) {
  760. $systemInstruction = $this->extractGeminiTextFromParts($content);
  761. } else {
  762. $systemInstruction = (string)$content;
  763. }
  764. continue;
  765. }
  766. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  767. $parts = [];
  768. if (is_array($content)) {
  769. foreach ($content as $part) {
  770. $partType = getProp($part, 'type', 'text');
  771. if ($partType === 'text') {
  772. $text = (string)getProp($part, 'text', '');
  773. if ($text !== '') {
  774. $parts[] = ['text' => $text];
  775. }
  776. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  777. if (in_array($partType, ['image_url', 'video_url'])) {
  778. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  779. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  780. } elseif (isset($part['inline_data'])) {
  781. // 已处理过的 inline_data 直接使用
  782. $parts[] = ['inline_data' => $part['inline_data']];
  783. continue;
  784. } else {
  785. $url = '';
  786. }
  787. $inlineData = $this->processMediaToInlineData($url);
  788. if ($inlineData) {
  789. $parts[] = ['inline_data' => $inlineData];
  790. }
  791. }
  792. }
  793. } else {
  794. $text = (string)$content;
  795. if ($text !== '') {
  796. $parts[] = ['text' => $text];
  797. }
  798. }
  799. if (!empty($parts)) {
  800. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  801. }
  802. }
  803. if (empty($contents)) {
  804. Utils::throwError('20003:请提供有效的对话内容');
  805. }
  806. // 构建生成配置
  807. $generationConfig = [];
  808. if (getProp($data, 'temperature', null) !== null) {
  809. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  810. }
  811. if (getProp($data, 'top_p', null) !== null) {
  812. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  813. }
  814. if (getProp($data, 'frequency_penalty', null) !== null) {
  815. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  816. }
  817. if (getProp($data, 'presence_penalty', null) !== null) {
  818. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  819. }
  820. $generationConfig['maxOutputTokens'] = (int)getProp($data, 'max_tokens', 8192);
  821. // response_format 映射:text -> text/plain,json -> application/json
  822. $responseFormat = getProp($data, 'response_format', 'text');
  823. if (is_array($responseFormat)) {
  824. $responseFormat = getProp($responseFormat, 'type', 'text');
  825. }
  826. if (in_array($responseFormat, ['json', 'json_object'])) {
  827. $generationConfig['responseMimeType'] = 'application/json';
  828. } else {
  829. $generationConfig['responseMimeType'] = 'text/plain';
  830. }
  831. $requestData = [
  832. 'contents' => $contents,
  833. 'generationConfig' => $generationConfig,
  834. ];
  835. if ($systemInstruction !== '') {
  836. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  837. }
  838. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  839. $thinkingMode = getProp($data, 'thinking', null);
  840. if (is_array($thinkingMode)) {
  841. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  842. }
  843. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  844. if ($thinkingMode === null) {
  845. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  846. }
  847. if ($thinkingMode === 'enabled') {
  848. $requestData['generationConfig']['thinkingConfig'] = [
  849. 'thinkingBudget' => (int)getProp($data, 'thinking_budget', 20)
  850. ];
  851. } else {
  852. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  853. }
  854. return $requestData;
  855. }
  856. /**
  857. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  858. *
  859. * 模型名 -> env 变量名映射:
  860. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  861. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  862. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  863. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  864. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  865. */
  866. private function getGeminiApiKey($model) {
  867. $map = [
  868. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  869. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  870. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  871. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  872. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  873. ];
  874. if (isset($map[$model])) {
  875. $key = env($map[$model]);
  876. if (!empty($key)) {
  877. return $key;
  878. }
  879. }
  880. return env('GEMINI_API_KEY', '');
  881. }
  882. /**
  883. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  884. */
  885. private function geminiChatOnly($requestData, $model) {
  886. $apiKey = $this->getGeminiApiKey($model);
  887. if (empty($apiKey)) {
  888. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  889. }
  890. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  891. . '/models/' . $model . ':generateContent';
  892. $client = new Client(['timeout' => 1800, 'verify' => false]);
  893. $headers = [
  894. 'Authorization' => 'Bearer ' . $apiKey,
  895. 'Content-Type' => 'application/json'
  896. ];
  897. $maxRetries = $this->gptRetryTimes();
  898. $interval = $this->gptRetryInterval();
  899. $attempt = 0;
  900. while (true) {
  901. try {
  902. $response = $client->post($url, [
  903. 'json' => $requestData,
  904. 'headers' => $headers
  905. ]);
  906. $responseArr = json_decode($response->getBody()->getContents(), true);
  907. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  908. $fullContent = $this->extractGeminiContent($responseArr);
  909. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  910. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  911. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  912. ? $responseArr['candidates'][0]['finishReason']
  913. : '';
  914. return [
  915. 'fullContent' => $fullContent,
  916. 'fullReasoningContent' => $fullReasoningContent,
  917. 'usage' => $usage,
  918. 'finish_reason' => $finishReason
  919. ];
  920. } catch (\Exception $e) {
  921. $retryable = true;
  922. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  923. $status = $e->getResponse()->getStatusCode();
  924. $retryable = $status >= 500 || $status == 429;
  925. }
  926. if (!$retryable || $attempt >= $maxRetries) {
  927. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  928. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  929. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  930. }
  931. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  932. 'retry' => $attempt + 1,
  933. 'max_retries' => $maxRetries,
  934. 'error' => $e->getMessage()
  935. ]);
  936. sleep($interval);
  937. $attempt++;
  938. }
  939. }
  940. }
  941. /**
  942. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  943. */
  944. private function geminiStreamResponse($requestData, $model) {
  945. $apiKey = $this->getGeminiApiKey($model);
  946. if (empty($apiKey)) {
  947. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  948. }
  949. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  950. if (isset($requestData['messages'])) {
  951. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  952. }
  953. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  954. . '/models/' . $model . ':generateContent?alt=sse';
  955. $client = new Client(['timeout' => 1800, 'verify' => false]);
  956. $headers = [
  957. 'Authorization' => 'Bearer ' . $apiKey,
  958. 'Content-Type' => 'application/json'
  959. ];
  960. try {
  961. $response = $client->post($url, [
  962. 'json' => $requestData,
  963. 'headers' => $headers,
  964. 'stream' => true
  965. ]);
  966. $body = $response->getBody();
  967. $fullContent = '';
  968. $fullReasoningContent = '';
  969. $usage = [];
  970. $buffer = '';
  971. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  972. while (!$body->eof()) {
  973. $chunk = $body->read(1024);
  974. $buffer .= $chunk;
  975. $lines = explode("\n", $buffer);
  976. $buffer = array_pop($lines);
  977. foreach ($lines as $line) {
  978. $line = trim($line);
  979. if (empty($line) || strpos($line, 'data: ') !== 0) {
  980. continue;
  981. }
  982. $data = substr($line, 6);
  983. if ($data === '[DONE]') {
  984. break 2;
  985. }
  986. try {
  987. $json = json_decode($data, true);
  988. if (json_last_error() !== JSON_ERROR_NONE) {
  989. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  990. continue;
  991. }
  992. // 思考内容(thoughts)
  993. $thoughts = $this->extractGeminiThoughts($json);
  994. if ($thoughts !== '') {
  995. $fullReasoningContent .= $thoughts;
  996. yield [
  997. 'type' => 'reasoning',
  998. 'content' => $thoughts,
  999. 'full_reasoning' => $fullReasoningContent
  1000. ];
  1001. }
  1002. // 回答内容
  1003. $partText = $this->extractGeminiContent($json);
  1004. if ($partText !== '') {
  1005. $fullContent .= $partText;
  1006. yield [
  1007. 'type' => 'content',
  1008. 'content' => $partText,
  1009. ];
  1010. }
  1011. // 使用统计
  1012. if (isset($json['usageMetadata'])) {
  1013. $usage = $json['usageMetadata'];
  1014. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  1015. }
  1016. } catch (\Exception $e) {
  1017. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1018. continue;
  1019. }
  1020. }
  1021. }
  1022. dLog('deepseek')->info('Gemini流式读取完成', [
  1023. 'content_length' => strlen($fullContent),
  1024. 'reasoning_length' => strlen($fullReasoningContent)
  1025. ]);
  1026. yield [
  1027. 'type' => 'done',
  1028. 'full_content' => $fullContent,
  1029. 'full_reasoning' => $fullReasoningContent,
  1030. 'usage' => $usage
  1031. ];
  1032. } catch (\Exception $e) {
  1033. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  1034. yield [
  1035. 'type' => 'error',
  1036. 'msg' => $e->getMessage(),
  1037. 'code' => $e->getCode()
  1038. ];
  1039. }
  1040. }
  1041. /**
  1042. * 从 Gemini 响应中提取回答文本
  1043. */
  1044. private function extractGeminiContent($responseArr) {
  1045. $text = '';
  1046. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  1047. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  1048. if (isset($part['text'])) {
  1049. $text .= $part['text'];
  1050. }
  1051. }
  1052. }
  1053. return $text;
  1054. }
  1055. /**
  1056. * 从 Gemini 响应中提取思考内容
  1057. */
  1058. private function extractGeminiReasoningContent($responseArr) {
  1059. $reasoning = '';
  1060. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1061. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1062. if (isset($thought['text'])) {
  1063. $reasoning .= $thought['text'];
  1064. }
  1065. }
  1066. }
  1067. return $reasoning;
  1068. }
  1069. /**
  1070. * 从 Gemini 流式响应中提取本次增量思考内容
  1071. */
  1072. private function extractGeminiThoughts($responseArr) {
  1073. $thoughts = '';
  1074. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1075. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1076. if (isset($thought['text'])) {
  1077. $thoughts .= $thought['text'];
  1078. }
  1079. }
  1080. }
  1081. return $thoughts;
  1082. }
  1083. /**
  1084. * 提取消息数组中的纯文本
  1085. */
  1086. private function extractGeminiTextFromParts($parts) {
  1087. $text = '';
  1088. if (is_array($parts)) {
  1089. foreach ($parts as $part) {
  1090. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  1091. $text .= (string)getProp($part, 'text', '');
  1092. }
  1093. }
  1094. }
  1095. return $text;
  1096. }
  1097. /**
  1098. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  1099. *
  1100. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  1101. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  1102. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  1103. *
  1104. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  1105. * @return array|null ['mime_type' => string, 'data' => string]
  1106. */
  1107. private function processMediaToInlineData($media) {
  1108. if (empty($media)) {
  1109. return null;
  1110. }
  1111. $localPath = null;
  1112. $isTempFile = false;
  1113. try {
  1114. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  1115. if (is_string($media) && strpos($media, 'data:') === 0) {
  1116. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  1117. return [
  1118. 'mime_type' => $matches[1],
  1119. 'data' => $matches[2]
  1120. ];
  1121. }
  1122. return null;
  1123. }
  1124. // 2. 获取本地文件路径
  1125. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  1126. $localPath = $this->downloadMediaToTemp($media);
  1127. $isTempFile = true;
  1128. } elseif (is_string($media)) {
  1129. $localPath = $media;
  1130. } else {
  1131. // Laravel UploadedFile 对象
  1132. $localPath = $media->getRealPath();
  1133. }
  1134. if (!$localPath || !file_exists($localPath)) {
  1135. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  1136. return null;
  1137. }
  1138. $fileSize = filesize($localPath);
  1139. $maxBytes = $this->geminiMediaMaxBytes();
  1140. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  1141. $mimeType = $this->detectMediaMime($localPath);
  1142. $isVideo = strpos($mimeType, 'video/') === 0;
  1143. $needCompress = $fileSize > $maxBytes;
  1144. $duration = 0;
  1145. if ($isVideo) {
  1146. $duration = $this->getMediaDuration($localPath);
  1147. if ($duration > 300) {
  1148. $needCompress = true;
  1149. }
  1150. }
  1151. $finalPath = $localPath;
  1152. $compressedPath = null;
  1153. if ($needCompress && $this->ffmpegAvailable()) {
  1154. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  1155. if ($compressed && file_exists($compressed)) {
  1156. $compressedPath = $compressed;
  1157. if (filesize($compressed) < $fileSize || $isVideo) {
  1158. $finalPath = $compressed;
  1159. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  1160. } else {
  1161. @unlink($compressed);
  1162. $compressedPath = null;
  1163. }
  1164. }
  1165. }
  1166. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  1167. $finalSize = filesize($finalPath);
  1168. if ($finalSize > $maxBytes) {
  1169. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  1170. 'path' => $localPath,
  1171. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  1172. 'limit_mb' => 14
  1173. ]);
  1174. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  1175. }
  1176. // 兜底校验:视频时长超过5分钟且未能压缩成功
  1177. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  1178. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  1179. }
  1180. $data = base64_encode(file_get_contents($finalPath));
  1181. return [
  1182. 'mime_type' => $mimeType,
  1183. 'data' => $data
  1184. ];
  1185. } catch (\App\Exceptions\ApiException $e) {
  1186. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  1187. throw $e;
  1188. } catch (\Exception $e) {
  1189. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  1190. return null;
  1191. } finally {
  1192. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  1193. @unlink($compressedPath);
  1194. }
  1195. if ($isTempFile && $localPath && file_exists($localPath)) {
  1196. @unlink($localPath);
  1197. }
  1198. }
  1199. }
  1200. /**
  1201. * 下载远程多媒体到临时目录
  1202. *
  1203. * @return string|null 本地临时文件路径
  1204. */
  1205. private function downloadMediaToTemp($url) {
  1206. try {
  1207. $tempDir = storage_path('app/temp/gemini');
  1208. if (!is_dir($tempDir)) {
  1209. mkdir($tempDir, 0775, true);
  1210. }
  1211. $extension = 'tmp';
  1212. $pathInfo = parse_url($url, PHP_URL_PATH);
  1213. if ($pathInfo) {
  1214. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  1215. if ($ext && strlen($ext) <= 10) {
  1216. $extension = strtolower($ext);
  1217. }
  1218. }
  1219. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  1220. $client = new Client(['timeout' => 300, 'verify' => false]);
  1221. $response = $client->get($url, ['sink' => $tmpFile]);
  1222. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  1223. @unlink($tmpFile);
  1224. return null;
  1225. }
  1226. return $tmpFile;
  1227. } catch (\Exception $e) {
  1228. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  1229. return null;
  1230. }
  1231. }
  1232. /**
  1233. * 检测多媒体文件 MIME 类型
  1234. */
  1235. private function detectMediaMime($filePath) {
  1236. $imageInfo = @getimagesize($filePath);
  1237. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  1238. return $imageInfo['mime'];
  1239. }
  1240. // 视频按扩展名粗略判断
  1241. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  1242. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  1243. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  1244. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  1245. if (isset($videoExts[$ext])) {
  1246. return $videoExts[$ext];
  1247. }
  1248. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  1249. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  1250. if (isset($imageExts[$ext])) {
  1251. return $imageExts[$ext];
  1252. }
  1253. return 'application/octet-stream';
  1254. }
  1255. /**
  1256. * 获取多媒体时长(秒),非视频或失败返回 0
  1257. */
  1258. private function getMediaDuration($filePath) {
  1259. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  1260. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  1261. $output = trim((string)shell_exec($cmd));
  1262. $duration = (float)$output;
  1263. return $duration > 0 ? $duration : 0;
  1264. }
  1265. /**
  1266. * 检查 ffmpeg 是否可用
  1267. */
  1268. private function ffmpegAvailable() {
  1269. static $available = null;
  1270. if ($available !== null) {
  1271. return $available;
  1272. }
  1273. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1274. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  1275. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  1276. $available = false;
  1277. return $available;
  1278. }
  1279. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  1280. $output = shell_exec($cmd);
  1281. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  1282. return $available;
  1283. }
  1284. /**
  1285. * 使用 ffmpeg 压缩多媒体文件
  1286. *
  1287. * @param string $inputFile 输入文件路径
  1288. * @param bool $isVideo 是否为视频
  1289. * @param float $duration 视频时长(秒),非视频传 0
  1290. * @return string|null 压缩后的文件路径,失败返回 null
  1291. */
  1292. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  1293. try {
  1294. $tempDir = storage_path('app/temp/gemini');
  1295. if (!is_dir($tempDir)) {
  1296. mkdir($tempDir, 0775, true);
  1297. }
  1298. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1299. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  1300. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  1301. if ($isVideo) {
  1302. // 视频:时长超过5分钟则加速压缩到5分钟以内
  1303. $speedFactor = 1.0;
  1304. if ($duration > 300) {
  1305. $speedFactor = $duration / 300;
  1306. }
  1307. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  1308. $finalDuration = $duration / max(1.0, $speedFactor);
  1309. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  1310. $targetBitrate = max(300, min(6000, $targetBitrate));
  1311. $filters = [];
  1312. $filters[] = 'scale=min(1280,iw):-2';
  1313. $filters[] = 'fps=24';
  1314. if ($speedFactor > 1.0) {
  1315. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  1316. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  1317. $fullCount = (int)ceil($speedFactor / 2.0);
  1318. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1319. if ($lastTempo < 0.5) {
  1320. $fullCount++;
  1321. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1322. }
  1323. for ($i = 0; $i < $fullCount; $i++) {
  1324. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  1325. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  1326. }
  1327. }
  1328. $filterStr = implode(',', $filters);
  1329. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  1330. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  1331. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  1332. } else {
  1333. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  1334. $imageInfo = @getimagesize($inputFile);
  1335. $scaleW = 2048;
  1336. $scaleH = 2048;
  1337. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  1338. if ($imageInfo[0] >= $imageInfo[1]) {
  1339. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  1340. $scaleW = 2048;
  1341. } else {
  1342. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  1343. $scaleH = 2048;
  1344. }
  1345. }
  1346. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  1347. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  1348. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  1349. }
  1350. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  1351. $output = shell_exec($cmd);
  1352. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  1353. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  1354. 'input' => $inputFile,
  1355. 'output' => $output
  1356. ]);
  1357. @unlink($outputFile);
  1358. return null;
  1359. }
  1360. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  1361. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  1362. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  1363. ]);
  1364. return $outputFile;
  1365. } catch (\Exception $e) {
  1366. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  1367. return null;
  1368. }
  1369. }
  1370. /**
  1371. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  1372. *
  1373. * @param array $data
  1374. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  1375. */
  1376. public function getScriptGenerateTasks($data) {
  1377. $uid = Site::getUid();
  1378. return DB::table('mp_script_generate_tasks as t')
  1379. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  1380. ->where('t.uid', $uid)
  1381. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  1382. ->orderByDesc('t.id')
  1383. ->paginate(15);
  1384. }
  1385. public function saveScriptChatHistory($data) {
  1386. $uid = Site::getUid();
  1387. $rid = getProp($data, 'rid');
  1388. $script_id = getProp($data, 'script_id');
  1389. $sequence = getProp($data, 'sequence', 0);
  1390. $content = getProp($data, 'content');
  1391. if (!$rid) {
  1392. Utils::throwError('20003:请选择对话记录ID');
  1393. }
  1394. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  1395. if (!$record) {
  1396. Utils::throwError('20003:对话记录不存在');
  1397. }
  1398. if (!$script_id) {
  1399. Utils::throwError('20003:请选择剧本');
  1400. }
  1401. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  1402. if (!$script) {
  1403. Utils::throwError('20003:剧本不存在');
  1404. }
  1405. // 批量插入数据
  1406. return DB::table('mp_script_records')->where('id', $rid)->update([
  1407. 'content' => $content,
  1408. 'updated_at' => date('Y-m-d H:i:s')
  1409. ]);
  1410. }
  1411. /**
  1412. * 获取剧本的历史对话记录
  1413. *
  1414. * @param array $data 请求参数
  1415. * @return array 返回历史记录数组
  1416. */
  1417. public function getScriptChatHistory($data) {
  1418. $uid = Site::getUid();
  1419. $script_id = getProp($data, 'script_id');
  1420. $rid = getProp($data, 'rid');
  1421. $sequence = getProp($data, 'sequence', null);
  1422. if (!$script_id) {
  1423. Utils::throwError('20003:请提供剧本ID');
  1424. }
  1425. // 验证剧本是否存在
  1426. $script = DB::table('mp_scripts')
  1427. ->where('id', $script_id)
  1428. ->where('is_deleted', 0)
  1429. ->first();
  1430. if (!$script) {
  1431. Utils::throwError('20003:剧本不存在');
  1432. }
  1433. // 构建查询
  1434. $query = DB::table('mp_script_records')
  1435. ->where('script_id', $script_id);
  1436. // ->where('uid', $uid);
  1437. // 如果提供了 sequence,则过滤指定剧集
  1438. if ($sequence !== null) {
  1439. $query->where('sequence', $sequence);
  1440. }
  1441. // 记录ID筛选
  1442. if ($rid) {
  1443. $query->where('id', $rid);
  1444. }
  1445. // 查询记录并按 id 正序排序
  1446. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  1447. ->orderBy('created_at', 'asc')
  1448. ->orderBy('id', 'asc')
  1449. ->get()
  1450. ->map(function ($record) {
  1451. return [
  1452. 'rid' => $record->id,
  1453. 'script_id' => $record->script_id,
  1454. 'sequence' => $record->sequence,
  1455. 'role' => $record->role,
  1456. 'content' => $record->content,
  1457. 'products' => $record->products ? json_decode($record->products) : [],
  1458. 'created_at' => $record->created_at,
  1459. ];
  1460. })
  1461. ->toArray();
  1462. return $records;
  1463. }
  1464. /**
  1465. * 处理图片转换为base64
  1466. *
  1467. * @param mixed $image 图片文件对象或文件路径
  1468. * @return string|null base64编码的图片数据
  1469. */
  1470. private function processImageToBase64($image) {
  1471. try {
  1472. // 获取文件路径
  1473. if (is_string($image)) {
  1474. $filePath = $image;
  1475. } else {
  1476. // Laravel UploadedFile 对象
  1477. $filePath = $image->getRealPath();
  1478. }
  1479. if (!file_exists($filePath)) {
  1480. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  1481. return null;
  1482. }
  1483. // 验证是否为图片文件
  1484. $imageInfo = @getimagesize($filePath);
  1485. if ($imageInfo === false) {
  1486. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  1487. return null;
  1488. }
  1489. // 读取图片并转换为base64
  1490. $imageData = file_get_contents($filePath);
  1491. $base64Image = base64_encode($imageData);
  1492. dLog('deepseek')->info('图片转换成功', [
  1493. 'size' => strlen($imageData),
  1494. 'type' => $imageInfo['mime']
  1495. ]);
  1496. return $base64Image;
  1497. } catch (\Exception $e) {
  1498. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  1499. return null;
  1500. }
  1501. }
  1502. private function getArtStylePromptMappings($art_style='')
  1503. {
  1504. $arr = [
  1505. '唯美真人风格' => [
  1506. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  1507. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  1508. ],
  1509. '真人古风风格' => [
  1510. 'aliases' => ['真人古风风格', '真人古风'],
  1511. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  1512. ],
  1513. '日系动漫风格' => [
  1514. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  1515. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  1516. ],
  1517. '国漫风格' => [
  1518. 'aliases' => ['国漫风格', '国漫'],
  1519. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  1520. ],
  1521. 'Q版卡通风格' => [
  1522. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  1523. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  1524. ],
  1525. '简约扁平风格' => [
  1526. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  1527. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  1528. ],
  1529. '武侠风格' => [
  1530. 'aliases' => ['武侠风格', '武侠'],
  1531. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  1532. ],
  1533. '古风仙侠风格' => [
  1534. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  1535. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  1536. ],
  1537. '新中式水墨风格' => [
  1538. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  1539. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  1540. ],
  1541. '写实插画风格' => [
  1542. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  1543. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  1544. ],
  1545. '3D卡通风格' => [
  1546. 'aliases' => ['3D卡通风格', '3D卡通'],
  1547. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  1548. ],
  1549. '条漫风格' => [
  1550. 'aliases' => ['条漫风格', '条漫'],
  1551. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  1552. ],
  1553. '赛博朋克风格' => [
  1554. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  1555. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  1556. ],
  1557. '暗黑悬疑风格' => [
  1558. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  1559. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  1560. ],
  1561. '治愈清新风格' => [
  1562. 'aliases' => ['治愈清新风格', '治愈清新'],
  1563. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  1564. ],
  1565. '3D真人风格' => [
  1566. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  1567. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  1568. ],
  1569. ];
  1570. if($art_style) {
  1571. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  1572. }
  1573. return $arr;
  1574. $arr = [
  1575. '唯美真人风格' => [
  1576. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  1577. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  1578. 2. 色彩色调
  1579. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  1580. 3. 画质精度
  1581. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  1582. 4. 画面观感
  1583. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  1584. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  1585. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  1586. ],
  1587. '真人古风风格' => [
  1588. 'aliases' => ['真人古风风格', '真人古风'],
  1589. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  1590. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  1591. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  1592. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  1593. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  1594. ],
  1595. '日系动漫风格' => [
  1596. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  1597. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  1598. 正向提示词(中文)
  1599. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  1600. 必须遵守规则
  1601. • 全程保持日系动漫风格,不混入其他画风
  1602. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  1603. • 画面适配所选画面比例,构图居中,主体突出
  1604. • 线条干净、色彩统一,不杂乱、不突兀
  1605. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  1606. ],
  1607. '国漫风格' => [
  1608. 'aliases' => ['国漫风格', '国漫'],
  1609. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  1610. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  1611. 必须遵守规则
  1612. • 严格保持国漫画风,不串风格、不混画风
  1613. • 角色形象统一,不随意改变五官、身材、服饰
  1614. • 画面构图稳定,适合漫剧叙事展示
  1615. • 色调统一,不出现脏色、杂色
  1616. 禁止/避免词汇
  1617. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  1618. ],
  1619. 'Q版卡通风格' => [
  1620. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  1621. 'prompt' => "风格说明
  1622. 头大身小,造型可爱圆润,简约干净
  1623. 正向提示词(中文)
  1624. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  1625. 必须遵守规则
  1626. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  1627. • 角色造型统一,表情可爱,不诡异
  1628. • 画面简洁清爽,无多余复杂元素
  1629. • 色彩明亮柔和,不刺眼
  1630. 禁止/避免词汇
  1631. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  1632. ],
  1633. '简约扁平风格' => [
  1634. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  1635. 'prompt' => "风格说明
  1636. 色块简洁、无复杂渐变,现代极简风
  1637. 正向提示词(中文)
  1638. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  1639. 必须遵守规则
  1640. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  1641. • 构图简洁,主体突出,无多余装饰
  1642. • 色彩统一、干净,不杂乱
  1643. 禁止/避免词汇
  1644. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  1645. ],
  1646. '武侠风格' => [
  1647. 'aliases' => ['武侠风格', '武侠'],
  1648. 'prompt' => "风格说明
  1649. 江湖气息,线条硬朗,动作感强
  1650. 正向提示词(中文)
  1651. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  1652. 必须遵守规则
  1653. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  1654. • 角色形象、服饰、身材比例统一
  1655. • 画面动作自然,不扭曲、不畸形
  1656. 禁止/避免词汇
  1657. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  1658. ],
  1659. '古风仙侠风格' => [
  1660. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  1661. 'prompt' => "风格说明
  1662. 飘逸汉服、云雾仙气、唯美空灵
  1663. 正向提示词(中文)
  1664. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  1665. 必须遵守规则
  1666. • 保持古风仙侠统一画风,不混入现代、科幻元素
  1667. • 角色服饰、发型、形象前后一致
  1668. • 场景仙气飘逸,色调清雅统一
  1669. • 画面唯美柔和,不阴暗、不诡异
  1670. 禁止/避免词汇
  1671. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  1672. ],
  1673. '新中式水墨风格' => [
  1674. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  1675. 'prompt' => "风格说明
  1676. 淡墨渲染,毛笔笔触,留白意境
  1677. 正向提示词(中文)
  1678. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  1679. 必须遵守规则
  1680. • 严格保持水墨质感,不混入厚涂、写实、卡通
  1681. • 色调淡雅统一,不浓艳杂乱
  1682. • 画面干净有意境,不堆砌元素
  1683. 禁止/避免词汇
  1684. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  1685. ],
  1686. '写实插画风格' => [
  1687. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  1688. 'prompt' => "风格说明
  1689. 接近真人比例,光影真实,质感细腻
  1690. 正向提示词(中文)
  1691. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  1692. 必须遵守规则
  1693. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  1694. • 角色五官、身材、服饰高度统一
  1695. • 画面清晰、光影自然、不扭曲
  1696. 禁止/避免词汇
  1697. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  1698. ],
  1699. '3D卡通风格' => [
  1700. 'aliases' => ['3D卡通风格', '3D卡通'],
  1701. 'prompt' => "风格说明
  1702. 3D建模质感,柔和渲染,圆润可爱
  1703. 正向提示词(中文)
  1704. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  1705. 必须遵守规则
  1706. • 保持3D卡通统一质感,不出现2D杂乱线条
  1707. • 角色模型、比例、形象前后一致
  1708. • 画面干净,不模糊、不穿模
  1709. 禁止/避免词汇
  1710. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  1711. ],
  1712. '条漫风格' => [
  1713. 'aliases' => ['条漫风格', '条漫'],
  1714. 'prompt' => "风格说明
  1715. 纵向分镜,上下滑动阅读,轻量化
  1716. 正向提示词(中文)
  1717. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  1718. 必须遵守规则
  1719. • 保持条漫纵向阅读逻辑,构图简洁
  1720. • 画风统一,不混写实、3D、水墨
  1721. • 画面干净,不杂乱
  1722. 禁止/避免词汇
  1723. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  1724. ],
  1725. '赛博朋克风格' => [
  1726. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  1727. 'prompt' => "风格说明
  1728. 霓虹灯光、未来都市、暗色调、科技机械
  1729. 正向提示词(中文)
  1730. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  1731. 必须遵守规则
  1732. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  1733. • 色调以暗调+霓虹为主,色彩统一
  1734. • 画面科技感强,不杂乱
  1735. 禁止/避免词汇
  1736. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  1737. ],
  1738. '暗黑悬疑风格' => [
  1739. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  1740. 'prompt' => "风格说明
  1741. 低饱和、冷色调、阴影重、神秘压抑
  1742. 正向提示词(中文)
  1743. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  1744. 必须遵守规则
  1745. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  1746. • 画面氛围压抑神秘,但不低俗、不血腥
  1747. • 角色形象统一,不崩坏
  1748. 禁止/避免词汇
  1749. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  1750. ],
  1751. '治愈清新风格' => [
  1752. 'aliases' => ['治愈清新风格', '治愈清新'],
  1753. 'prompt' => "风格说明
  1754. 马卡龙色系、柔光、温暖干净
  1755. 正向提示词(中文)
  1756. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  1757. 必须遵守规则
  1758. • 保持治愈清新统一色调,不阴暗、不诡异
  1759. • 画面柔和干净,无杂乱元素
  1760. • 角色形象柔和可爱,不狰狞
  1761. 禁止/避免词汇
  1762. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  1763. ],
  1764. ];
  1765. return $arr;
  1766. }
  1767. public function getArtStylePromptByInput($inputArtStyle): string
  1768. {
  1769. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  1770. if ($normalizedInput === '') {
  1771. return '';
  1772. }
  1773. return $this->getArtStylePromptMappings($normalizedInput);
  1774. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  1775. // foreach ($mapping['aliases'] as $alias) {
  1776. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  1777. // if ($normalizedAlias === '') {
  1778. // continue;
  1779. // }
  1780. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  1781. // return $mapping['prompt'];
  1782. // }
  1783. // }
  1784. // }
  1785. return '';
  1786. }
  1787. public function getArtStyleShortPromptByInput($inputArtStyle) {
  1788. $stylePrefixes = [
  1789. '唯美真人风格' => [
  1790. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  1791. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  1792. ],
  1793. '真人古风风格' => [
  1794. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  1795. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  1796. ],
  1797. '日系动漫风格' => [
  1798. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  1799. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  1800. ],
  1801. '国漫风格' => [
  1802. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  1803. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  1804. ],
  1805. 'Q版卡通风格' => [
  1806. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  1807. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  1808. ],
  1809. '简约扁平风格' => [
  1810. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  1811. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  1812. ],
  1813. '武侠风格' => [
  1814. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  1815. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  1816. ],
  1817. '古风仙侠风格' => [
  1818. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  1819. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  1820. ],
  1821. '新中式水墨风格' => [
  1822. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  1823. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  1824. ],
  1825. '写实插画风格' => [
  1826. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  1827. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  1828. ],
  1829. '3D卡通风格' => [
  1830. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  1831. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  1832. ],
  1833. '条漫风格' => [
  1834. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  1835. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  1836. ],
  1837. '赛博朋克风格' => [
  1838. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  1839. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  1840. ],
  1841. '暗黑悬疑风格' => [
  1842. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  1843. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  1844. ],
  1845. '治愈清新风格' => [
  1846. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  1847. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  1848. ]
  1849. ];
  1850. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  1851. }
  1852. private function normalizeArtStyleInput($value): string
  1853. {
  1854. $value = trim((string)$value);
  1855. if ($value === '') {
  1856. return '';
  1857. }
  1858. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  1859. return mb_strtolower($value, 'UTF-8');
  1860. }
  1861. private function replaceArtStyleSection(string $content, string $artStyle): string
  1862. {
  1863. if ($content === '' || $artStyle === '') {
  1864. return $content;
  1865. }
  1866. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  1867. if (!preg_match($pattern, $content)) {
  1868. return $content;
  1869. }
  1870. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  1871. }
  1872. /**
  1873. * DeepSeek流式输出处理方法
  1874. *
  1875. * @param array $post_data DeepSeek API请求参数
  1876. * @return \Generator 返回生成器,用于流式输出
  1877. */
  1878. private function deepSeekStreamResponse($post_data) {
  1879. // 设置最大输出tokens
  1880. $post_data['max_tokens'] = 300000;
  1881. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1882. $response = $client->post($this->url, [
  1883. 'json' => $post_data,
  1884. 'headers' => $this->headers,
  1885. 'stream' => true // 启用流式响应
  1886. ]);
  1887. $body = $response->getBody();
  1888. $fullContent = '';
  1889. $fullReasoningContent = '';
  1890. $usage = [];
  1891. $buffer = '';
  1892. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1893. // 逐行读取流式响应
  1894. while (!$body->eof()) {
  1895. $chunk = $body->read(1024); // 每次读取 1KB
  1896. $buffer .= $chunk;
  1897. // 按行分割
  1898. $lines = explode("\n", $buffer);
  1899. // 保留最后一个不完整的行
  1900. $buffer = array_pop($lines);
  1901. foreach ($lines as $line) {
  1902. $line = trim($line);
  1903. // 跳过空行
  1904. if (empty($line)) {
  1905. continue;
  1906. }
  1907. // 检查是否是 SSE 数据行
  1908. if (strpos($line, 'data: ') !== 0) {
  1909. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1910. continue;
  1911. }
  1912. $data = substr($line, 6); // 移除 "data: " 前缀
  1913. if ($data === '[DONE]') {
  1914. dLog('deepseek')->info('收到结束标记');
  1915. break 2; // 跳出两层循环
  1916. }
  1917. try {
  1918. $json = json_decode($data, true);
  1919. if (json_last_error() !== JSON_ERROR_NONE) {
  1920. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1921. continue;
  1922. }
  1923. if (isset($json['choices'][0]['delta'])) {
  1924. $delta = $json['choices'][0]['delta'];
  1925. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1926. if (isset($delta['reasoning_content'])) {
  1927. $fullReasoningContent .= $delta['reasoning_content'];
  1928. yield [
  1929. 'type' => 'reasoning',
  1930. 'content' => $delta['reasoning_content'],
  1931. 'full_reasoning' => $fullReasoningContent
  1932. ];
  1933. }
  1934. // 处理最终回答内容
  1935. if (isset($delta['content'])) {
  1936. $fullContent .= $delta['content'];
  1937. yield [
  1938. 'type' => 'content',
  1939. 'content' => $delta['content'],
  1940. ];
  1941. }
  1942. }
  1943. // 获取使用统计信息
  1944. if (isset($json['usage'])) {
  1945. $usage = $json['usage'];
  1946. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1947. }
  1948. } catch (\Exception $e) {
  1949. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1950. continue;
  1951. }
  1952. }
  1953. }
  1954. dLog('deepseek')->info('流式读取完成', [
  1955. 'content_length' => strlen($fullContent),
  1956. 'reasoning_length' => strlen($fullReasoningContent)
  1957. ]);
  1958. yield [
  1959. 'type' => 'done',
  1960. 'full_content' => $fullContent,
  1961. 'full_reasoning' => $fullReasoningContent,
  1962. 'usage' => $usage
  1963. ];
  1964. }
  1965. /**
  1966. * GPT 重试次数(env 可配置,默认 5 次)
  1967. */
  1968. private function gptRetryTimes()
  1969. {
  1970. return (int)env('GPT_RETRY_TIMES', 5);
  1971. }
  1972. /**
  1973. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  1974. */
  1975. private function gptRetryInterval()
  1976. {
  1977. return (int)env('GPT_RETRY_INTERVAL', 10);
  1978. }
  1979. /**
  1980. * 判断 GPT 请求异常是否可重试
  1981. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  1982. */
  1983. private function isGptRetryableException(\Exception $e)
  1984. {
  1985. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  1986. return false;
  1987. }
  1988. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1989. $status = $e->getResponse()->getStatusCode();
  1990. return $status >= 500 || $status == 429;
  1991. }
  1992. return true;
  1993. }
  1994. /**
  1995. * GPT 中转站探活:GET /v1/models,5 秒短超时
  1996. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  1997. */
  1998. private function checkGptServiceAvailable()
  1999. {
  2000. $apiKey = env('GPT_54_API_KEY');
  2001. if (empty($apiKey)) {
  2002. return false;
  2003. }
  2004. try {
  2005. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  2006. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  2007. 'headers' => [
  2008. 'Authorization' => 'Bearer ' . $apiKey,
  2009. 'Content-Type' => 'application/json'
  2010. ]
  2011. ]);
  2012. $status = $response->getStatusCode();
  2013. return $status < 500 && $status != 429;
  2014. } catch (\Exception $e) {
  2015. return false;
  2016. }
  2017. }
  2018. /**
  2019. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  2020. * 全部失败抛出友好错误
  2021. */
  2022. private function ensureGptServiceAvailable()
  2023. {
  2024. $maxRetries = $this->gptRetryTimes();
  2025. $interval = $this->gptRetryInterval();
  2026. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  2027. if ($this->checkGptServiceAvailable()) {
  2028. return;
  2029. }
  2030. if ($attempt < $maxRetries) {
  2031. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  2032. 'retry' => $attempt + 1,
  2033. 'max_retries' => $maxRetries
  2034. ]);
  2035. sleep($interval);
  2036. }
  2037. }
  2038. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  2039. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  2040. 'max_retries' => $maxRetries,
  2041. 'interval' => $interval
  2042. ]);
  2043. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  2044. }
  2045. /**
  2046. * GPT 流式输出处理方法
  2047. *
  2048. * @param array $post_data GPT API请求参数
  2049. * @return \Generator 返回生成器,用于流式输出
  2050. */
  2051. private function gpt54StreamResponse($post_data) {
  2052. $apiKey = env('GPT_54_API_KEY');
  2053. if (empty($apiKey)) {
  2054. Utils::throwError('20003:GPT API Key未配置');
  2055. }
  2056. // 先探活,服务不可用时自动重试
  2057. $this->ensureGptServiceAvailable();
  2058. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2059. $headers = [
  2060. 'Authorization' => 'Bearer ' . $apiKey,
  2061. 'Content-Type' => 'application/json'
  2062. ];
  2063. // 移除 thinking 参数,GPT-5.4 不支持
  2064. if (isset($post_data['thinking'])) {
  2065. unset($post_data['thinking']);
  2066. }
  2067. if (isset($post_data['reasoning_effort'])) {
  2068. unset($post_data['reasoning_effort']);
  2069. }
  2070. $post_data['max_completion_tokens'] = 100000;
  2071. $maxRetries = $this->gptRetryTimes();
  2072. $interval = $this->gptRetryInterval();
  2073. $attempt = 0;
  2074. while (true) {
  2075. $fullContent = '';
  2076. $usage = [];
  2077. $buffer = '';
  2078. try {
  2079. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  2080. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  2081. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  2082. 'json' => $post_data,
  2083. 'headers' => $headers,
  2084. 'stream' => true // 启用流式响应
  2085. ]);
  2086. $body = $response->getBody();
  2087. dLog('deepseek')->info('开始读取 GPT 流式响应');
  2088. // 逐行读取流式响应
  2089. while (!$body->eof()) {
  2090. $chunk = $body->read(1024); // 每次读取 1KB
  2091. $buffer .= $chunk;
  2092. // 按行分割
  2093. $lines = explode("\n", $buffer);
  2094. // 保留最后一个不完整的行
  2095. $buffer = array_pop($lines);
  2096. foreach ($lines as $line) {
  2097. $line = trim($line);
  2098. // 跳过空行
  2099. if (empty($line)) {
  2100. continue;
  2101. }
  2102. // 检查是否是 SSE 数据行
  2103. if (strpos($line, 'data: ') !== 0) {
  2104. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2105. continue;
  2106. }
  2107. $data = substr($line, 6); // 移除 "data: " 前缀
  2108. if ($data === '[DONE]') {
  2109. dLog('deepseek')->info('收到结束标记');
  2110. break 2; // 跳出 foreach 和流读取循环
  2111. }
  2112. try {
  2113. $json = json_decode($data, true);
  2114. if (json_last_error() !== JSON_ERROR_NONE) {
  2115. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2116. continue;
  2117. }
  2118. if (isset($json['choices'][0]['delta'])) {
  2119. $delta = $json['choices'][0]['delta'];
  2120. // 处理回答内容
  2121. if (isset($delta['content'])) {
  2122. $fullContent .= $delta['content'];
  2123. yield [
  2124. 'type' => 'content',
  2125. 'content' => $delta['content'],
  2126. ];
  2127. }
  2128. }
  2129. // 获取使用统计信息
  2130. if (isset($json['usage'])) {
  2131. $usage = $json['usage'];
  2132. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2133. }
  2134. } catch (\Exception $e) {
  2135. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2136. continue;
  2137. }
  2138. }
  2139. }
  2140. dLog('deepseek')->info('流式读取完成', [
  2141. 'content_length' => strlen($fullContent)
  2142. ]);
  2143. yield [
  2144. 'type' => 'done',
  2145. 'full_content' => $fullContent,
  2146. 'full_reasoning' => '',
  2147. 'usage' => $usage
  2148. ];
  2149. return;
  2150. } catch (\Exception $e) {
  2151. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  2152. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  2153. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  2154. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  2155. throw $e;
  2156. }
  2157. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  2158. 'retry' => $attempt + 1,
  2159. 'max_retries' => $maxRetries,
  2160. 'error' => $e->getMessage()
  2161. ]);
  2162. sleep($interval);
  2163. $attempt++;
  2164. }
  2165. }
  2166. }
  2167. // 与推理模型对话
  2168. public function chatWithReasoner($data) {
  2169. $content = getProp($data, 'content');
  2170. $model = getProp($data, 'model', 'r1');
  2171. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2172. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2173. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2174. if ($model == 'r1') {
  2175. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  2176. $thinkingMode = 'disabled';
  2177. } else {
  2178. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  2179. $thinkingMode = 'disabled';
  2180. }
  2181. // 获取可选情感(根据音色可支持情感选)
  2182. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  2183. $emotion_list = [];
  2184. foreach ($timbre_emotion as $emotion) {
  2185. $tmp = explode(',', $emotion);
  2186. $emotion_list = array_merge($emotion_list, $tmp);
  2187. }
  2188. $emotion_list = array_unique($emotion_list);
  2189. $emotion_str = implode('、', $emotion_list);
  2190. // // 获取可选情感
  2191. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  2192. // $emotion_str = implode('、', $emotion_list);
  2193. // 是否启用情感
  2194. $enable_emotion = getProp($data, 'enable_emotion', 0);
  2195. if ($enable_emotion) {
  2196. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  2197. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2198. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  2199. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  2200. }else {
  2201. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  2202. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2203. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  2204. }
  2205. $messages = [
  2206. [
  2207. 'role' => 'system',
  2208. 'content' => $sys_content
  2209. ],
  2210. [
  2211. 'role' => 'user',
  2212. 'content' => $content
  2213. ]
  2214. ];
  2215. $post_data = [
  2216. 'model' => $model,
  2217. 'messages' => $messages,
  2218. // 'max_tokens' => 8192,
  2219. 'temperature' => 1,
  2220. 'frequency_penalty' => 0,
  2221. 'presence_penalty' => 0,
  2222. 'thinking' => ['type' => $thinkingMode],
  2223. 'response_format' => [
  2224. 'type' => 'text'
  2225. ],
  2226. 'stream' => false
  2227. ];
  2228. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2229. // 根据模型类型选择调用方法
  2230. $fullContent = '';
  2231. $usage = [];
  2232. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2233. // DeepSeek 官方模型使用 DeepSeek API
  2234. $chatResult = $this->chatOnly($post_data);
  2235. } else if (in_array($model, $this->gpt_text_models)) {
  2236. // GPT-5.4 模型使用 TokenRouter API
  2237. $chatResult = $this->gpt54ChatOnly($post_data);
  2238. } else {
  2239. // 其他模型使用火山引擎API
  2240. $chatResult = $this->volcEngineChatCompletion($post_data);
  2241. }
  2242. if (is_array($chatResult)) {
  2243. $fullContent = $chatResult['fullContent'];
  2244. $usage = $chatResult['usage'];
  2245. }
  2246. // 处理获取到的剧本数据
  2247. $script_content = handleScriptWords($fullContent, $enable_emotion);
  2248. $result = [
  2249. 'origin_content' => $fullContent,
  2250. 'roles' => getProp($script_content, 'roles'),
  2251. 'words' => getProp($script_content, 'words'),
  2252. ];
  2253. return $result;
  2254. }
  2255. public function resetParagraphAudio($data) {
  2256. $bid = getProp($data, 'bid');
  2257. $cid = getProp($data, 'cid');
  2258. $version_id = getProp($data, 'version_id');
  2259. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  2260. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  2261. 'generate_status' => '待制作',
  2262. 'updated_at' => date('Y-m-d H:i:s')
  2263. ]);
  2264. }
  2265. public function saveParagraphAudio($data) {
  2266. $bid = getProp($data, 'bid');
  2267. $cid = getProp($data, 'cid');
  2268. $version_id = getProp($data, 'version_id');
  2269. $sequence = getProp($data, 'sequence');
  2270. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  2271. // 获取所有情感
  2272. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  2273. $emotion_list = array_flip($emotion_list);
  2274. // 获取音色支持情感
  2275. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  2276. $timbre_emotion = explode(',', $timbre_emotion);
  2277. $emotion = getProp($data, 'emotion');
  2278. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  2279. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  2280. $list = [
  2281. 'bid' => $bid,
  2282. 'cid' => $cid,
  2283. 'version_id' => $version_id,
  2284. 'sequence' => $sequence,
  2285. 'role' => getProp($data, 'role'),
  2286. 'gender' => getProp($data, 'gender'),
  2287. 'text' => trim(getProp($data, 'text')),
  2288. 'emotion' => $emotion,
  2289. 'emotion_type' => $emotion_type,
  2290. 'voice_type' => getProp($data, 'voice_type'),
  2291. 'voice_name' => getProp($data, 'voice_name'),
  2292. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  2293. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  2294. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  2295. 'pitch' => getProp($data, 'pitch', 0),
  2296. // 'paragraph_audio_url' => '',
  2297. 'generate_status' => '制作中',
  2298. 'error_msg' => '',
  2299. 'updated_at' => date('Y-m-d H:i:s')
  2300. ];
  2301. $continue = false;
  2302. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  2303. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  2304. $list['generate_status'] = '制作成功';
  2305. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2306. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  2307. $continue = true;
  2308. }
  2309. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  2310. if ($id) {
  2311. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  2312. }else {
  2313. $list['created_at'] = date('Y-m-d H:i:s');
  2314. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  2315. $boolen = $id ? true : false;
  2316. }
  2317. // 如果更新成功则加入查询队列
  2318. if ($boolen) {
  2319. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  2320. Redis::sadd($redis_key, $id);
  2321. }
  2322. if ($boolen && !$continue) {
  2323. $boolen = false;
  2324. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2325. // 根据ID通过API通知合成音频
  2326. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  2327. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  2328. $response = $result->getBody()->getContents();
  2329. $response_arr = json_decode($response, true);
  2330. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2331. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2332. Log::info('通知火山生成段落音频失败: '.$error_msg);
  2333. Utils::throwError('20003:通知火山生成段落音频失败');
  2334. }
  2335. $boolen = true;
  2336. }
  2337. return $boolen;
  2338. }
  2339. public function insertAudioEffect($data) {
  2340. $audio_id = getProp($data, 'audio_id');
  2341. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2342. $bid = getProp($chapter_audio, 'bid');
  2343. $version_id = getProp($chapter_audio, 'version_id');
  2344. $cid = getProp($chapter_audio, 'cid');
  2345. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2346. $audio_effect_json = getProp($data, 'audio_effect_json');
  2347. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  2348. try {
  2349. DB::beginTransaction();
  2350. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2351. if (!$count) {
  2352. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2353. }else {
  2354. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2355. }
  2356. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2357. 'audio_effect_status' => '添加中',
  2358. 'audio_effect_json' => $audio_effect_json,
  2359. 'updated_at' => date('Y-m-d H:i:s')
  2360. ]);
  2361. if (!$boolen1) {
  2362. DB::rollBack();
  2363. Utils::throwError('20003:更新生成数据失败');
  2364. }
  2365. $id = DB::table('mp_audio_tasks')->insertGetId([
  2366. 'audio_id' => $audio_id,
  2367. 'generate_status' => '执行中',
  2368. 'generate_json' => json_encode([], 256),
  2369. 'bid' => $bid,
  2370. 'book_name' => getProp($chapter_audio, 'book_name'),
  2371. 'version_id' => $version_id,
  2372. 'version_name' => getProp($chapter_audio, 'version_name'),
  2373. 'cid' => $cid,
  2374. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2375. 'task_name' => $task_name,
  2376. 'created_at' => date('Y-m-d H:i:s'),
  2377. 'updated_at' => date('Y-m-d H:i:s')
  2378. ]);
  2379. if (!$id) {
  2380. DB::rollBack();
  2381. Utils::throwError('20003:创建任务失败');
  2382. }
  2383. }catch (\Exception $e) {
  2384. DB::rollBack();
  2385. Utils::throwError('20003:'.$e->getMessage());
  2386. }
  2387. DB::commit();
  2388. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2389. // 根据ID通过API通知合成音频
  2390. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2391. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2392. $response = $result->getBody()->getContents();
  2393. $response_arr = json_decode($response, true);
  2394. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2395. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2396. Log::info('通知火山插入音效失败: '.$error_msg);
  2397. Utils::throwError('20003:通知火山插入音效失败');
  2398. }
  2399. return true;
  2400. }
  2401. public function insertBgm($data) {
  2402. $audio_id = getProp($data, 'audio_id');
  2403. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2404. $bid = getProp($chapter_audio, 'bid');
  2405. $version_id = getProp($chapter_audio, 'version_id');
  2406. $cid = getProp($chapter_audio, 'cid');
  2407. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2408. $bgm_json = getProp($data, 'bgm_json');
  2409. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2410. if (!$bgm_json) {
  2411. $bgm_json = getProp($data, 'audio_effect_json');
  2412. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2413. }
  2414. try {
  2415. DB::beginTransaction();
  2416. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2417. if (!$count) {
  2418. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2419. }else {
  2420. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2421. }
  2422. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2423. 'bgm_status' => '添加中',
  2424. 'bgm_json' => $bgm_json,
  2425. 'updated_at' => date('Y-m-d H:i:s')
  2426. ]);
  2427. if (!$boolen1) {
  2428. DB::rollBack();
  2429. Utils::throwError('20003:更新生成数据失败');
  2430. }
  2431. $id = DB::table('mp_audio_tasks')->insertGetId([
  2432. 'audio_id' => $audio_id,
  2433. 'generate_status' => '执行中',
  2434. 'generate_json' => json_encode([], 256),
  2435. 'bid' => $bid,
  2436. 'book_name' => getProp($chapter_audio, 'book_name'),
  2437. 'version_id' => $version_id,
  2438. 'version_name' => getProp($chapter_audio, 'version_name'),
  2439. 'cid' => $cid,
  2440. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2441. 'task_name' => $task_name,
  2442. 'created_at' => date('Y-m-d H:i:s'),
  2443. 'updated_at' => date('Y-m-d H:i:s')
  2444. ]);
  2445. if (!$id) {
  2446. DB::rollBack();
  2447. Utils::throwError('20003:创建任务失败');
  2448. }
  2449. }catch (\Exception $e) {
  2450. DB::rollBack();
  2451. Utils::throwError('20003:'.$e->getMessage());
  2452. }
  2453. DB::commit();
  2454. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2455. // 根据ID通过API通知合成音频
  2456. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2457. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2458. $response = $result->getBody()->getContents();
  2459. $response_arr = json_decode($response, true);
  2460. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2461. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2462. Log::info('通知火山插入bgm失败: '.$error_msg);
  2463. Utils::throwError('20003:通知火山插入bgm失败');
  2464. }
  2465. return true;
  2466. }
  2467. public function getParagraphAudios($data) {
  2468. $bid = getProp($data, 'bid');
  2469. $cid = getProp($data, 'cid');
  2470. $version_id = getProp($data, 'version_id');
  2471. $sequence = getProp($data, 'sequence');
  2472. // 获取已生成的音频
  2473. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  2474. if ($sequence) $query->where('sequence', $sequence);
  2475. $paragraph_audios = $query->orderBy('sequence')->get();
  2476. $result = [];
  2477. foreach($paragraph_audios as $item) {
  2478. $result[] = [
  2479. 'sequence' => getProp($item, 'sequence'),
  2480. 'role' => getProp($item, 'role'),
  2481. 'gender' => getProp($item, 'gender'),
  2482. 'text' => trim(getProp($item, 'text')),
  2483. 'emotion' => getProp($item, 'emotion'),
  2484. 'emotion_type' => getProp($item, 'emotion_type'),
  2485. 'voice_type' => getProp($item, 'voice_type'),
  2486. 'voice_name' => getProp($item, 'voice_name'),
  2487. 'speed_ratio' => getProp($item, 'speed_ratio'),
  2488. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  2489. 'emotion_scale' => getProp($item, 'emotion_scale'),
  2490. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  2491. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  2492. ];
  2493. }
  2494. return $result;
  2495. }
  2496. // 新增合成任务
  2497. public function addGenerateTask($data) {
  2498. $bid = getProp($data, 'bid');
  2499. $cid = getProp($data, 'cid');
  2500. $version_id = getProp($data, 'version_id');
  2501. $generate_json = getProp($data, 'generate_json');
  2502. // 获取已生成的音频
  2503. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  2504. $paragraph_list = [];
  2505. foreach($paragraph_audios as $item) {
  2506. $paragraph_list[getProp($item, 'sequence')] = [
  2507. 'role' => getProp($item, 'role'),
  2508. 'gender' => getProp($item, 'gender'),
  2509. 'text' => trim(getProp($item, 'text')),
  2510. 'emotion' => getProp($item, 'emotion'),
  2511. 'emotion_type' => getProp($item, 'emotion_type'),
  2512. 'voice_type' => getProp($item, 'voice_type'),
  2513. 'voice_name' => getProp($item, 'voice_name'),
  2514. 'speed_ratio' => getProp($item, 'speed_ratio'),
  2515. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  2516. 'emotion_scale' => getProp($item, 'emotion_scale'),
  2517. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  2518. ];
  2519. }
  2520. // 更新角色-音色信息
  2521. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  2522. $existed_role_info = json_decode($existed_role_info, true);
  2523. if (!$existed_role_info) $existed_role_info = [];
  2524. // 获取情感信息
  2525. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  2526. $emotion_list = array_flip($emotion_list);
  2527. // 获取音色对应情感组
  2528. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  2529. $timbre_emotion_list = [];
  2530. foreach($timbre_emotions as $item) {
  2531. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  2532. }
  2533. // 构造生成音频的json
  2534. $words = json_decode($generate_json, true);
  2535. // 最终合成前的参数组
  2536. $mp_chapter_paragraph_audios = [];
  2537. $sequence = 1;
  2538. $complete_paragraph_sequences = [];
  2539. foreach($words as &$word) {
  2540. if (!isset($word['text']) || !isset($word['emotion']) || !isset($word['voice_type']) || !isset($word['voice_name']) || !isset($word['speed_ratio']) || !isset($word['loudness_ratio']) || !isset($word['emotion_scale'])) Utils::throwError('20003:参数格式有误');
  2541. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  2542. $role = getProp($word, 'role');
  2543. $word['gender'] = (int)$word['gender'];
  2544. // 判断音色对应情感是否支持,不支持则调整为中性
  2545. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  2546. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  2547. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  2548. if (isset($emotion_list[getProp($word, 'emotion')])) {
  2549. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  2550. }else {
  2551. $word['emotion'] = '中性';
  2552. $word['emotion_type'] = 'neutral';
  2553. }
  2554. $existed_role_info[$role] = [
  2555. 'timbre_type' => $word['voice_type'],
  2556. 'timbre_name' => $word['voice_name'],
  2557. 'emotion' => $word['emotion'],
  2558. 'emotion_type' => $word['emotion_type'],
  2559. 'speed_ratio' => $word['speed_ratio'],
  2560. 'loudness_ratio'=> $word['loudness_ratio'],
  2561. 'emotion_scale' => $word['emotion_scale'],
  2562. 'pitch' => $word['pitch']
  2563. ];
  2564. $word['paragraph_audio_url'] = '';
  2565. // 判断生成参数是否相同,相同则直接使用已生成的音频
  2566. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  2567. // 如果音频存在并且参数都未改变则使用已生成的音频
  2568. if (getProp($paragraph, 'paragraph_audio_url')) {
  2569. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  2570. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  2571. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  2572. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  2573. // {
  2574. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  2575. // }
  2576. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  2577. }
  2578. $tmp = $word;
  2579. // 组装章节分句音频数据
  2580. // $tmp['sequence'] = getProp($word, 'sequence');
  2581. // $tmp['text'] = getProp($word, 'text');
  2582. // $tmp['emotion'] = getProp($word, 'emotion');
  2583. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  2584. // $tmp['voice_name'] = getProp($word, 'voice_name');
  2585. // $tmp['voice_type'] = getProp($word, 'voice_type');
  2586. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  2587. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  2588. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  2589. $tmp['bid'] = $bid;
  2590. $tmp['version_id'] = $version_id;
  2591. $tmp['cid'] = $cid;
  2592. $tmp['sequence'] = $sequence;
  2593. $tmp['created_at'] = date('Y-m-d H:i:s');
  2594. $tmp['updated_at'] = date('Y-m-d H:i:s');
  2595. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  2596. $mp_chapter_paragraph_audios[] = $tmp;
  2597. $complete_paragraph_sequences[] = $sequence;
  2598. $sequence++;
  2599. }
  2600. $generate_json = json_encode($words, 256);
  2601. // 判断是否有未生成字幕的段落
  2602. $no_subtitle_sequences = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->whereIn('sequence', $complete_paragraph_sequences)->whereNull('subtitle_info')->pluck('sequence')->toArray();
  2603. if ($no_subtitle_sequences) {
  2604. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  2605. }
  2606. try {
  2607. DB::beginTransaction();
  2608. $role_info = json_encode($existed_role_info, 256);
  2609. $boolen = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->update(['role_info' => $role_info, 'updated_at' => date('Y-m-d H:i:s')]);
  2610. if (!$boolen) {
  2611. DB::rollBack();
  2612. Utils::throwError('20003:更新角色信息失败');
  2613. }
  2614. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  2615. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  2616. if (!$count) {
  2617. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2618. }else {
  2619. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2620. }
  2621. $boolen1 = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->update(['generate_status'=>'制作中', 'generate_json' => $generate_json, 'updated_at' => date('Y-m-d H:i:s')]);
  2622. if (!$boolen1) {
  2623. DB::rollBack();
  2624. Utils::throwError('20003:更新生成数据失败');
  2625. }
  2626. $id = DB::table('mp_audio_tasks')->insertGetId([
  2627. 'audio_id' => getProp($chapter_audio, 'id'),
  2628. 'generate_status' => '执行中',
  2629. 'generate_json' => $generate_json,
  2630. 'bid' => $bid,
  2631. 'book_name' => getProp($chapter_audio, 'book_name'),
  2632. 'version_id' => $version_id,
  2633. 'version_name' => getProp($chapter_audio, 'version_name'),
  2634. 'cid' => $cid,
  2635. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2636. 'task_name' => $task_name,
  2637. 'created_at' => date('Y-m-d H:i:s'),
  2638. 'updated_at' => date('Y-m-d H:i:s')
  2639. ]);
  2640. if (!$id) {
  2641. DB::rollBack();
  2642. Utils::throwError('20003:创建任务失败');
  2643. }
  2644. // 删除不在段落序号范围内的其他数据
  2645. if ($complete_paragraph_sequences) {
  2646. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  2647. }
  2648. // // 删除章节分句音频数据并重新插入
  2649. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  2650. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  2651. // if (!$boolen3) {
  2652. // DB::rollBack();
  2653. // Utils::throwError('20003:更新章节分句音频失败');
  2654. // }
  2655. } catch (\Exception $e) {
  2656. DB::rollBack();
  2657. Utils::throwError('20003:'.$e->getMessage());
  2658. }
  2659. DB::commit();
  2660. // 通知火山生成音频
  2661. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2662. // 根据ID通过API通知合成音频
  2663. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  2664. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  2665. $response = $result->getBody()->getContents();
  2666. $response_arr = json_decode($response, true);
  2667. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2668. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2669. Log::info('通知火山生成音频失败: '.$error_msg);
  2670. Utils::throwError('20003:通知火山生成音频失败');
  2671. }
  2672. return true;
  2673. }
  2674. public function timbreList($data) {
  2675. $gender = getProp($data, 'gender');
  2676. $timbre_name = getProp($data, 'voice_name');
  2677. $category_id = getProp($data, 'category_id');
  2678. $age_stage = getProp($data, 'age_stage');
  2679. $query = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_name as voice_name', 'timbre_type as voice_type', 'gender', 'age_stage', 'language', 'emotion', 'label', 'first_category_id', 'first_category_name', 'second_category_id', 'second_category_name', 'third_category_id', 'third_category_name', 'audio_url');
  2680. if ($gender) {
  2681. $query->where('gender', $gender);
  2682. }
  2683. if ($timbre_name) {
  2684. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  2685. }
  2686. if ($category_id) {
  2687. $query->where(function ($query) use ($category_id) {
  2688. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  2689. });
  2690. }
  2691. if ($age_stage) {
  2692. $query->where('age_stage', $age_stage);
  2693. }
  2694. $list = $query->get()->map(function ($value) {
  2695. $value = (array)$value;
  2696. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  2697. return $value;
  2698. })->toArray();
  2699. return $list;
  2700. }
  2701. // 生成火山临时token
  2702. public function setStsToken() {
  2703. // ************* 配置参数 *************
  2704. $method = 'GET';
  2705. $service = 'sts';
  2706. $host = 'open.volcengineapi.com';
  2707. $region = env('VOLC_REGION');
  2708. $endpoint = 'https://open.volcengineapi.com';
  2709. // $endpoint = 'https://tos-cn-beijing.volces.com';
  2710. $access_key = env('VOLC_AK');
  2711. $secret_key = env('VOLC_SK');
  2712. // 获取缓存中的token,如果没有则请求接口
  2713. $token = Redis::get('volc_sts_token');
  2714. if (!$token) {
  2715. // 查询参数
  2716. $query_parameters = [
  2717. 'Action' => 'AssumeRole',
  2718. 'RoleSessionName' => 'user@zw',
  2719. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  2720. 'Version' => '2018-01-01'
  2721. ];
  2722. // 生成URL编码的查询字符串
  2723. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  2724. // 获取签名头信息
  2725. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  2726. // 构建完整URL
  2727. $request_url = $endpoint . '?' . $request_parameters;
  2728. $client = new Client(['verify' => false]);
  2729. $response = $client->get($request_url, ['headers' => $headers]);
  2730. $response_arr = json_decode($response->getBody()->getContents(), true);
  2731. $result = [
  2732. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  2733. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  2734. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  2735. 'Region' => env('VOLC_REGION'),
  2736. 'Endpoint' => env('VOLC_END_POINT'),
  2737. 'Bucket' => env('VOLC_BUCKET'),
  2738. ];
  2739. // 缓存token
  2740. Redis::setex('volc_sts_token', 3000, json_encode($result));
  2741. return $result;
  2742. } else {
  2743. return json_decode($token, true);
  2744. }
  2745. // $response = $response['Response'];
  2746. // $access_key = $response['Credentials']['AccessKeyId'];
  2747. // $secret_key = $response['Credentials']['AccessKeySecret'];
  2748. // $security_token = $response['Credentials']['SecurityToken'];
  2749. // $expiration = $response['Credentials']['Expiration'];
  2750. // dd($response_arr);
  2751. }
  2752. public function emotionGroups($data) {
  2753. $id = getProp($data, 'group_id');
  2754. $group_name = getProp($data, 'group_name');
  2755. $voice_type = getProp($data, 'voice_type');
  2756. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  2757. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  2758. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  2759. if ($group_name) {
  2760. $query->where('group_name', 'like', "%{$group_name}%");
  2761. }
  2762. if ($id) {
  2763. $query->where('id', $id);
  2764. }
  2765. if ($voice_type) {
  2766. $query->where('voice_type', $voice_type);
  2767. }
  2768. return $query->orderBy('id')->get()->map(function ($value) {
  2769. return (array)$value;
  2770. })->toArray();
  2771. }
  2772. private function sign($key, $msg) {
  2773. return hash_hmac('sha256', $msg, $key, true);
  2774. }
  2775. // 生成签名密钥
  2776. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  2777. $kDate = $this->sign($key, $dateStamp);
  2778. $kRegion = $this->sign($kDate, $regionName);
  2779. $kService = $this->sign($kRegion, $serviceName);
  2780. $kSigning = $this->sign($kService, 'request');
  2781. return $kSigning;
  2782. }
  2783. // 获取签名头信息
  2784. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  2785. $contenttype = 'application/x-www-form-urlencoded';
  2786. $accept = 'application/json';
  2787. // 获取当前UTC时间
  2788. $t = new DateTime('now', new DateTimeZone('UTC'));
  2789. $xdate = $t->format('Ymd\THis\Z');
  2790. $datestamp = $t->format('Ymd');
  2791. // 1. 拼接规范请求串
  2792. $canonical_uri = '/';
  2793. $canonical_querystring = $request_parameters;
  2794. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  2795. $signed_headers = 'content-type;host;x-date';
  2796. // 空请求体的SHA256哈希
  2797. $payload_hash = hash('sha256', '');
  2798. $canonical_request = implode("\n", [
  2799. $method,
  2800. $canonical_uri,
  2801. $canonical_querystring,
  2802. $canonical_headers,
  2803. $signed_headers,
  2804. $payload_hash
  2805. ]);
  2806. // 2. 拼接待签名字符串
  2807. $algorithm = 'HMAC-SHA256';
  2808. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  2809. $hashed_canonical_request = hash('sha256', $canonical_request);
  2810. $string_to_sign = implode("\n", [
  2811. $algorithm,
  2812. $xdate,
  2813. $credential_scope,
  2814. $hashed_canonical_request
  2815. ]);
  2816. // 3. 计算签名
  2817. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  2818. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  2819. // 4. 添加签名到请求头
  2820. $authorization_header = sprintf(
  2821. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  2822. $algorithm,
  2823. $access_key,
  2824. $credential_scope,
  2825. $signed_headers,
  2826. $signature
  2827. );
  2828. return [
  2829. 'Accept' => $accept,
  2830. 'Content-Type' => $contenttype,
  2831. 'X-Date' => $xdate,
  2832. 'Authorization' => $authorization_header
  2833. ];
  2834. }
  2835. // 文字合成语音(火山引擎)
  2836. public function tts($data) {
  2837. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  2838. $headers = [
  2839. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  2840. 'Content-Type' => 'application/json; charset=UTF-8'
  2841. ];
  2842. $post_data = [
  2843. 'app' => [
  2844. 'appid' => env('VOLC_APPID'),
  2845. 'token' => env('VOLC_TOKEN'),
  2846. 'cluster' => 'volcano_tts'
  2847. ],
  2848. 'user' => [
  2849. 'uid' => 'mp_audio'
  2850. ],
  2851. // 'audio' => [
  2852. // 'voice_type' =>
  2853. // ],
  2854. ];
  2855. }
  2856. public function scriptList($data) {
  2857. $uid = Site::getUid();
  2858. $script_id = getProp($data, 'script_id');
  2859. $script_name = getProp($data, 'script_name');
  2860. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  2861. if ($script_id) {
  2862. $query->where('id', $script_id);
  2863. }
  2864. if ($script_name) {
  2865. $query->where('script_name', 'like', "%{$script_name}%");
  2866. }
  2867. return $query->orderBy('created_at', 'desc')->paginate(12);
  2868. }
  2869. public function scripts($data) {
  2870. $uid = Site::getUid();
  2871. $script_id = getProp($data, 'script_id');
  2872. $script_name = getProp($data, 'script_name');
  2873. $is_products = getProp($data, 'is_products');
  2874. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  2875. if ($script_id) {
  2876. $query->where('id', $script_id);
  2877. }
  2878. if ($is_products !== '') {
  2879. $query->where('is_products', $is_products);
  2880. }
  2881. if ($script_name) {
  2882. $query->where('script_name', 'like', "%{$script_name}%");
  2883. }
  2884. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  2885. return (array)$value;
  2886. })->toArray();
  2887. }
  2888. public function scriptInfo($data) {
  2889. $uid = Site::getUid();
  2890. $script_id = getProp($data, 'script_id');
  2891. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  2892. // ->selectRaw('id as script_id, script_name, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_sequence, end_episode_sequence, episode_num, remark, created_at')->first();
  2893. ->selectRaw('id as script_id, script_name')->first();
  2894. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2895. $script = (array)$script;
  2896. // 获取分集组信息
  2897. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  2898. ->selectRaw('id as group_id, script_id, group_name, start_episode_number, end_episode_number, intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, episode_content')
  2899. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  2900. $value = (array)$value;
  2901. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  2902. return (array)$value;
  2903. })->toArray();
  2904. $script['group'] = $groups;
  2905. return $script;
  2906. }
  2907. public function createScript($data) {
  2908. $script_name = getProp($data, 'script_name');
  2909. $uid = Site::getUid(); // 获取当前用户ID
  2910. $cpid = Site::getCpid(); // 获取当前公司组ID
  2911. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  2912. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  2913. $script_name .= '_'.date('YmdHis');
  2914. }
  2915. return DB::table('mp_scripts')->insertGetId([
  2916. 'script_name' => $script_name,
  2917. 'user_id' => $uid,
  2918. 'cpid' => $cpid,
  2919. 'created_at' => date('Y-m-d H:i:s'),
  2920. 'updated_at' => date('Y-m-d H:i:s')
  2921. ]);
  2922. }
  2923. public function editScript($data) {
  2924. $script_id = getProp($data, 'script_id');
  2925. $script_name = getProp($data, 'script_name');
  2926. $uid = Site::getUid(); // 获取当前用户ID
  2927. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  2928. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  2929. if ($id && (int)$id !== (int)$script_id) {
  2930. $script_name .= '_'.date('YmdHis');
  2931. }
  2932. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2933. 'script_name' => $script_name,
  2934. 'updated_at' => date('Y-m-d H:i:s')
  2935. ]);
  2936. }
  2937. public function delScript($data) {
  2938. $script_id = getProp($data, 'script_id');
  2939. $uid = Site::getUid(); // 获取当前用户ID
  2940. if (!$script_id) Utils::throwError('20003:请选择剧本');
  2941. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2942. 'is_deleted' => 1,
  2943. 'updated_at' => date('Y-m-d H:i:s')
  2944. ]);
  2945. }
  2946. public function createEpisode($data) {
  2947. $script_id = getProp($data, 'script_id');
  2948. $group_name = getProp($data, 'group_name');
  2949. $remark = getProp($data, 'remark');
  2950. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  2951. $uid = Site::getUid(); // 获取当前用户ID
  2952. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  2953. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  2954. $group_name .= '_'.date('YmdHis');
  2955. }
  2956. return DB::table('mp_script_episode_group')->insertGetId([
  2957. 'script_id' => $script_id,
  2958. 'group_name' => $group_name,
  2959. 'user_id' => $uid,
  2960. 'remark' => $remark,
  2961. 'created_at' => date('Y-m-d H:i:s'),
  2962. 'updated_at' => date('Y-m-d H:i:s')
  2963. ]);
  2964. }
  2965. public function editEpisode($data) {
  2966. $group_id = getProp($data, 'group_id');
  2967. $start_episode_number = getProp($data, 'start_episode_number');
  2968. $end_episode_number = getProp($data, 'end_episode_number');
  2969. $group_name = getProp($data, 'group_name');
  2970. $uid = Site::getUid(); // 获取当前用户ID
  2971. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  2972. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  2973. if ($id && (int)$id !== (int)$group_id) {
  2974. $group_name .= '_'.date('YmdHis');
  2975. }
  2976. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2977. 'group_name' => $group_name,
  2978. 'start_episode_number' => $start_episode_number,
  2979. 'end_episode_number' => $end_episode_number,
  2980. 'updated_at' => date('Y-m-d H:i:s')
  2981. ]);
  2982. }
  2983. public function delEpisode($data) {
  2984. $group_id = getProp($data, 'group_id');
  2985. $uid = Site::getUid(); // 获取当前用户ID
  2986. if (!$group_id) Utils::throwError('20003:请选择分集');
  2987. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2988. 'is_deleted' => 1,
  2989. 'updated_at' => date('Y-m-d H:i:s')
  2990. ]);
  2991. }
  2992. /**
  2993. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2994. *
  2995. * @param array $data 包含以下参数:
  2996. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2997. * - question: 用户问题(可选)
  2998. * - model: 使用的模型(r1 或 v3,默认 v3)
  2999. * @return \Generator 返回生成器,用于流式输出
  3000. */
  3001. public function generateEpisodes($data) {
  3002. $script_id = getProp($data, 'script_id');
  3003. $group_id = getProp($data, 'group_id');
  3004. // $file = getProp($data, 'file');
  3005. $file = '';
  3006. $content = getProp($data, 'content', '');
  3007. // $bid = getProp($data, 'bid', 0);
  3008. $bid = 0;
  3009. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3010. if (!$group) {
  3011. Utils::throwError('20003:剧本分集不存在');
  3012. }
  3013. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  3014. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  3015. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  3016. $prompt = getProp($data, 'prompt');
  3017. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  3018. $model = getProp($data, 'model');
  3019. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3020. Utils::throwError('20003:该模型不存在!');
  3021. }
  3022. // 检查是否存在重叠的剧集序号范围
  3023. $exists_groups = DB::table('mp_script_episode_group')
  3024. ->where('script_id', $script_id)
  3025. ->where('id', '<>', $group_id) // 排除当前组
  3026. ->where('is_deleted', 0)
  3027. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3028. // 检查新范围是否与现有范围重叠
  3029. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3030. // 新范围的开始在现有范围内
  3031. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3032. ->where('end_episode_number', '>=', $start_episode_sequence);
  3033. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3034. // 新范围的结束在现有范围内
  3035. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3036. ->where('end_episode_number', '>=', $end_episode_sequence);
  3037. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3038. // 新范围完全包含现有范围
  3039. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3040. ->where('end_episode_number', '<=', $end_episode_sequence);
  3041. });
  3042. })
  3043. ->select('start_episode_number', 'end_episode_number')
  3044. ->get();
  3045. if ($exists_groups->isNotEmpty()) {
  3046. $conflict_ranges = [];
  3047. foreach ($exists_groups as $group) {
  3048. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3049. }
  3050. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3051. }
  3052. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3053. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3054. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3055. if ($model === 'deepseek-chat') {
  3056. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3057. $model = 'deepseek-v4-flash';
  3058. $thinkingMode = 'disabled';
  3059. } elseif ($model === 'deepseek-reasoner') {
  3060. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3061. $model = 'deepseek-v4-flash';
  3062. $thinkingMode = 'enabled';
  3063. }
  3064. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3065. if (!$script) {
  3066. Utils::throwError('20003:剧本不存在');
  3067. }
  3068. $content = getProp($group, 'content');
  3069. if (!$file && !$content && !$bid) {
  3070. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3071. }
  3072. // 提取文件内容
  3073. if ($file) {
  3074. $content = $this->extractFileContent($file);
  3075. if (!$content) {
  3076. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3077. }
  3078. } elseif ($bid) {
  3079. $content = $this->getContentByBid($bid);
  3080. if (!$content) {
  3081. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3082. }
  3083. } elseif ($content) {
  3084. $content = filterContent($content);
  3085. } elseif ($prompt) {
  3086. $content = filterContent($prompt);
  3087. } else {
  3088. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3089. }
  3090. // 构建消息
  3091. $messages = [
  3092. $this->sys_message,
  3093. [
  3094. 'role' => 'user',
  3095. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3096. ]
  3097. ];
  3098. $post_data = [
  3099. 'model' => $model,
  3100. 'messages' => $messages,
  3101. // 'max_tokens' => 8192,
  3102. 'temperature' => 0.7,
  3103. 'frequency_penalty' => 0,
  3104. 'presence_penalty' => 0,
  3105. 'thinking' => ['type' => $thinkingMode],
  3106. 'response_format' => ['type' => 'text'],
  3107. 'stream' => true
  3108. ];
  3109. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3110. // 根据模型类型选择调用方法
  3111. $fullContent = '';
  3112. $fullReasoningContent = '';
  3113. $usage = [];
  3114. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3115. // DeepSeek 官方模型使用 DeepSeek API
  3116. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3117. } else if (in_array($model, $this->gpt_text_models)) {
  3118. // GPT-5.4 模型使用 TokenRouter API
  3119. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3120. } else if (in_array($model, $this->gemini_text_models)) {
  3121. // Gemini 模型使用 Gemini API
  3122. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3123. } else {
  3124. // 其他模型使用火山引擎API
  3125. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3126. }
  3127. // 处理流式输出
  3128. foreach ($streamGenerator as $chunk) {
  3129. if (isset($chunk['type'])) {
  3130. if ($chunk['type'] === 'done') {
  3131. // 最终结果
  3132. $fullContent = $chunk['full_content'];
  3133. $fullReasoningContent = $chunk['full_reasoning'];
  3134. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3135. } else {
  3136. // 逐块yield数据
  3137. yield $chunk;
  3138. }
  3139. }
  3140. }
  3141. dLog('deepseek')->info('完整内容: '.$fullContent);
  3142. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3143. // 处理完整内容并返回最终结果
  3144. $script_arr = [];
  3145. if ($fullContent) {
  3146. $script_arr = extractScriptContent($fullContent);
  3147. }
  3148. logDB('deepseek', 'info', '解析内容', $script_arr);
  3149. if (!$script_arr['episodes']) {
  3150. Utils::throwError('20003:未生成剧本相关信息');
  3151. // yield [
  3152. // 'type' => 'done',
  3153. // 'script' => $script_arr,
  3154. // 'msg' => '未生成剧本相关信息',
  3155. // 'answer' => $fullContent,
  3156. // 'reasoning' => $fullReasoningContent,
  3157. // 'usage' => $usage
  3158. // ];
  3159. // return ;
  3160. }
  3161. try {
  3162. DB::beginTransaction();
  3163. // // 返回前保存剧本内容
  3164. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3165. // 'content' => $content,
  3166. // 'updated_at' => date('Y-m-d H:i:s')
  3167. // ]);
  3168. // if (!$boolen) {
  3169. // Utils::throwError('20003:保存剧本内容失败');
  3170. // }
  3171. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3172. // 'start_episode_number' => $start_episode_sequence,
  3173. // 'end_episode_number' => $end_episode_sequence,
  3174. // 'updated_at' => date('Y-m-d H:i:s')
  3175. // ]);
  3176. // if (!$boolen1) {
  3177. // Utils::throwError('20003:保存分集失败');
  3178. // }
  3179. $episode_content = '';
  3180. $episodes = [];
  3181. foreach ($script_arr['episodes'] as $item) {
  3182. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  3183. // $episodes[] = [
  3184. // 'script_id' => $script_id,
  3185. // 'episode_number' => $item['episode_number'],
  3186. // 'episode_name' => $item['episode_name'],
  3187. // 'episode_content' => $item['episode_content'],
  3188. // 'created_at' => date('Y-m-d H:i:s'),
  3189. // 'updated_at' => date('Y-m-d H:i:s'),
  3190. // ];
  3191. }
  3192. if ($episode_content) {
  3193. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3194. 'episode_content' => $episode_content,
  3195. 'updated_at' => date('Y-m-d H:i:s')
  3196. ]);
  3197. if (!$boolen2) {
  3198. Utils::throwError('20003:保存分集内容失败');
  3199. }
  3200. }else {
  3201. Utils::throwError('20003:分集剧本解析失败');
  3202. }
  3203. }catch (\Exception $e) {
  3204. DB::rollBack();
  3205. Utils::throwError('20003:'.$e->getMessage());
  3206. }
  3207. DB::commit();
  3208. yield [
  3209. 'type' => 'done',
  3210. 'script' => $script_arr,
  3211. 'episode_content' => $episode_content,
  3212. 'answer' => $fullContent,
  3213. 'reasoning' => $fullReasoningContent,
  3214. 'usage' => $usage
  3215. ];
  3216. }
  3217. public function chatWithFileStream($data) {
  3218. $script_id = getProp($data, 'script_id');
  3219. $group_id = getProp($data, 'group_id');
  3220. $file = getProp($data, 'file');
  3221. $content = getProp($data, 'content', '');
  3222. $bid = getProp($data, 'bid', 0);
  3223. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3224. $total_episode_num = getProp($data, 'total_episode_num', 30);
  3225. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  3226. $prompt = getProp($data, 'prompt');
  3227. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  3228. if (!empty($prompt)) {
  3229. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  3230. }
  3231. $question = getProp($data, 'question', $baseQuestion);
  3232. $model = getProp($data, 'model');
  3233. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3234. Utils::throwError('20003:该模型不存在!');
  3235. }
  3236. // 检查是否存在重叠的剧集序号范围
  3237. $exists_groups = DB::table('mp_script_episode_group')
  3238. ->where('script_id', $script_id)
  3239. ->where('id', '<>', $group_id)
  3240. ->where('is_deleted', 0)
  3241. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3242. // 检查新范围是否与现有范围重叠
  3243. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3244. // 新范围的开始在现有范围内
  3245. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3246. ->where('end_episode_number', '>=', $start_episode_sequence);
  3247. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3248. // 新范围的结束在现有范围内
  3249. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3250. ->where('end_episode_number', '>=', $end_episode_sequence);
  3251. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3252. // 新范围完全包含现有范围
  3253. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3254. ->where('end_episode_number', '<=', $end_episode_sequence);
  3255. });
  3256. })
  3257. ->select('start_episode_number', 'end_episode_number')
  3258. ->get();
  3259. if ($exists_groups->isNotEmpty()) {
  3260. $conflict_ranges = [];
  3261. foreach ($exists_groups as $group) {
  3262. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3263. }
  3264. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3265. }
  3266. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3267. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3268. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3269. if ($model === 'deepseek-chat') {
  3270. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3271. $model = 'deepseek-v4-flash';
  3272. $thinkingMode = 'disabled';
  3273. } elseif ($model === 'deepseek-reasoner') {
  3274. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3275. $model = 'deepseek-v4-flash';
  3276. $thinkingMode = 'enabled';
  3277. }
  3278. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3279. if (!$script) {
  3280. Utils::throwError('20003:剧本不存在');
  3281. }
  3282. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3283. if (!$group) {
  3284. Utils::throwError('20003:剧本分集不存在');
  3285. }
  3286. if (!$file && !$content && !$bid) {
  3287. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3288. }
  3289. // 提取文件内容
  3290. if ($file) {
  3291. $content = $this->extractFileContent($file);
  3292. if (!$content) {
  3293. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3294. }
  3295. } elseif ($bid) {
  3296. $content = $this->getContentByBid($bid);
  3297. if (!$content) {
  3298. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3299. }
  3300. } elseif ($content) {
  3301. $content = filterContent($content);
  3302. } elseif ($prompt) {
  3303. $content = filterContent($prompt);
  3304. } else {
  3305. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3306. }
  3307. // 构建消息
  3308. $messages = [
  3309. [
  3310. 'role' => 'system',
  3311. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3312. 强制要求:\n
  3313. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3314. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  3315. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  3316. 普通要求:\n
  3317. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  3318. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  3319. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  3320. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  3321. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  3322. 示例如下:\n
  3323. ###剧本名:西昆仑
  3324. ###故事梗概
  3325. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3326. ###剧本亮点
  3327. 亮点1:绝境奇药,生死一线
  3328. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3329. 亮点2:结拜兄妹,化解尴尬
  3330. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3331. 亮点3:纤发夺命,情愫暗涌
  3332. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3333. ###人物关系
  3334. 阿雪与梁萧之间存在兄妹之情。
  3335. ###核心矛盾
  3336. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3337. ###主体列表
  3338. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  3339. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  3340. 阴阳球:天地异宝,能化生精气,救人于危难。
  3341. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  3342. ###美术风格
  3343. 基础画风风格词:厚涂古风
  3344. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3345. ###场景列表
  3346. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  3347. [
  3348. 'role' => 'user',
  3349. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3350. ]
  3351. ];
  3352. $post_data = [
  3353. 'model' => $model,
  3354. 'messages' => $messages,
  3355. // 'max_tokens' => 8192,
  3356. 'temperature' => 0.7,
  3357. 'frequency_penalty' => 0,
  3358. 'presence_penalty' => 0,
  3359. 'thinking' => ['type' => $thinkingMode],
  3360. 'response_format' => ['type' => 'text'],
  3361. 'stream' => true
  3362. ];
  3363. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3364. // 根据模型类型选择调用方法
  3365. $fullContent = '';
  3366. $fullReasoningContent = '';
  3367. $usage = [];
  3368. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3369. // DeepSeek 官方模型使用 DeepSeek API
  3370. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3371. } else if (in_array($model, $this->gpt_text_models)) {
  3372. // GPT-5.4 模型使用 TokenRouter API
  3373. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3374. } else if (in_array($model, $this->gemini_text_models)) {
  3375. // Gemini 模型使用 Gemini API
  3376. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3377. } else {
  3378. // 其他模型使用火山引擎API
  3379. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3380. }
  3381. // 处理流式输出
  3382. foreach ($streamGenerator as $chunk) {
  3383. if (isset($chunk['type'])) {
  3384. if ($chunk['type'] === 'done') {
  3385. // 最终结果
  3386. $fullContent = $chunk['full_content'];
  3387. $fullReasoningContent = $chunk['full_reasoning'];
  3388. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3389. } else {
  3390. // 逐块yield数据
  3391. yield $chunk;
  3392. }
  3393. }
  3394. }
  3395. dLog('deepseek')->info('完整内容: '.$fullContent);
  3396. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3397. // 处理完整内容并返回最终结果
  3398. $script_arr = [];
  3399. if ($fullContent) {
  3400. $script_arr = extractScriptContent($fullContent);
  3401. }
  3402. logDB('deepseek', 'info', '解析内容', $script_arr);
  3403. if (!$script_arr['roles']) {
  3404. Utils::throwError('20003:未生成剧本相关信息');
  3405. // yield [
  3406. // 'type' => 'done',
  3407. // 'script' => $script_arr,
  3408. // 'msg' => '未生成剧本相关信息',
  3409. // 'answer' => $fullContent,
  3410. // 'reasoning' => $fullReasoningContent,
  3411. // 'usage' => $usage
  3412. // ];
  3413. }
  3414. try {
  3415. DB::beginTransaction();
  3416. // // 返回前保存剧本内容
  3417. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3418. // 'content' => $content,
  3419. // 'status' => '解析完成',
  3420. // 'updated_at' => date('Y-m-d H:i:s')
  3421. // ]);
  3422. // if (!$boolen) {
  3423. // Utils::throwError('20003:保存剧本内容失败');
  3424. // }
  3425. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3426. 'start_episode_number' => $start_episode_sequence,
  3427. 'end_episode_number' => $end_episode_sequence,
  3428. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3429. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3430. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3431. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3432. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3433. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3434. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3435. 'status' => '解析完成',
  3436. 'content' => $content,
  3437. 'updated_at' => date('Y-m-d H:i:s')
  3438. ]);
  3439. if (!$boolen1) {
  3440. Utils::throwError('20003:保存分集失败');
  3441. }
  3442. // $episodes = [];
  3443. // foreach ($script_arr['episodes'] as $item) {
  3444. // $episodes[] = [
  3445. // 'script_id' => $script_id,
  3446. // 'episode_number' => $item['episode_number'],
  3447. // 'episode_name' => $item['episode_name'],
  3448. // 'episode_content' => $item['episode_content'],
  3449. // 'created_at' => date('Y-m-d H:i:s'),
  3450. // 'updated_at' => date('Y-m-d H:i:s'),
  3451. // ];
  3452. // }
  3453. // if ($episodes) {
  3454. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  3455. // if (!$boolen2) {
  3456. // Utils::throwError('20003:保存分集内容失败');
  3457. // }
  3458. // }else {
  3459. // Utils::throwError('20003:分集剧本解析失败');
  3460. // }
  3461. }catch (\Exception $e) {
  3462. DB::rollBack();
  3463. Utils::throwError('20003:'.$e->getMessage());
  3464. }
  3465. DB::commit();
  3466. yield [
  3467. 'type' => 'done',
  3468. 'script' => $script_arr,
  3469. 'answer' => $fullContent,
  3470. 'reasoning' => $fullReasoningContent,
  3471. 'usage' => $usage
  3472. ];
  3473. }
  3474. /**
  3475. * 上传文件识别文字内容并与 DeepSeek 进行对话
  3476. *
  3477. * @param array $data 包含以下参数:
  3478. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3479. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  3480. * - model: 使用的模型(r1 或 v3,默认 v3)
  3481. * @return array
  3482. */
  3483. public function chatWithFile($data) {
  3484. $script_id = getProp($data, 'script_id');
  3485. $file = getProp($data, 'file');
  3486. $content = getProp($data, 'content', '');
  3487. $bid = getProp($data, 'bid', 0);
  3488. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3489. $total_episode_num = getProp($data, 'total_episode_num', 30);
  3490. $prompt = getProp($data, 'prompt');
  3491. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  3492. if (!empty($prompt)) {
  3493. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  3494. }
  3495. $question = getProp($data, 'question', $baseQuestion);
  3496. // 处理文本模型
  3497. $model = getProp($data, 'model');
  3498. if (!$model) {
  3499. // 用户没有输入,使用默认值
  3500. $model = 'doubao-seed-2-0-mini-260215';
  3501. }
  3502. // 验证模型是否在可用模型表中
  3503. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3504. $model = 'doubao-seed-2-0-mini-260215';
  3505. }
  3506. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3507. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3508. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3509. if ($model === 'deepseek-chat') {
  3510. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3511. $model = 'deepseek-v4-flash';
  3512. $thinkingMode = 'disabled';
  3513. } elseif ($model === 'deepseek-reasoner') {
  3514. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3515. $model = 'deepseek-v4-flash';
  3516. $thinkingMode = 'enabled';
  3517. }
  3518. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3519. if (!$script) {
  3520. Utils::throwError('20003:剧本不存在');
  3521. }
  3522. if (!$file && !$content && !$bid) {
  3523. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3524. }
  3525. // 提取文件内容
  3526. if ($file) {
  3527. $content = $this->extractFileContent($file);
  3528. if (!$content) {
  3529. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3530. }
  3531. } elseif ($bid) {
  3532. $content = $this->getContentByBid($bid);
  3533. if (!$content) {
  3534. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3535. }
  3536. } elseif ($content) {
  3537. $content = filterContent($content);
  3538. } elseif ($prompt) {
  3539. $content = filterContent($prompt);
  3540. } else {
  3541. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3542. }
  3543. // 构建消息
  3544. $messages = [
  3545. $this->sys_message,
  3546. [
  3547. 'role' => 'user',
  3548. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3549. ]
  3550. ];
  3551. $post_data = [
  3552. 'model' => $model,
  3553. 'messages' => $messages,
  3554. // 'max_tokens' => 8192,
  3555. 'temperature' => 0.7,
  3556. 'frequency_penalty' => 0,
  3557. 'presence_penalty' => 0,
  3558. 'thinking' => ['type' => $thinkingMode],
  3559. 'response_format' => ['type' => 'text'],
  3560. 'stream' => false
  3561. ];
  3562. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3563. // 根据模型类型选择调用方法
  3564. $fullContent = '';
  3565. $usage = [];
  3566. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3567. // DeepSeek 官方模型使用 DeepSeek API
  3568. $chatResult = $this->chatOnly($post_data);
  3569. } else if (in_array($model, $this->gpt_text_models)) {
  3570. // GPT-5.4 模型使用 TokenRouter API
  3571. $chatResult = $this->gpt54ChatOnly($post_data);
  3572. } else {
  3573. // 其他模型使用火山引擎API
  3574. $chatResult = $this->volcEngineChatCompletion($post_data);
  3575. }
  3576. if (is_array($chatResult)) {
  3577. $fullContent = $chatResult['fullContent'];
  3578. $usage = $chatResult['usage'];
  3579. }
  3580. $script_arr = [];
  3581. // 处理结果
  3582. if ($fullContent) {
  3583. $script_arr = extractScriptContent($fullContent);
  3584. }
  3585. // 返回前保存剧本内容
  3586. DB::table('mp_scripts')->where('id', $script_id)->update([
  3587. 'content' => $content,
  3588. 'updated_at' => date('Y-m-d H:i:s')
  3589. ]);
  3590. return [
  3591. 'script' => $script_arr,
  3592. 'answer' => $fullContent,
  3593. 'usage' => $usage
  3594. ];
  3595. }
  3596. public function getEpisodeContent($data) {
  3597. $group_id = getProp($data, 'group_id');
  3598. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  3599. }
  3600. public function saveEpisodeContent($data) {
  3601. $script_id = getProp($data, 'script_id');
  3602. $group_id = getProp($data, 'group_id');
  3603. $start_episode_sequence = getProp($data, 'start_episode_number');
  3604. $end_episode_sequence = getProp($data, 'end_episode_number');
  3605. // 检查是否存在重叠的剧集序号范围
  3606. $exists_groups = DB::table('mp_script_episode_group')
  3607. ->where('script_id', $script_id)
  3608. ->where('id', '<>', $group_id) // 排除当前组
  3609. ->where('is_deleted', 0)
  3610. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3611. // 检查新范围是否与现有范围重叠
  3612. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3613. // 新范围的开始在现有范围内
  3614. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3615. ->where('end_episode_number', '>=', $start_episode_sequence);
  3616. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3617. // 新范围的结束在现有范围内
  3618. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3619. ->where('end_episode_number', '>=', $end_episode_sequence);
  3620. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3621. // 新范围完全包含现有范围
  3622. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3623. ->where('end_episode_number', '<=', $end_episode_sequence);
  3624. });
  3625. })
  3626. ->select('start_episode_number', 'end_episode_number')
  3627. ->get();
  3628. if ($exists_groups->isNotEmpty()) {
  3629. $conflict_ranges = [];
  3630. foreach ($exists_groups as $group) {
  3631. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3632. }
  3633. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3634. }
  3635. $episode_content = getProp($data, 'episode_content');
  3636. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  3637. 'content' => $episode_content,
  3638. 'start_episode_number' => $start_episode_sequence,
  3639. 'end_episode_number' => $end_episode_sequence,
  3640. 'updated_at' => date('Y-m-d H:i:s')
  3641. ]);
  3642. $script_arr =getProp($data, 'script', []);
  3643. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  3644. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3645. $script_id = getProp($data, 'script_id');
  3646. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  3647. try {
  3648. DB::beginTransaction();
  3649. $update_data = [
  3650. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3651. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3652. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3653. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3654. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3655. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3656. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3657. 'status' => 3,
  3658. 'start_episode_sequence' => $start_episode_sequence,
  3659. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  3660. 'episode_num' => count($script_arr['episodes']),
  3661. 'updated_at' => date('Y-m-d H:i:s')
  3662. ];
  3663. // 保存剧本内容
  3664. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  3665. if (!$boolen) {
  3666. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  3667. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  3668. Utils::throwError('20003:剧本内容保存失败');
  3669. }
  3670. // 保存分集内容
  3671. // 删除历史分集内容
  3672. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  3673. $episodes = [];
  3674. $sequence = 1;
  3675. foreach ($script_arr['episodes'] as $episode) {
  3676. $segment_number = 1;
  3677. foreach($episode['segments'] as $segment) {
  3678. $episodes[] = [
  3679. 'script_id' => $script_id,
  3680. 'episode_number' => $episode['episode_number'],
  3681. 'title' => $episode['title'],
  3682. // 'content' => $episode['content'],
  3683. 'content' => '',
  3684. 'segment_number' => $segment_number,
  3685. 'segment_content' => $segment['segment_content'],
  3686. 'sequence' => $sequence,
  3687. 'created_at' => date('Y-m-d H:i:s'),
  3688. 'updated_at' => date('Y-m-d H:i:s')
  3689. ];
  3690. $sequence++;
  3691. $segment_number++;
  3692. }
  3693. }
  3694. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  3695. if (!$boolen2) {
  3696. dLog('deepseek')->info('分集内容保存失败', $episodes);
  3697. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  3698. Utils::throwError('20003:分集内容保存失败');
  3699. }
  3700. } catch (\Exception $e) {
  3701. DB::rollBack();
  3702. Utils::throwError('20003:'.$e->getMessage());
  3703. }
  3704. DB::commit();
  3705. return true;
  3706. }
  3707. public function getBookContent($data) {
  3708. $bid = getProp($data, 'bid');
  3709. $start_sequence = getProp($data, 'start_sequence');
  3710. $end_sequence = getProp($data, 'end_sequence');
  3711. $chapter_contents = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', 'cc.id')->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->whereBetween('c.sequence', [$start_sequence, $end_sequence])
  3712. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  3713. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  3714. return $return_content;
  3715. }
  3716. public function exportScript($data) {
  3717. $filename = getProp($data, 'filename');
  3718. $script_id = getProp($data, 'script_id');
  3719. $group_id = getProp($data, 'group_id');
  3720. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  3721. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  3722. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3723. $script = (array)$script;
  3724. // 获取分集组信息
  3725. if ($group_id) {
  3726. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  3727. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  3728. ->get()->map(function($value) {
  3729. return (array)$value;
  3730. })->toArray();
  3731. }else {
  3732. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  3733. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  3734. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  3735. return (array)$value;
  3736. })->toArray();
  3737. }
  3738. if (!$groups) Utils::throwError('20003:分集不存在');
  3739. $script['group'] = $groups;
  3740. $export_type = getProp($data, 'export_type', 'txt');
  3741. // 生成文件名
  3742. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  3743. // 根据导出类型生成不同格式的文件
  3744. switch ($export_type) {
  3745. case 'txt':
  3746. return $this->exportScriptAsTxt($script, $filename);
  3747. case 'pdf':
  3748. return $this->exportScriptAsPdf($script, $filename);
  3749. default:
  3750. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  3751. }
  3752. }
  3753. /**
  3754. * 导出剧本为TXT格式
  3755. */
  3756. private function exportScriptAsTxt($script, $filename) {
  3757. // 构建TXT内容
  3758. $content = $this->buildScriptContent($script);
  3759. // 设置响应头,直接下载
  3760. header('Content-Type: text/plain; charset=utf-8');
  3761. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  3762. header('Content-Length: ' . strlen($content));
  3763. // 输出内容并结束
  3764. echo $content;
  3765. exit();
  3766. }
  3767. /**
  3768. * 导出剧本为PDF格式
  3769. */
  3770. private function exportScriptAsPdf($script, $filename) {
  3771. // 使用HTML转PDF的方式来更好地支持中文
  3772. $htmlContent = $this->buildScriptHtmlForPdf($script);
  3773. // 创建PDF实例
  3774. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  3775. // 设置文档信息
  3776. $pdf->SetCreator('剧本导出系统');
  3777. $pdf->SetAuthor('系统');
  3778. $pdf->SetTitle($script['script_name']);
  3779. $pdf->SetSubject('剧本导出');
  3780. // 设置边距
  3781. $pdf->SetMargins(15, 15, 15);
  3782. $pdf->SetAutoPageBreak(TRUE, 15);
  3783. // 添加页面
  3784. $pdf->AddPage();
  3785. // 注册并使用 simsun.ttf 字体
  3786. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  3787. // 使用HTML内容生成PDF
  3788. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  3789. // 直接输出PDF文件供下载
  3790. header('Content-Type: application/pdf');
  3791. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  3792. // 直接输出PDF内容
  3793. $pdf->Output($filename . '.pdf', 'D');
  3794. exit();
  3795. }
  3796. /**
  3797. * 构建用于PDF的HTML内容
  3798. */
  3799. private function buildScriptHtmlForPdf($script) {
  3800. $html = '<style>
  3801. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  3802. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  3803. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  3804. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  3805. .info { margin-bottom: 8px; }
  3806. .group { margin-bottom: 30px; page-break-inside: avoid; }
  3807. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  3808. .segment { margin-bottom: 10px; margin-left: 20px; }
  3809. .episode-content { white-space: pre-wrap; }
  3810. </style>';
  3811. // 标题
  3812. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  3813. // 处理分组数据
  3814. if (!empty($script['group']) && is_array($script['group'])) {
  3815. $groups = (array)$script['group'];
  3816. foreach ($groups as $group) {
  3817. $html .= '<div class="group">';
  3818. // 分组标题
  3819. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  3820. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  3821. // 故事梗概
  3822. if (!empty($group['intro'])) {
  3823. $html .= '<h3>故事梗概</h3>';
  3824. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  3825. }
  3826. // 剧本亮点
  3827. if (!empty($group['highlights'])) {
  3828. $html .= '<h3>剧本亮点</h3>';
  3829. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  3830. }
  3831. // 人物关系
  3832. if (!empty($group['role_relationship'])) {
  3833. $html .= '<h3>人物关系</h3>';
  3834. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  3835. }
  3836. // 核心矛盾
  3837. if (!empty($group['core_contradiction'])) {
  3838. $html .= '<h3>核心矛盾</h3>';
  3839. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  3840. }
  3841. // 主体列表
  3842. if (!empty($group['roles']) && is_array($group['roles'])) {
  3843. $html .= '<h3>主体列表</h3>';
  3844. $html .= '<ul>';
  3845. foreach ($group['roles'] as $role) {
  3846. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  3847. }
  3848. $html .= '</ul>';
  3849. }
  3850. // 美术风格
  3851. if (!empty($group['art_style'])) {
  3852. $html .= '<h3>美术风格</h3>';
  3853. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  3854. }
  3855. // 场景列表
  3856. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3857. $html .= '<h3>场景列表</h3>';
  3858. $html .= '<ul>';
  3859. foreach ($group['scenes'] as $scene) {
  3860. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  3861. }
  3862. $html .= '</ul>';
  3863. }
  3864. // 分集剧本
  3865. if (!empty($group['episode_content'])) {
  3866. $html .= '<h3>分集剧本</h3>';
  3867. // 去除零宽字符和其他不可见字符
  3868. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  3869. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  3870. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  3871. }
  3872. $html .= '</div>';
  3873. }
  3874. }
  3875. return $html;
  3876. }
  3877. /**
  3878. * 构建PDF内容
  3879. */
  3880. private function buildPdfContent($pdf, $script) {
  3881. // 标题
  3882. $pdf->SetFont('dejavusans', 'B', 18);
  3883. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  3884. $pdf->Ln(5);
  3885. // 基本信息
  3886. $pdf->SetFont('dejavusans', '', 12);
  3887. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  3888. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  3889. $pdf->Ln(5);
  3890. // 剧本简介
  3891. if (!empty($script['intro'])) {
  3892. $pdf->SetFont('dejavusans', 'B', 14);
  3893. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  3894. $pdf->SetFont('dejavusans', '', 12);
  3895. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  3896. $pdf->Ln(3);
  3897. }
  3898. // 亮点
  3899. if (!empty($script['highlights'])) {
  3900. $pdf->SetFont('dejavusans', 'B', 14);
  3901. $pdf->Cell(0, 10, '亮点', 0, 1);
  3902. $pdf->SetFont('dejavusans', '', 12);
  3903. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  3904. $pdf->Ln(3);
  3905. }
  3906. // 核心矛盾
  3907. if (!empty($script['core_contradiction'])) {
  3908. $pdf->SetFont('dejavusans', 'B', 14);
  3909. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  3910. $pdf->SetFont('dejavusans', '', 12);
  3911. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  3912. $pdf->Ln(3);
  3913. }
  3914. // 艺术风格
  3915. if (!empty($script['art_style'])) {
  3916. $pdf->SetFont('dejavusans', 'B', 14);
  3917. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  3918. $pdf->SetFont('dejavusans', '', 12);
  3919. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  3920. $pdf->Ln(3);
  3921. }
  3922. // 备注
  3923. if (!empty($script['remark'])) {
  3924. $pdf->SetFont('dejavusans', 'B', 14);
  3925. $pdf->Cell(0, 10, '备注', 0, 1);
  3926. $pdf->SetFont('dejavusans', '', 12);
  3927. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  3928. $pdf->Ln(3);
  3929. }
  3930. // 角色列表
  3931. if (!empty($script['roles']) && is_array($script['roles'])) {
  3932. $pdf->SetFont('dejavusans', 'B', 14);
  3933. $pdf->Cell(0, 10, '角色列表', 0, 1);
  3934. $pdf->SetFont('dejavusans', '', 12);
  3935. foreach ($script['roles'] as $index => $role) {
  3936. if (is_array($role) || is_object($role)) {
  3937. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  3938. } else {
  3939. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  3940. }
  3941. }
  3942. $pdf->Ln(3);
  3943. }
  3944. // 角色关系
  3945. if (!empty($script['role_relationship'])) {
  3946. $pdf->SetFont('dejavusans', 'B', 14);
  3947. $pdf->Cell(0, 10, '角色关系', 0, 1);
  3948. $pdf->SetFont('dejavusans', '', 12);
  3949. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  3950. $pdf->Ln(3);
  3951. }
  3952. // 场景列表
  3953. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  3954. $pdf->SetFont('dejavusans', 'B', 14);
  3955. $pdf->Cell(0, 10, '场景列表', 0, 1);
  3956. $pdf->SetFont('dejavusans', '', 12);
  3957. foreach ($script['scenes'] as $index => $scene) {
  3958. if (is_array($scene) || is_object($scene)) {
  3959. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  3960. } else {
  3961. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  3962. }
  3963. }
  3964. $pdf->Ln(5);
  3965. }
  3966. // 分集内容
  3967. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  3968. $pdf->SetFont('dejavusans', 'B', 16);
  3969. $pdf->Cell(0, 12, '分集内容', 0, 1);
  3970. $pdf->Ln(3);
  3971. foreach ($script['episodes'] as $episode) {
  3972. // 检查是否需要新页面
  3973. if ($pdf->GetY() > 250) {
  3974. $pdf->AddPage();
  3975. }
  3976. $pdf->SetFont('dejavusans', 'B', 14);
  3977. $episodeTitle = '第' . $episode['episode_number'] . '集';
  3978. if (!empty($episode['title'])) {
  3979. $episodeTitle .= ':' . $episode['title'];
  3980. }
  3981. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  3982. // 处理分段内容
  3983. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  3984. $pdf->SetFont('dejavusans', '', 12);
  3985. foreach ($episode['segments'] as $segment) {
  3986. if (!empty($segment['segment_content'])) {
  3987. // 如果有分段编号,显示分段标题
  3988. if (!empty($segment['segment_number'])) {
  3989. $pdf->SetFont('dejavusans', 'B', 12);
  3990. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  3991. $pdf->SetFont('dejavusans', '', 12);
  3992. }
  3993. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  3994. $pdf->Ln(2);
  3995. }
  3996. }
  3997. }
  3998. $pdf->Ln(5);
  3999. }
  4000. }
  4001. }
  4002. /**
  4003. * 构建剧本文本内容
  4004. */
  4005. private function buildScriptContent($script) {
  4006. $content = '';
  4007. $groups = $script['group'];
  4008. $groups = (array)$groups;
  4009. foreach ($groups as $group) {
  4010. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  4011. // 剧本基本信息
  4012. if (!empty($group['intro'])) {
  4013. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  4014. }
  4015. if (!empty($group['highlights'])) {
  4016. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  4017. }
  4018. if (!empty($group['role_relationship'])) {
  4019. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  4020. }
  4021. if (!empty($group['core_contradiction'])) {
  4022. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  4023. }
  4024. if (!empty($group['roles']) && is_array($group['roles'])) {
  4025. $content .= "###主体列表\n";
  4026. foreach ($group['roles'] as $role) {
  4027. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  4028. }
  4029. $content .= "\n\n";
  4030. }
  4031. if (!empty($group['art_style'])) {
  4032. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  4033. }
  4034. // 场景信息
  4035. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4036. $content .= "###场景列表\n";
  4037. foreach ($group['scenes'] as $scene) {
  4038. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  4039. }
  4040. $content .= "\n\n";
  4041. }
  4042. // 分集内容
  4043. if (!empty($group['episode_content'])) {
  4044. $content .= "###分集剧本\n";
  4045. $content .= $group['episode_content'];
  4046. // foreach ($script['episodes'] as $episode) {
  4047. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  4048. // // if (!empty($episode['episode_name'])) {
  4049. // // $content .= ":" . $episode['episode_name'];
  4050. // // }
  4051. // // $content .= "\n";
  4052. // $content .= $episode['episode_content'] . "\n\n";
  4053. // }
  4054. }
  4055. }
  4056. return $content;
  4057. }
  4058. /**
  4059. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4060. *
  4061. * @param array $data 包含以下参数:
  4062. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4063. * - question: 用户问题(可选)
  4064. * - model: 使用的模型(r1 或 v3,默认 v3)
  4065. * @return \Generator 返回生成器,用于流式输出
  4066. */
  4067. public function addChat($data) {
  4068. $uid = Site::getUid();
  4069. $anime_id = getProp($data, 'anime_id');
  4070. if (!$anime_id) Utils::throwError('20003:请选择对话');
  4071. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4072. if (!$anime) Utils::throwError('20003:对话不存在');
  4073. $file = getProp($data, 'file');
  4074. $content = getProp($data, 'content', '');
  4075. $bid = getProp($data, 'bid', 0);
  4076. $script_id = getProp($data, 'script_id', 0);
  4077. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  4078. $prompt = getProp($data, 'prompt');
  4079. $user_anime_name = getProp($anime, 'anime_name');
  4080. // 处理文本模型
  4081. $model = getProp($data, 'model');
  4082. if (!$model) {
  4083. // 用户没有输入,从anime表获取
  4084. $model = getProp($anime, 'model');
  4085. if (!$model) {
  4086. // anime表也没有,使用默认值
  4087. $model = 'doubao-seed-2-0-mini-260215';
  4088. }
  4089. }
  4090. // 验证模型是否在可用模型表中
  4091. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4092. $model = 'doubao-seed-2-0-mini-260215';
  4093. }
  4094. $is_multi = getProp($anime, 'is_multi');
  4095. $is_single = (int)$is_multi !== 1;
  4096. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4097. if ($prompt) {
  4098. $question .= "本次修改要求如下:\n{$prompt}";
  4099. }
  4100. // if (!$file && !$content && !$bid) {
  4101. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4102. // }
  4103. // 提取文件内容
  4104. if ($file) {
  4105. $content = $this->extractFileContent($file);
  4106. if (!$content) {
  4107. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4108. }
  4109. } elseif ($script_id) {
  4110. $content = $this->getContentByScriptId($script_id);
  4111. if (!$content) {
  4112. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4113. }
  4114. } elseif ($bid) {
  4115. $content = $this->getContentByBid($bid);
  4116. if (!$content) {
  4117. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4118. }
  4119. } elseif ($content) {
  4120. $content = filterContent($content);
  4121. } else {
  4122. $content = getProp($anime, 'content');
  4123. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4124. $need_generate_content = true;
  4125. }
  4126. }
  4127. // 美术风格
  4128. $input_art_style = getProp($data, 'art_style');
  4129. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4130. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4131. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4132. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4133. 中年女:邻居阿姨
  4134. 老年男:幽默大爷
  4135. 老年女:婆婆
  4136. 萌娃:奶气萌娃";
  4137. // 判断是否需要生成原文内容
  4138. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4139. // 如果需要生成原文内容,添加额外的要求
  4140. $content_generation_requirement = $need_generate_content
  4141. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4142. : "";
  4143. // 美术风格
  4144. if (!$mappedArtStyle) {
  4145. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4146. }else {
  4147. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4148. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4149. }else {
  4150. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4151. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4152. }
  4153. }
  4154. $systemPrompt = $is_single
  4155. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4156. 强制要求:
  4157. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4158. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4159. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4160. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4161. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4162. 普通要求:
  4163. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4164. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4165. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  4166. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4167. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4168. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4169. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4170. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4171. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4172. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4173. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4174. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4175. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4176. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4177. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4178. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4179. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4180. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4181. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4182. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4183. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4184. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4185. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4186. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4187. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4188. 5.{$mappedArtStyle_prompt}\n\n
  4189. 示例如下:\n
  4190. ###剧本名:西昆仑
  4191. ###故事梗概
  4192. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4193. ###剧本亮点
  4194. 亮点1:绝境奇药,生死一线
  4195. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4196. 亮点2:结拜兄妹,化解尴尬
  4197. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4198. 亮点3:纤发夺命,情愫暗涌
  4199. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4200. ###人物关系
  4201. 阿雪与梁萧之间存在兄妹之情。
  4202. ###核心矛盾
  4203. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4204. ###主体列表
  4205. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4206. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4207. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4208. 姿态:站立。}{{甜心小美}}
  4209. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4210. 全景,正面拍摄,青年女性,亚洲人。
  4211. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4212. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4213. 姿态:站立。}{{阳光青年}}
  4214. ###美术风格
  4215. 基础画风风格词:厚涂古风
  4216. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4217. ###场景列表
  4218. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4219. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4220. 无人物。}
  4221. ###分镜剧本
  4222. ##第1幕:徐家老旧厨房 白天 室内
  4223. 分镜1
  4224. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4225. 场景:徐家老旧厨房
  4226. 构图设计:全景,低角度仰视
  4227. 运镜调度:手持拍摄
  4228. 配音角色:旁白
  4229. 出镜角色:许芸-校服装、徐母
  4230. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4231. 画面类型:普通画面
  4232. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4233. 分镜2
  4234. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4235. 场景:徐家老旧厨房
  4236. 构图设计:近景,徐母面部特写
  4237. 运镜调度:固定镜头
  4238. 配音角色:徐母
  4239. 出镜角色:徐母
  4240. 台词内容:问我夜不归宿死哪儿去了。
  4241. 画面类型:对口型
  4242. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4243. ##第2幕:徐家简陋客厅 黄昏 室内
  4244. 分镜3
  4245. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4246. 场景:徐家简陋客厅
  4247. 构图设计:全景,景深虚化
  4248. 运镜调度:固定镜头
  4249. 配音角色:旁白
  4250. 出镜角色:无
  4251. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4252. 画面类型:普通画面
  4253. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4254. 分镜4
  4255. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4256. 场景:徐家简陋客厅
  4257. 构图设计:特写,火车票
  4258. 运镜调度:固定镜头
  4259. 配音角色:旁白
  4260. 出镜角色:无
  4261. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4262. 画面类型:普通画面
  4263. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4264. "
  4265. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4266. 强制要求:\n
  4267. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4268. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4269. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4270. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4271. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4272. 普通要求:\n
  4273. 1.剧本名(必须生成)必须与文档内容高度相关
  4274. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4275. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4276. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4277. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4278. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4279. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4280. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4281. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4282. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4283. 4.{$mappedArtStyle_prompt}\n\n
  4284. 示例如下:\n
  4285. ###剧本名:西昆仑
  4286. ###故事梗概
  4287. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4288. ###剧本亮点
  4289. 亮点1:绝境奇药,生死一线
  4290. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4291. 亮点2:结拜兄妹,化解尴尬
  4292. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4293. 亮点3:纤发夺命,情愫暗涌
  4294. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4295. ###人物关系
  4296. 阿雪与梁萧之间存在兄妹之情。
  4297. ###核心矛盾
  4298. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4299. ###主体列表
  4300. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4301. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4302. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4303. 姿态:站立。}{{甜心小美}}
  4304. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4305. 全景,正面拍摄,青年女性,亚洲人。
  4306. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4307. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4308. 姿态:站立。}{{阳光青年}}
  4309. ###美术风格
  4310. 基础画风风格词:厚涂古风
  4311. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4312. ###场景列表
  4313. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4314. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4315. 无人物。}";
  4316. // 构建消息
  4317. $messages = [
  4318. [
  4319. 'role' => 'system',
  4320. 'content' => $systemPrompt
  4321. ],
  4322. [
  4323. 'role' => 'user',
  4324. 'content' => "以下是文档内容:
  4325. {$content}
  4326. 用户问题:
  4327. {$question}"
  4328. ]
  4329. ];
  4330. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4331. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4332. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4333. if ($model === 'deepseek-chat') {
  4334. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4335. $model = 'deepseek-v4-flash';
  4336. $thinkingMode = 'disabled';
  4337. } elseif ($model === 'deepseek-reasoner') {
  4338. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4339. $model = 'deepseek-v4-flash';
  4340. $thinkingMode = 'enabled';
  4341. }
  4342. $post_data = [
  4343. 'model' => $model,
  4344. 'messages' => $messages,
  4345. // 'max_tokens' => 8192,
  4346. 'temperature' => 0.7,
  4347. 'frequency_penalty' => 0,
  4348. 'presence_penalty' => 0,
  4349. 'response_format' => ['type' => 'text'],
  4350. 'thinking' => ['type'=>$thinkingMode],
  4351. 'stream' => true // 启用流式输出
  4352. ];
  4353. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4354. // 根据模型类型选择调用方法
  4355. $fullContent = '';
  4356. $fullReasoningContent = '';
  4357. $usage = [];
  4358. try {
  4359. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4360. // DeepSeek 官方模型使用 DeepSeek API
  4361. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4362. } else if (in_array($model, $this->gpt_text_models)) {
  4363. // GPT-5.4 模型使用 TokenRouter API
  4364. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4365. } else if (in_array($model, $this->gemini_text_models)) {
  4366. // Gemini 模型使用 Gemini API
  4367. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4368. } else {
  4369. // 其他模型使用火山引擎API
  4370. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4371. }
  4372. // 验证返回值类型
  4373. if (!is_iterable($streamGenerator)) {
  4374. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4375. dLog('deepseek')->error('addChat流式生成器无效', [
  4376. 'generator_type' => $errorType,
  4377. 'model' => $model,
  4378. 'anime_id' => $anime_id
  4379. ]);
  4380. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  4381. 'type' => $errorType,
  4382. 'model' => $model
  4383. ]);
  4384. yield [
  4385. 'type' => 'error',
  4386. 'script' => [],
  4387. 'episode' => [],
  4388. 'answer' => '',
  4389. 'reasoning' => '',
  4390. 'usage' => [],
  4391. 'error' => '接口返回数据异常,请重新请求'
  4392. ];
  4393. return;
  4394. }
  4395. // 处理流式输出
  4396. foreach ($streamGenerator as $chunk) {
  4397. if (isset($chunk['type'])) {
  4398. if ($chunk['type'] === 'done') {
  4399. // 最终结果
  4400. $fullContent = $chunk['full_content'];
  4401. $fullReasoningContent = $chunk['full_reasoning'];
  4402. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4403. } else {
  4404. // 逐块yield数据
  4405. yield $chunk;
  4406. }
  4407. }
  4408. }
  4409. } catch (\Exception $e) {
  4410. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  4411. 'model' => $model,
  4412. 'anime_id' => $anime_id,
  4413. 'trace' => $e->getTraceAsString()
  4414. ]);
  4415. logDB('deepseek', 'error', 'addChat流式处理失败', [
  4416. 'error' => $e->getMessage(),
  4417. 'model' => $model
  4418. ]);
  4419. yield [
  4420. 'type' => 'error',
  4421. 'script' => [],
  4422. 'episode' => [],
  4423. 'answer' => '',
  4424. 'reasoning' => '',
  4425. 'usage' => [],
  4426. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4427. ];
  4428. return;
  4429. }
  4430. dLog('deepseek')->info('完整内容: '.$fullContent);
  4431. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4432. // 处理完整内容并返回最终结果
  4433. $script_arr = [];
  4434. if ($fullContent) {
  4435. $script_arr = handleScriptContent($fullContent);
  4436. dLog('deepseek')->info('解析内容', $script_arr);
  4437. logDB('deepseek', 'info', '解析内容', $script_arr);
  4438. }
  4439. if (empty($script_arr['roles'])) {
  4440. // 未生成剧本相关内容,保存对话记录并返回提示
  4441. dLog('deepseek')->info('未生成剧本相关的内容');
  4442. try {
  4443. DB::beginTransaction();
  4444. $now = date('Y-m-d H:i:s');
  4445. // 保存对话记录
  4446. $records = [
  4447. [
  4448. 'uid' => $uid,
  4449. 'anime_id' => $anime_id,
  4450. 'sequence' => 0,
  4451. 'role' => 'user',
  4452. 'content' => $prompt,
  4453. 'created_at' => $now,
  4454. 'updated_at' => $now
  4455. ],
  4456. [
  4457. 'uid' => $uid,
  4458. 'anime_id' => $anime_id,
  4459. 'sequence' => 0,
  4460. 'role' => 'assistant',
  4461. // 'content' => $fullContent,
  4462. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  4463. 'created_at' => $now,
  4464. 'updated_at' => $now
  4465. ]
  4466. ];
  4467. DB::table('mp_anime_records')->insert($records);
  4468. DB::commit();
  4469. } catch (\Exception $e) {
  4470. DB::rollBack();
  4471. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4472. }
  4473. yield [
  4474. 'type' => 'done',
  4475. 'script' => [],
  4476. 'episode' => [],
  4477. 'answer' => $fullContent,
  4478. 'reasoning' => $fullReasoningContent,
  4479. 'usage' => $usage,
  4480. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4481. ];
  4482. return;
  4483. }
  4484. // 如果需要生成原文内容,从script_arr中提取
  4485. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4486. $content = $script_arr['content'];
  4487. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  4488. if (!$content) {
  4489. yield [
  4490. 'type' => 'done',
  4491. 'script' => [],
  4492. 'episode' => [],
  4493. 'answer' => $fullContent,
  4494. 'reasoning' => $fullReasoningContent,
  4495. 'usage' => $usage,
  4496. 'error' => '未生成剧本内容,请调整提示词再试'
  4497. ];
  4498. return;
  4499. }
  4500. }
  4501. // 替换美术风格
  4502. if ($mappedArtStyle !== '') {
  4503. $script_arr['art_style'] = $mappedArtStyle;
  4504. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4505. }
  4506. // 新建动漫
  4507. if ($user_anime_name == '新剧本策划') {
  4508. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  4509. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  4510. // if (!$anime_name) {
  4511. // // 未识别到剧本名,保存对话记录并返回提示
  4512. // dLog('deepseek')->info('未能识别到剧本名称');
  4513. // try {
  4514. // DB::beginTransaction();
  4515. // $now = date('Y-m-d H:i:s');
  4516. // // 保存对话记录
  4517. // $records = [
  4518. // [
  4519. // 'uid' => $uid,
  4520. // 'anime_id' => $anime_id,
  4521. // 'sequence' => 0,
  4522. // 'role' => 'user',
  4523. // 'content' => $prompt,
  4524. // 'created_at' => $now,
  4525. // 'updated_at' => $now
  4526. // ],
  4527. // [
  4528. // 'uid' => $uid,
  4529. // 'anime_id' => $anime_id,
  4530. // 'sequence' => 0,
  4531. // 'role' => 'assistant',
  4532. // 'content' => '未能生成剧本名称,请重试',
  4533. // 'created_at' => $now,
  4534. // 'updated_at' => $now
  4535. // ]
  4536. // ];
  4537. // DB::table('mp_anime_records')->insert($records);
  4538. // DB::commit();
  4539. // } catch (\Exception $e) {
  4540. // DB::rollBack();
  4541. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4542. // }
  4543. // yield [
  4544. // 'type' => 'done',
  4545. // 'script' => [],
  4546. // 'episode' => [],
  4547. // 'answer' => $fullContent,
  4548. // 'reasoning' => $fullReasoningContent,
  4549. // 'usage' => $usage,
  4550. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  4551. // ];
  4552. // return;
  4553. // }
  4554. // 确认对话名称唯一性
  4555. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4556. $anime_name = $anime_name . '_' . date('YmdHis');
  4557. }
  4558. }else {
  4559. $anime_name = $user_anime_name;
  4560. }
  4561. $table_data = [
  4562. 'user_id' => $uid,
  4563. 'anime_name' => $anime_name,
  4564. 'model' => $model,
  4565. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4566. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4567. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4568. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4569. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4570. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4571. 'art_style_type' => $input_art_style,
  4572. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4573. 'status' => '解析完成',
  4574. 'content' => $content,
  4575. 'is_multi' => $is_multi,
  4576. 'ace_mode' => $ace_mode,
  4577. 'generate_status' => '待执行',
  4578. 'updated_at' => date('Y-m-d H:i:s')
  4579. ];
  4580. if ($table_data['content']) {
  4581. $chapters = splitContent($table_data['content']);
  4582. $chapter_count = count($chapters);
  4583. if ($chapter_count > 0) {
  4584. $table_data['start_episode_sequence'] = 1;
  4585. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4586. }
  4587. }
  4588. // 如果有剧本ID则进行绑定
  4589. if ($script_id) {
  4590. $table_data['script_id'] = $script_id;
  4591. }
  4592. $single_episode = [];
  4593. try {
  4594. DB::beginTransaction();
  4595. $now = date('Y-m-d H:i:s');
  4596. // 更新动漫大纲
  4597. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4598. if (!$boolen) {
  4599. dLog('deepseek')->info('动漫保存失败', $table_data);
  4600. Utils::throwError('20003:动漫保存失败');
  4601. }
  4602. // 保存对话记录
  4603. $records = [
  4604. [
  4605. 'uid' => $uid,
  4606. 'anime_id' => $anime_id,
  4607. 'sequence' => 0,
  4608. 'role' => 'user',
  4609. 'content' => $prompt,
  4610. 'created_at' => date('Y-m-d H:i:s'),
  4611. 'updated_at' => date('Y-m-d H:i:s')
  4612. ],
  4613. [
  4614. 'uid' => $uid,
  4615. 'anime_id' => $anime_id,
  4616. 'sequence' => 0,
  4617. 'role' => 'assistant',
  4618. 'content' => $fullContent,
  4619. 'created_at' => date('Y-m-d H:i:s'),
  4620. 'updated_at' => date('Y-m-d H:i:s')
  4621. ]
  4622. ];
  4623. // 保存对话记录
  4624. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4625. if (!$boolen3) {
  4626. Utils::throwError('20003:对话记录保存失败');
  4627. }
  4628. if ($is_single) {
  4629. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4630. if (empty($episode_arr['acts'])) {
  4631. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4632. }
  4633. $saveResult = $this->saveEpisodeVersionData(
  4634. $anime_id,
  4635. 1,
  4636. $episode_arr,
  4637. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4638. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4639. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  4640. null,
  4641. null,
  4642. false,
  4643. $content,
  4644. $now
  4645. );
  4646. $single_episode = $saveResult['episode'];
  4647. $episode_id = $saveResult['episode_id'];
  4648. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4649. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4650. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4651. 'props' => json_encode($saveResult['merged_props'], 256),
  4652. 'updated_at' => $now
  4653. ]);
  4654. if ($boolen5 === false) {
  4655. Utils::throwError('20003:单剧集主表资源同步失败');
  4656. }
  4657. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4658. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4659. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  4660. $episode_record_content = '确认分镜大纲';
  4661. if ($content !== '') {
  4662. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4663. }
  4664. $episode_records = [
  4665. [
  4666. 'uid' => $uid,
  4667. 'anime_id' => $anime_id,
  4668. 'role' => 'user',
  4669. 'content' => $episode_record_content,
  4670. 'sequence' => 1,
  4671. 'episode_id' => $episode_id,
  4672. 'created_at' => $now,
  4673. 'updated_at' => $now
  4674. ],
  4675. [
  4676. 'uid' => $uid,
  4677. 'anime_id' => $anime_id,
  4678. 'role' => 'assistant',
  4679. 'content' => $fullContent,
  4680. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4681. 'sequence' => 1,
  4682. 'episode_id' => $episode_id,
  4683. 'created_at' => $now,
  4684. 'updated_at' => $now
  4685. ]
  4686. ];
  4687. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4688. if (!$boolen4) {
  4689. Utils::throwError('20003:单剧集分镜记录保存失败');
  4690. }
  4691. }
  4692. }catch (\Exception $e) {
  4693. DB::rollBack();
  4694. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  4695. yield [
  4696. 'type' => 'done',
  4697. 'answer' => $fullContent,
  4698. 'reasoning' => $fullReasoningContent,
  4699. 'usage' => $usage,
  4700. 'error' => $e->getMessage(),
  4701. ];
  4702. return;
  4703. }
  4704. DB::commit();
  4705. dLog('deepseek')->info('保存完毕');
  4706. if ($is_single && !empty($single_episode)) {
  4707. // $this->batchSetGlobalRoleImg([
  4708. // 'anime_id' => $anime_id,
  4709. // ]);
  4710. // $this->batchSetGlobalSceneImg([
  4711. // 'anime_id' => $anime_id,
  4712. // ]);
  4713. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4714. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4715. }
  4716. $table_data['anime_id'] = $anime_id;
  4717. $table_data['roles'] = json_decode($table_data['roles'], true);
  4718. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4719. // $table_data['episodes'] = $script_arr['episodes'];
  4720. unset($table_data['created_at']);
  4721. unset($table_data['updated_at']);
  4722. unset($table_data['status']);
  4723. dLog('deepseek')->info('开始返回');
  4724. yield [
  4725. 'type' => 'done',
  4726. 'script' => $table_data,
  4727. 'episode' => $single_episode,
  4728. 'answer' => $fullContent,
  4729. 'reasoning' => $fullReasoningContent,
  4730. 'usage' => $usage
  4731. ];
  4732. }
  4733. public function reGenerateAnime($data) {
  4734. $uid = Site::getUid();
  4735. $file = getProp($data, 'file');
  4736. $content = getProp($data, 'content', '');
  4737. $bid = getProp($data, 'bid', 0);
  4738. $script_id = getProp($data, 'script_id', 0);
  4739. $anime_id = getProp($data, 'anime_id');
  4740. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4741. if (!$anime) {
  4742. Utils::throwError('20003:该对话不存在');
  4743. }
  4744. $user_anime_name = getProp($anime, 'anime_name');
  4745. $prompt = getProp($data, 'prompt');
  4746. // 处理文本模型
  4747. $model = getProp($data, 'model');
  4748. if (!$model) {
  4749. // 用户没有输入,从anime表获取
  4750. $model = getProp($anime, 'model');
  4751. if (!$model) {
  4752. // anime表也没有,使用默认值
  4753. $model = 'doubao-seed-2-0-mini-260215';
  4754. }
  4755. }
  4756. // 验证模型是否在可用模型表中
  4757. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4758. $model = 'doubao-seed-2-0-mini-260215';
  4759. }
  4760. $is_multi = getProp($anime, 'is_multi', 1);
  4761. $is_single = (int)$is_multi !== 1;
  4762. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  4763. if ($is_single) {
  4764. $episode_exists = DB::table('mp_anime_episodes')
  4765. ->where('anime_id', $anime_id)
  4766. ->where('sequence', 1)
  4767. ->exists();
  4768. if ($episode_exists) {
  4769. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  4770. }
  4771. }
  4772. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4773. if ($prompt) {
  4774. $question .= "本次修改要求如下:\n{$prompt}";
  4775. }
  4776. // 提取文件内容
  4777. if ($file) {
  4778. $content = $this->extractFileContent($file);
  4779. if (!$content) {
  4780. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4781. }
  4782. } elseif ($script_id) {
  4783. $content = $this->getContentByScriptId($script_id);
  4784. if (!$content) {
  4785. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4786. }
  4787. } elseif ($bid) {
  4788. $content = $this->getContentByBid($bid);
  4789. if (!$content) {
  4790. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4791. }
  4792. } elseif ($content) {
  4793. $content = filterContent($content);
  4794. }else {
  4795. $content = filterContent(getProp($anime, 'content'));
  4796. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4797. $need_generate_content = true;
  4798. }
  4799. }
  4800. // 判断是否需要生成原文内容
  4801. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4802. // 如果需要生成原文内容,添加额外的要求
  4803. $content_generation_requirement = $need_generate_content
  4804. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4805. : "";
  4806. // 美术风格
  4807. $input_art_style = getProp($anime, 'art_style');
  4808. if (!$input_art_style) {
  4809. $input_art_style = getProp($data, 'art_style');
  4810. }
  4811. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4812. // 美术风格
  4813. if (!$mappedArtStyle) {
  4814. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4815. }else {
  4816. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4817. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4818. }else {
  4819. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4820. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4821. }
  4822. }
  4823. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4824. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4825. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4826. 中年女:邻居阿姨
  4827. 老年男:幽默大爷
  4828. 老年女:婆婆
  4829. 萌娃:奶气萌娃";
  4830. $system_message = ['role'=>'system', 'content'=>$is_single
  4831. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4832. 强制要求:
  4833. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4834. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4835. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4836. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4837. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4838. 普通要求:
  4839. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4840. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4841. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4842. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4843. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4844. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4845. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4846. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4847. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4848. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4849. 3.$mappedArtStyle_prompt\n\n
  4850. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4851. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4852. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4853. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4854. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4855. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4856. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4857. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4858. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4859. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4860. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4861. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4862. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4863. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4864. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4865. 示例如下:\n
  4866. ###剧本名:西昆仑
  4867. ###故事梗概
  4868. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4869. ###剧本亮点
  4870. 亮点1:绝境奇药,生死一线
  4871. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4872. 亮点2:结拜兄妹,化解尴尬
  4873. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4874. 亮点3:纤发夺命,情愫暗涌
  4875. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4876. ###人物关系
  4877. 阿雪与梁萧之间存在兄妹之情。
  4878. ###核心矛盾
  4879. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4880. ###主体列表
  4881. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4882. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4883. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4884. 姿态:站立。}{{甜心小美}}
  4885. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4886. 全景,正面拍摄,青年女性,亚洲人。
  4887. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4888. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4889. 姿态:站立。}{{阳光青年}}
  4890. ###美术风格
  4891. 基础画风风格词:厚涂古风
  4892. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4893. ###场景列表
  4894. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4895. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4896. 无人物。}
  4897. ###分镜剧本
  4898. ##第1幕:徐家老旧厨房 白天 室内
  4899. 分镜1
  4900. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4901. 场景:徐家老旧厨房
  4902. 构图设计:全景,低角度仰视
  4903. 运镜调度:手持拍摄
  4904. 配音角色:旁白
  4905. 出镜角色:许芸-校服装、徐母
  4906. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4907. 画面类型:普通画面
  4908. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4909. 分镜2
  4910. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4911. 场景:徐家老旧厨房
  4912. 构图设计:近景,徐母面部特写
  4913. 运镜调度:固定镜头
  4914. 配音角色:徐母
  4915. 出镜角色:徐母
  4916. 台词内容:问我夜不归宿死哪儿去了。
  4917. 画面类型:对口型
  4918. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4919. ##第2幕:徐家简陋客厅 黄昏 室内
  4920. 分镜3
  4921. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4922. 场景:徐家简陋客厅
  4923. 构图设计:全景,景深虚化
  4924. 运镜调度:固定镜头
  4925. 配音角色:旁白
  4926. 出镜角色:无
  4927. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4928. 画面类型:普通画面
  4929. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4930. 分镜4
  4931. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4932. 场景:徐家简陋客厅
  4933. 构图设计:特写,火车票
  4934. 运镜调度:固定镜头
  4935. 配音角色:旁白
  4936. 出镜角色:无
  4937. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4938. 画面类型:普通画面
  4939. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4940. "
  4941. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4942. 强制要求:\n
  4943. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4944. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4945. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4946. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4947. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4948. 普通要求:\n
  4949. 1.剧本名(必须生成)必须与文档内容高度相关
  4950. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4951. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4952. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4953. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4954. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4955. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4956. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4957. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4958. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4959. 4.$mappedArtStyle_prompt\n\n
  4960. 示例如下:\n
  4961. ###剧本名:西昆仑
  4962. ###故事梗概
  4963. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4964. ###剧本亮点
  4965. 亮点1:绝境奇药,生死一线
  4966. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4967. 亮点2:结拜兄妹,化解尴尬
  4968. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4969. 亮点3:纤发夺命,情愫暗涌
  4970. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4971. ###人物关系
  4972. 阿雪与梁萧之间存在兄妹之情。
  4973. ###核心矛盾
  4974. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4975. ###主体列表
  4976. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4977. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4978. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4979. 姿态:站立。}{{甜心小美}}
  4980. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4981. 全景,正面拍摄,青年女性,亚洲人。
  4982. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4983. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4984. 姿态:站立。}{{阳光青年}}
  4985. ###美术风格
  4986. 基础画风风格词:厚涂古风
  4987. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4988. ###场景列表
  4989. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4990. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4991. 无人物。}"];
  4992. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  4993. $episode_count = $this->extractEpisodeNumber($prompt);
  4994. if ((int)getProp($anime, 'is_multi') !== 1) {
  4995. yield [
  4996. 'type' => 'done',
  4997. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  4998. 'reasoning' => '',
  4999. 'usage' => []
  5000. ];
  5001. return;
  5002. }
  5003. if ($episode_count) {
  5004. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  5005. $system_message = [
  5006. 'role' => 'system',
  5007. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5008. 强制要求:\n
  5009. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5010. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5011. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5012. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5013. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5014. 普通要求:\n
  5015. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5016. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5017. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5018. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5019. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5020. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5021. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5022. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5023. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5024. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  5025. 示例如下:\n
  5026. ###剧本名:西昆仑
  5027. ###故事梗概
  5028. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5029. ###剧本亮点
  5030. 亮点1:绝境奇药,生死一线
  5031. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5032. 亮点2:结拜兄妹,化解尴尬
  5033. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5034. 亮点3:纤发夺命,情愫暗涌
  5035. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5036. ###人物关系
  5037. 阿雪与梁萧之间存在兄妹之情。
  5038. ###核心矛盾
  5039. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5040. ###主体列表
  5041. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5042. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5043. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5044. 姿态:站立。}{{甜心小美}}
  5045. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5046. 全景,正面拍摄,青年女性,亚洲人。
  5047. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5048. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5049. 姿态:站立。}{{阳光青年}}
  5050. ###美术风格
  5051. 基础画风风格词:厚涂古风
  5052. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5053. ###场景列表
  5054. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5055. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5056. 无人物。}
  5057. ###分集详细内容
  5058. ##第1章 重生
  5059. 我重生了。
  5060. 源于一个男人偏执的暗恋。
  5061. ##第2章 相救
  5062. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  5063. 我眼睛扫向站在锅炉后的卞大伟。"
  5064. ];
  5065. // 构建消息
  5066. $messages = [
  5067. $system_message,
  5068. [
  5069. 'role' => 'user',
  5070. 'content' => "以下是文档内容:
  5071. {$content}
  5072. 用户问题:
  5073. {$question}"
  5074. ]
  5075. ];
  5076. }else {
  5077. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  5078. // 构建消息
  5079. $messages = [
  5080. $system_message,
  5081. [
  5082. 'role' => 'user',
  5083. 'content' => "以下是文档内容:
  5084. {$content}
  5085. 用户问题:
  5086. {$question}"
  5087. ]
  5088. ];
  5089. }else {
  5090. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  5091. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  5092. return (array)$value;
  5093. })->toArray();
  5094. array_unshift($messages, $system_message);
  5095. $messages[] = [
  5096. 'role' => 'user',
  5097. 'content' => $prompt
  5098. ];
  5099. }
  5100. }
  5101. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5102. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5103. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5104. if ($model === 'deepseek-chat') {
  5105. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5106. $model = 'deepseek-v4-flash';
  5107. $thinkingMode = 'disabled';
  5108. } elseif ($model === 'deepseek-reasoner') {
  5109. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5110. $model = 'deepseek-v4-flash';
  5111. $thinkingMode = 'enabled';
  5112. }
  5113. $post_data = [
  5114. 'model' => $model,
  5115. 'messages' => $messages,
  5116. // 'max_tokens' => 8192,
  5117. 'temperature' => 0.7,
  5118. 'frequency_penalty' => 0,
  5119. 'presence_penalty' => 0,
  5120. 'response_format' => ['type' => 'text'],
  5121. 'thinking' => ['type' => $thinkingMode],
  5122. 'stream' => true // 启用流式输出
  5123. ];
  5124. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5125. // 根据模型类型选择调用方法
  5126. $fullContent = '';
  5127. $fullReasoningContent = '';
  5128. $usage = [];
  5129. // dd($post_data);
  5130. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  5131. try {
  5132. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5133. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5134. } else if (in_array($model, $this->gpt_text_models)) {
  5135. // GPT-5.4 模型使用 TokenRouter API
  5136. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5137. } else if (in_array($model, $this->gemini_text_models)) {
  5138. // Gemini 模型使用 Gemini API
  5139. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  5140. } else {
  5141. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5142. }
  5143. // 验证返回值类型
  5144. if (!is_iterable($streamGenerator)) {
  5145. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5146. dLog('deepseek')->error('方法名流式生成器无效', [
  5147. 'generator_type' => $errorType,
  5148. 'model' => $model,
  5149. // 添加其他上下文信息
  5150. ]);
  5151. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  5152. 'type' => $errorType,
  5153. 'model' => $model
  5154. ]);
  5155. yield [
  5156. 'type' => 'error',
  5157. // 根据方法返回相应的空数据结构
  5158. 'answer' => '',
  5159. 'reasoning' => '',
  5160. 'usage' => [],
  5161. 'error' => '接口返回数据异常,请重新请求'
  5162. ];
  5163. return;
  5164. }
  5165. // 处理流式输出
  5166. foreach ($streamGenerator as $chunk) {
  5167. if (isset($chunk['type'])) {
  5168. if ($chunk['type'] === 'done') {
  5169. $fullContent = $chunk['full_content'];
  5170. $fullReasoningContent = $chunk['full_reasoning'];
  5171. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5172. } else {
  5173. yield $chunk;
  5174. }
  5175. }
  5176. }
  5177. } catch (\Exception $e) {
  5178. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  5179. 'model' => $model,
  5180. 'trace' => $e->getTraceAsString()
  5181. ]);
  5182. logDB('deepseek', 'error', '方法名流式处理失败', [
  5183. 'error' => $e->getMessage(),
  5184. 'model' => $model
  5185. ]);
  5186. yield [
  5187. 'type' => 'error',
  5188. // 根据方法返回相应的空数据结构
  5189. 'answer' => '',
  5190. 'reasoning' => '',
  5191. 'usage' => [],
  5192. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5193. ];
  5194. return;
  5195. }
  5196. dLog('deepseek')->info('完整内容: '.$fullContent);
  5197. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5198. // 处理完整内容并返回最终结果
  5199. $script_arr = [];
  5200. if ($fullContent) {
  5201. $script_arr = handleScriptContent($fullContent);
  5202. dLog('deepseek')->info('解析内容', $script_arr);
  5203. logDB('deepseek', 'info', '解析内容', $script_arr);
  5204. }
  5205. if (empty($script_arr['roles'])) {
  5206. // 未生成剧本相关内容,保存对话记录并返回提示
  5207. dLog('deepseek')->info('未生成剧本相关的内容');
  5208. try {
  5209. $now = date('Y-m-d H:i:s');
  5210. // 保存对话记录
  5211. $records = [
  5212. [
  5213. 'uid' => $uid,
  5214. 'anime_id' => $anime_id,
  5215. 'sequence' => 0,
  5216. 'role' => 'user',
  5217. 'content' => $prompt,
  5218. 'created_at' => $now,
  5219. 'updated_at' => $now
  5220. ],
  5221. [
  5222. 'uid' => $uid,
  5223. 'anime_id' => $anime_id,
  5224. 'sequence' => 0,
  5225. 'role' => 'assistant',
  5226. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  5227. 'created_at' => $now,
  5228. 'updated_at' => $now
  5229. ]
  5230. ];
  5231. DB::table('mp_anime_records')->insert($records);
  5232. } catch (\Exception $e) {
  5233. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5234. }
  5235. yield [
  5236. 'type' => 'done',
  5237. 'script' => [],
  5238. 'episode' => [],
  5239. 'answer' => $fullContent,
  5240. 'reasoning' => $fullReasoningContent,
  5241. 'usage' => $usage,
  5242. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5243. ];
  5244. return;
  5245. }
  5246. // 替换美术风格
  5247. if ($mappedArtStyle !== '') {
  5248. $script_arr['art_style'] = $mappedArtStyle;
  5249. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5250. }
  5251. if ($user_anime_name != '新剧本策划') {
  5252. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5253. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5254. // 确认对话名称唯一性
  5255. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5256. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  5257. }
  5258. }else {
  5259. $anime_name = $user_anime_name;
  5260. }
  5261. $table_data = [
  5262. 'user_id' => $uid,
  5263. 'model' => $model,
  5264. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5265. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5266. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5267. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5268. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5269. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5270. 'art_style_type' => $input_art_style,
  5271. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5272. 'status' => '解析完成',
  5273. 'generate_status' => '待执行',
  5274. 'updated_at' => date('Y-m-d H:i:s')
  5275. ];
  5276. if ($anime_name) $table_data['anime_name'] = $anime_name;
  5277. // 如果是修改集数,则将content内容更新(会改变原文)
  5278. if (isset($episode_count) && $episode_count > 0) {
  5279. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  5280. $table_data['start_episode_sequence'] = 1;
  5281. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  5282. }else {
  5283. // 如果需要生成原文内容,从script_arr中提取
  5284. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5285. $table_data['content'] = $script_arr['content'];
  5286. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  5287. if (!$table_data['content']) {
  5288. yield [
  5289. 'type' => 'done',
  5290. 'script' => [],
  5291. 'episode' => [],
  5292. 'answer' => $fullContent,
  5293. 'reasoning' => $fullReasoningContent,
  5294. 'usage' => $usage,
  5295. 'error' => '未生成剧本内容,请调整提示词再试'
  5296. ];
  5297. return;
  5298. }
  5299. }
  5300. if (isset($table_data['content']) && $table_data['content']) {
  5301. $chapters = splitContent($table_data['content']);
  5302. $chapter_count = count($chapters);
  5303. if ($chapter_count > 0) {
  5304. $table_data['start_episode_sequence'] = 1;
  5305. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5306. }
  5307. }
  5308. }
  5309. $single_episode = [];
  5310. try {
  5311. DB::beginTransaction();
  5312. $now = date('Y-m-d H:i:s');
  5313. // 更新动漫大纲
  5314. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5315. if (!$boolen) {
  5316. dLog('deepseek')->info('对话修改失败', $table_data);
  5317. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  5318. Utils::throwError('20003:对话修改失败');
  5319. }
  5320. // 保存对话记录
  5321. $records = [
  5322. [
  5323. 'uid' => $uid,
  5324. 'anime_id' => $anime_id,
  5325. 'sequence' => 0,
  5326. 'role' => 'user',
  5327. 'content' => $prompt,
  5328. 'created_at' => $now,
  5329. 'updated_at' => $now
  5330. ],
  5331. [
  5332. 'uid' => $uid,
  5333. 'anime_id' => $anime_id,
  5334. 'sequence' => 0,
  5335. 'role' => 'assistant',
  5336. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5337. 'content' => $fullContent,
  5338. 'created_at' => $now,
  5339. 'updated_at' => $now
  5340. ]
  5341. ];
  5342. // 保存对话记录
  5343. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5344. if (!$boolen3) {
  5345. Utils::throwError('20003:对话记录保存失败');
  5346. }
  5347. // 单剧集模式:生成并保存剧集信息
  5348. if ($is_single) {
  5349. $anime_name = getProp($anime, 'anime_name', '未命名');
  5350. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5351. if (empty($episode_arr['acts'])) {
  5352. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5353. }
  5354. $saveResult = $this->saveEpisodeVersionData(
  5355. $anime_id,
  5356. 1,
  5357. $episode_arr,
  5358. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5359. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5360. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5361. null,
  5362. null,
  5363. false,
  5364. $content,
  5365. $now
  5366. );
  5367. $single_episode = $saveResult['episode'];
  5368. $episode_id = $saveResult['episode_id'];
  5369. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5370. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5371. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5372. 'props' => json_encode($saveResult['merged_props'], 256),
  5373. 'updated_at' => $now
  5374. ]);
  5375. if ($boolen5 === false) {
  5376. Utils::throwError('20003:单剧集主表资源同步失败');
  5377. }
  5378. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5379. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5380. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5381. $episode_record_content = '确认分镜大纲';
  5382. if ($content !== '') {
  5383. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5384. }
  5385. $episode_records = [
  5386. [
  5387. 'uid' => $uid,
  5388. 'anime_id' => $anime_id,
  5389. 'role' => 'user',
  5390. 'content' => $episode_record_content,
  5391. 'sequence' => 1,
  5392. 'episode_id' => $episode_id,
  5393. 'created_at' => $now,
  5394. 'updated_at' => $now
  5395. ],
  5396. [
  5397. 'uid' => $uid,
  5398. 'anime_id' => $anime_id,
  5399. 'role' => 'assistant',
  5400. 'content' => $fullContent,
  5401. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5402. 'sequence' => 1,
  5403. 'episode_id' => $episode_id,
  5404. 'created_at' => $now,
  5405. 'updated_at' => $now
  5406. ]
  5407. ];
  5408. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5409. if (!$boolen4) {
  5410. Utils::throwError('20003:单剧集分镜记录保存失败');
  5411. }
  5412. }
  5413. }catch (\Exception $e) {
  5414. DB::rollBack();
  5415. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  5416. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  5417. yield [
  5418. 'type' => 'done',
  5419. 'answer' => $fullContent,
  5420. 'reasoning' => $fullReasoningContent,
  5421. 'usage' => $usage,
  5422. 'error' => $e->getMessage(),
  5423. ];
  5424. return;
  5425. }
  5426. DB::commit();
  5427. dLog('deepseek')->info('保存完毕');
  5428. if ($is_single && !empty($single_episode)) {
  5429. // $this->batchSetGlobalRoleImg([
  5430. // 'anime_id' => $anime_id,
  5431. // ]);
  5432. // $this->batchSetGlobalSceneImg([
  5433. // 'anime_id' => $anime_id,
  5434. // ]);
  5435. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5436. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5437. }
  5438. $table_data['anime_id'] = $anime_id;
  5439. $table_data['roles'] = json_decode($table_data['roles'], true);
  5440. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5441. unset($table_data['updated_at']);
  5442. unset($table_data['status']);
  5443. yield [
  5444. 'type' => 'done',
  5445. 'script' => $table_data,
  5446. 'episode' => $single_episode,
  5447. 'answer' => $fullContent,
  5448. 'reasoning' => $fullReasoningContent,
  5449. 'usage' => $usage
  5450. ];
  5451. }
  5452. public function chat($data) {
  5453. $uid = Site::getUid();
  5454. $anime_id = getProp($data, 'anime_id');
  5455. $file = getProp($data, 'file');
  5456. $content = getProp($data, 'content', '');
  5457. $bid = getProp($data, 'bid', 0);
  5458. $script_id = getProp($data, 'script_id', 0);
  5459. $episode_number = getProp($data, 'episode_number', 1);
  5460. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5461. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5462. if (!$anime) Utils::throwError('20003:该对话不存在!');
  5463. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  5464. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  5465. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  5466. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  5467. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  5468. $roles = is_array($roles) ? $roles : [];
  5469. $scenes = is_array($scenes) ? $scenes : [];
  5470. // 获取最后一集序号
  5471. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  5472. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  5473. // 转换主体列表和场景列表的格式
  5474. // 获取参考主体或场景
  5475. if ((int)$episode_number === 1) {
  5476. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  5477. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  5478. }else {
  5479. $prev_episode_number = $episode_number - 1;
  5480. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  5481. }
  5482. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  5483. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  5484. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  5485. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  5486. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5487. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5488. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5489. 中年女:邻居阿姨
  5490. 老年男:幽默大爷
  5491. 老年女:婆婆
  5492. 萌娃:奶气萌娃";
  5493. if ($roles_content) {
  5494. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  5495. 主体范围:\n {$roles_content}\n
  5496. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  5497. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5498. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  5499. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5500. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  5501. }else {
  5502. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5503. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5504. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  5505. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5506. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  5507. }
  5508. if ($scenes_content) {
  5509. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  5510. 场景范围:\n {$scenes_content}\n
  5511. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  5512. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5513. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5514. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  5515. }else {
  5516. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5517. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5518. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5519. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  5520. }
  5521. // 提取文件内容
  5522. if ($file) {
  5523. $uploaded_content = $this->extractFileContent($file);
  5524. if (!$uploaded_content) {
  5525. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5526. }
  5527. } elseif ($script_id) {
  5528. $uploaded_content = $this->getContentByScriptId($script_id);
  5529. if (!$uploaded_content) {
  5530. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5531. }
  5532. } elseif ($bid) {
  5533. $uploaded_content = $this->getContentByBid($bid);
  5534. if (!$uploaded_content) {
  5535. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5536. }
  5537. } elseif ($content) {
  5538. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  5539. }
  5540. // elseif ($prompt) {
  5541. // $uploaded_content = filterContent($prompt);
  5542. // }
  5543. else {
  5544. $uploaded_content = '';
  5545. }
  5546. $input_art_style = getProp($anime, 'art_style');
  5547. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5548. // 美术风格
  5549. if (!$mappedArtStyle) {
  5550. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5551. }else {
  5552. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5553. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5554. }else {
  5555. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5556. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5557. }
  5558. }
  5559. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5560. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5561. // 强制要求:
  5562. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5563. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5564. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5565. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  5566. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  5567. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  5568. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  5569. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  5570. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  5571. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  5572. // - 分镜要和场景列表、人物主体保持一致\n
  5573. // 普通要求:
  5574. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  5575. // {$role_demo}
  5576. // {$scene_demo}
  5577. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5578. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5579. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5580. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5581. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  5582. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5583. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5584. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5585. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5586. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5587. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5588. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5589. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5590. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5591. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  5592. // 5.$mappedArtStyle_prompt\n\n
  5593. // 示例格式:\n
  5594. // 第1集:隐形的守护者
  5595. // ###故事梗概
  5596. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5597. // ###美术风格
  5598. // 基础画风风格词:韩漫二次元
  5599. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  5600. // ###主体列表
  5601. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  5602. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  5603. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  5604. // ###场景列表
  5605. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  5606. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5607. // 无人物。}
  5608. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  5609. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  5610. // 无人物。}
  5611. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  5612. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  5613. // 无人物。}
  5614. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  5615. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  5616. // 无人物。}
  5617. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  5618. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  5619. // 无人物。}
  5620. // ###分镜剧本
  5621. // ##第1幕:徐家老旧厨房 白天 室内
  5622. // 分镜1
  5623. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5624. // 场景:徐家老旧厨房
  5625. // 构图设计:全景,低角度仰视
  5626. // 运镜调度:手持拍摄
  5627. // 配音角色:旁白
  5628. // 出镜角色:许芸-校服装、徐母
  5629. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5630. // 画面类型:普通画面
  5631. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5632. // 分镜2
  5633. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5634. // 场景:徐家老旧厨房
  5635. // 构图设计:近景,徐母面部特写
  5636. // 运镜调度:固定镜头
  5637. // 配音角色:徐母
  5638. // 出镜角色:徐母
  5639. // 台词内容:问我夜不归宿死哪儿去了。
  5640. // 画面类型:对口型
  5641. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5642. // ##第2幕:徐家简陋客厅 黄昏 室内
  5643. // 分镜3
  5644. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5645. // 场景:徐家简陋客厅
  5646. // 构图设计:全景,景深虚化
  5647. // 运镜调度:固定镜头
  5648. // 配音角色:旁白
  5649. // 出镜角色:无
  5650. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5651. // 画面类型:普通画面
  5652. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5653. // 分镜4
  5654. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5655. // 场景:徐家简陋客厅
  5656. // 构图设计:特写,火车票
  5657. // 运镜调度:固定镜头
  5658. // 配音角色:旁白
  5659. // 出镜角色:无
  5660. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5661. // 画面类型:普通画面
  5662. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  5663. // \n\n";
  5664. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  5665. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  5666. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  5667. 普通要求:
  5668. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  5669. {$role_demo}
  5670. {$scene_demo}
  5671. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5672. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5673. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5674. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  5675. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  5676. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5677. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5678. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5679. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5680. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5681. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5682. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5683. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5684. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5685. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  5686. 5.$mappedArtStyle_prompt
  5687. 6.《情绪-视听语言映射表》:
  5688. 6.1 场景空间与时间心理学 (Scene & Temporality)
  5689. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  5690. -----|---------|------------|----------------
  5691. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  5692. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  5693. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  5694. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  5695. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  5696. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  5697. -----|---------|------------|----------------
  5698. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  5699. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  5700. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  5701. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  5702. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  5703. --------|---------|--------------|-------------
  5704. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  5705. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  5706. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  5707. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  5708. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  5709. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  5710. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  5711. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  5712. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  5713. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  5714. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  5715. -----|---------|------------|------------
  5716. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  5717. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  5718. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  5719. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  5720. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  5721. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  5722. --------|---------|--------------|----------
  5723. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  5724. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  5725. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  5726. 6.6 声音设计与潜意识影响 (Soundscape)
  5727. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  5728. -----|---------|------------|------------------
  5729. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  5730. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  5731. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  5732. 理论基石:
  5733. - The Five C's of Cinematography by Joseph V. Mascelli
  5734. - Film Art: An Introduction by David Bordwell
  5735. - Sight, Sound, Motion by Herbert Zettl
  5736. - Notes on the Cinematograph by Robert Bresson
  5737. \n\n
  5738. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  5739. 示例格式:\n
  5740. 第1集:隐形的守护者
  5741. ###故事梗概
  5742. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5743. ###美术风格
  5744. 基础画风风格词:韩漫二次元
  5745. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  5746. ###主体列表
  5747. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  5748. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  5749. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  5750. ###场景列表
  5751. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  5752. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5753. 无人物。}
  5754. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  5755. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  5756. 无人物。}
  5757. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  5758. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  5759. 无人物。}
  5760. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  5761. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  5762. 无人物。}
  5763. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  5764. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  5765. 无人物。}
  5766. ###分镜剧本
  5767. ##第1幕:徐家老旧厨房 白天 室内
  5768. 分镜1
  5769. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5770. 场景:徐家老旧厨房
  5771. 构图设计:全景,低角度仰视
  5772. 运镜调度:手持拍摄
  5773. 配音角色:旁白
  5774. 出镜角色:许芸-校服装、徐母
  5775. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5776. 画面类型:普通画面
  5777. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5778. 分镜2
  5779. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5780. 场景:徐家老旧厨房
  5781. 构图设计:近景,徐母面部特写
  5782. 运镜调度:固定镜头
  5783. 配音角色:徐母
  5784. 出镜角色:徐母
  5785. 台词内容:问我夜不归宿死哪儿去了。
  5786. 画面类型:对口型
  5787. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5788. ##第2幕:徐家简陋客厅 黄昏 室内
  5789. 分镜3
  5790. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5791. 场景:徐家简陋客厅
  5792. 构图设计:全景,景深虚化
  5793. 运镜调度:固定镜头
  5794. 配音角色:旁白
  5795. 出镜角色:无
  5796. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5797. 画面类型:普通画面
  5798. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5799. 分镜4
  5800. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5801. 场景:徐家简陋客厅
  5802. 构图设计:特写,火车票
  5803. 运镜调度:固定镜头
  5804. 配音角色:旁白
  5805. 出镜角色:无
  5806. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5807. 画面类型:普通画面
  5808. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  5809. \n\n";
  5810. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5811. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  5812. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  5813. $prompt = $origin_prompt;
  5814. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  5815. // 获取章节内容
  5816. $full_content = getProp($anime, 'content');
  5817. if ($uploaded_content) {
  5818. $full_content = $uploaded_content;
  5819. }
  5820. // 根据章节内容拆分章节
  5821. $chapters = splitContent($full_content);
  5822. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  5823. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  5824. $messages = [];
  5825. if ($prompt == '确认分镜大纲') {
  5826. // 暂时保留
  5827. $content = $chapter_content;
  5828. if ($is_single) $content = $full_content; // 单剧集使用全文
  5829. if (!$content) {
  5830. Utils::throwError('20003:章节内容无法获取,请确认');
  5831. }
  5832. $question = $is_single
  5833. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  5834. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  5835. // 构建消息
  5836. $messages[] =
  5837. [
  5838. 'role' => 'user',
  5839. 'content' => $question
  5840. ];
  5841. }else if ($prompt == '继续策划下一集') {
  5842. if ($is_single) {
  5843. Utils::throwError('20003:单剧集不支持继续策划下一集');
  5844. }
  5845. $content = $chapter_content;
  5846. if (!$content) {
  5847. Utils::throwError('20003:章节内容无法获取,请确认');
  5848. }
  5849. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  5850. // 获取上一集最后记录
  5851. $prev_sequence = $episode_number - 1;
  5852. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  5853. // 构建消息
  5854. $messages[] =
  5855. [
  5856. 'role' => 'user',
  5857. 'content' => $question
  5858. ];
  5859. }else {
  5860. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  5861. if (!$content) {
  5862. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  5863. }
  5864. if (!$content) {
  5865. Utils::throwError('20003:章节内容无法获取,请确认');
  5866. }
  5867. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  5868. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  5869. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  5870. if ($origin_prompt) {
  5871. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  5872. }
  5873. $messages[] =
  5874. [
  5875. 'role' => 'user',
  5876. 'content' => $question
  5877. ];
  5878. }
  5879. // 处理文本模型
  5880. $model = getProp($data, 'model');
  5881. if (!$model) {
  5882. // 用户没有输入,从anime表获取
  5883. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5884. $model = getProp($anime, 'model');
  5885. if (!$model) {
  5886. // anime表也没有,使用默认值
  5887. $model = 'doubao-seed-2-0-mini-260215';
  5888. }
  5889. }
  5890. // 验证模型是否在可用模型表中
  5891. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5892. $model = 'doubao-seed-2-0-mini-260215';
  5893. }
  5894. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5895. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5896. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5897. if ($model === 'deepseek-chat') {
  5898. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5899. $model = 'deepseek-v4-flash';
  5900. $thinkingMode = 'disabled';
  5901. } elseif ($model === 'deepseek-reasoner') {
  5902. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5903. $model = 'deepseek-v4-flash';
  5904. $thinkingMode = 'enabled';
  5905. }
  5906. $post_data = [
  5907. 'model' => $model,
  5908. 'messages' => $messages,
  5909. // 'max_tokens' => 8192,
  5910. 'temperature' => 0.2,
  5911. 'frequency_penalty' => 0,
  5912. 'presence_penalty' => 0,
  5913. 'response_format' => ['type' => 'text'],
  5914. 'thinking' => ['type' => $thinkingMode],
  5915. 'stream' => true // 启用流式输出
  5916. ];
  5917. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5918. // 根据模型类型选择调用方法
  5919. $fullContent = '';
  5920. $fullReasoningContent = '';
  5921. $usage = [];
  5922. try {
  5923. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5924. // DeepSeek 官方模型使用 DeepSeek API
  5925. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5926. } else if (in_array($model, $this->gpt_text_models)) {
  5927. // GPT-5.4 模型使用 TokenRouter API
  5928. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5929. } else if (in_array($model, $this->gemini_text_models)) {
  5930. // Gemini 模型使用 Gemini API
  5931. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  5932. } else {
  5933. // 其他模型使用火山引擎API
  5934. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5935. }
  5936. // 验证返回值类型
  5937. if (!is_iterable($streamGenerator)) {
  5938. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5939. dLog('deepseek')->error('chat流式生成器无效', [
  5940. 'generator_type' => $errorType,
  5941. 'model' => $model,
  5942. 'anime_id' => $anime_id,
  5943. 'episode_number' => $episode_number
  5944. ]);
  5945. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  5946. 'type' => $errorType,
  5947. 'model' => $model
  5948. ]);
  5949. yield [
  5950. 'type' => 'error',
  5951. 'episode' => [],
  5952. 'answer' => '',
  5953. 'reasoning' => '',
  5954. 'usage' => [],
  5955. 'error' => '接口返回数据异常,请重新请求'
  5956. ];
  5957. return;
  5958. }
  5959. // 处理流式输出
  5960. foreach ($streamGenerator as $chunk) {
  5961. if (isset($chunk['type'])) {
  5962. if ($chunk['type'] === 'done') {
  5963. // 最终结果
  5964. $fullContent = $chunk['full_content'];
  5965. $fullReasoningContent = $chunk['full_reasoning'];
  5966. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5967. } else {
  5968. // 逐块yield数据
  5969. yield $chunk;
  5970. }
  5971. }
  5972. }
  5973. } catch (\Exception $e) {
  5974. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  5975. 'model' => $model,
  5976. 'anime_id' => $anime_id,
  5977. 'episode_number' => $episode_number,
  5978. 'trace' => $e->getTraceAsString()
  5979. ]);
  5980. logDB('deepseek', 'error', 'chat流式处理失败', [
  5981. 'error' => $e->getMessage(),
  5982. 'model' => $model
  5983. ]);
  5984. yield [
  5985. 'type' => 'error',
  5986. 'episode' => [],
  5987. 'answer' => '',
  5988. 'reasoning' => '',
  5989. 'usage' => [],
  5990. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5991. ];
  5992. return;
  5993. }
  5994. dLog('deepseek')->info('完整内容: '.$fullContent);
  5995. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5996. // 处理完整内容并返回最终结果
  5997. $episode_arr = handleEpisodeContent($fullContent);
  5998. logDB('deepseek', 'info', '解析内容', $episode_arr);
  5999. if (empty($episode_arr['acts'])) {
  6000. // 未生成剧本相关内容,保存对话记录并返回提示
  6001. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  6002. try {
  6003. $now = date('Y-m-d H:i:s');
  6004. // 保存对话记录
  6005. $records = [
  6006. [
  6007. 'uid' => $uid,
  6008. 'anime_id' => $anime_id,
  6009. 'sequence' => $episode_number,
  6010. 'role' => 'user',
  6011. 'content' => $prompt,
  6012. 'created_at' => $now,
  6013. 'updated_at' => $now
  6014. ],
  6015. [
  6016. 'uid' => $uid,
  6017. 'anime_id' => $anime_id,
  6018. 'sequence' => $episode_number,
  6019. 'role' => 'assistant',
  6020. 'content' => $fullContent,
  6021. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6022. 'created_at' => $now,
  6023. 'updated_at' => $now
  6024. ]
  6025. ];
  6026. DB::table('mp_anime_records')->insert($records);
  6027. } catch (\Exception $e) {
  6028. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6029. }
  6030. yield [
  6031. 'type' => 'done',
  6032. 'episode' => [],
  6033. 'answer' => $fullContent,
  6034. 'reasoning' => $fullReasoningContent,
  6035. 'usage' => $usage,
  6036. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  6037. ];
  6038. return;
  6039. }
  6040. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  6041. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  6042. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  6043. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  6044. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  6045. $existing_props = is_array($existing_props) ? $existing_props : [];
  6046. $now = date('Y-m-d H:i:s');
  6047. try {
  6048. DB::beginTransaction();
  6049. $saveResult = $this->saveEpisodeVersionData(
  6050. $anime_id,
  6051. $episode_number,
  6052. $episode_arr,
  6053. $existing_roles,
  6054. $existing_scenes,
  6055. $existing_props,
  6056. $current_episode,
  6057. $base_episode,
  6058. $is_regenerate_version,
  6059. $content,
  6060. $now
  6061. );
  6062. $episode = $saveResult['episode'];
  6063. $episode_id = $saveResult['episode_id'];
  6064. $merged_roles = $saveResult['merged_roles'];
  6065. $merged_scenes = $saveResult['merged_scenes'];
  6066. $merged_props = $saveResult['merged_props'];
  6067. $record_content = $origin_prompt;
  6068. if ($uploaded_content !== '') {
  6069. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  6070. }
  6071. $records = [
  6072. [
  6073. 'uid' => $uid,
  6074. 'anime_id' => $anime_id,
  6075. 'role' => 'user',
  6076. 'content' => $record_content,
  6077. 'sequence' => $episode_number,
  6078. 'episode_id' => $episode_id,
  6079. 'created_at' => $now,
  6080. 'updated_at' => $now
  6081. ],
  6082. [
  6083. 'uid' => $uid,
  6084. 'anime_id' => $anime_id,
  6085. 'role' => 'assistant',
  6086. 'content' => $fullContent,
  6087. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6088. 'sequence' => $episode_number,
  6089. 'episode_id' => $episode_id,
  6090. 'created_at' => $now,
  6091. 'updated_at' => $now
  6092. ]
  6093. ];
  6094. $boolen4 = DB::table('mp_anime_records')->insert($records);
  6095. if (!$boolen4) {
  6096. Utils::throwError('20003:对话记录保存失败');
  6097. }
  6098. // 保存模型和内容到anime表
  6099. $update_anime_data = [
  6100. 'model' => $model,
  6101. 'updated_at' => $now
  6102. ];
  6103. if ($uploaded_content) {
  6104. $update_anime_data['content'] = $uploaded_content;
  6105. }
  6106. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  6107. }catch (\Exception $e) {
  6108. DB::rollBack();
  6109. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6110. yield [
  6111. 'type' => 'done',
  6112. 'answer' => $fullContent,
  6113. 'reasoning' => $fullReasoningContent,
  6114. 'usage' => $usage,
  6115. 'error' => $e->getMessage(),
  6116. ];
  6117. return;
  6118. }
  6119. DB::commit();
  6120. if ($is_global_generate_pics) {
  6121. // // 批量生成全局角色图片
  6122. // $this->batchSetGlobalRoleImg([
  6123. // 'anime_id' => $anime_id,
  6124. // ], true);
  6125. // // 批量生成全局场景图片
  6126. // $this->batchSetGlobalSceneImg([
  6127. // 'anime_id' => $anime_id,
  6128. // ], true);
  6129. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6130. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6131. }
  6132. $episode['episode_id'] = $episode_id;
  6133. $episode['roles'] = $merged_roles;
  6134. $episode['scenes'] = $merged_scenes;
  6135. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  6136. yield [
  6137. 'type' => 'done',
  6138. 'episode' => $episode,
  6139. 'answer' => $fullContent,
  6140. 'reasoning' => $fullReasoningContent,
  6141. 'usage' => $usage
  6142. ];
  6143. }
  6144. public function addChatForAce($data) {
  6145. $uid = Site::getUid();
  6146. $anime_id = getProp($data, 'anime_id');
  6147. if (!$anime_id) Utils::throwError('20003:请选择对话');
  6148. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  6149. if (!$anime) Utils::throwError('20003:对话不存在');
  6150. $file = getProp($data, 'file');
  6151. $content = getProp($data, 'content', '');
  6152. $bid = getProp($data, 'bid', 0);
  6153. $script_id = getProp($data, 'script_id', 0);
  6154. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  6155. $prompt = getProp($data, 'prompt');
  6156. $is_multi = getProp($anime, 'is_multi');
  6157. $is_single = (int)$is_multi !== 1;
  6158. $extra_products = getProp($data, 'products', []);
  6159. if (!$extra_products) {
  6160. $extra_products = getProp($anime, 'extra_products');
  6161. if ($extra_products) {
  6162. $extra_products = json_decode($extra_products, true);
  6163. }else {
  6164. $extra_products = [];
  6165. }
  6166. }else {
  6167. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6168. }
  6169. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6170. $anime_script_id = getProp($anime, 'script_id');
  6171. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  6172. $cpid = Site::getCpid();
  6173. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6174. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6175. ->where('mapping.script_id', $anime_script_id)
  6176. ->where('product.cpid', $cpid)
  6177. ->where('product.is_deleted', 0);
  6178. $mappings = $script_products_mappings->select(
  6179. 'mapping.product_id',
  6180. 'mapping.episode_number',
  6181. 'product.product_name',
  6182. 'product.type',
  6183. 'product.product',
  6184. 'product.pic_prompt',
  6185. 'product.url',
  6186. 'product.pic_task_id',
  6187. 'product.pic_task_status',
  6188. 'product.three_view_image_url'
  6189. )
  6190. ->get();
  6191. // 按 product_id 分组,合并 episode_number
  6192. $productMap = [];
  6193. foreach ($mappings as $item) {
  6194. $product_id = $item->product_id;
  6195. $product_name = $item->product_name;
  6196. // 处理product_name两边的符号
  6197. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6198. if (!isset($productMap[$product_id])) {
  6199. $productMap[$product_id] = [
  6200. 'product_id' => $product_id,
  6201. 'product_name' => $product_name,
  6202. 'type' => (int)$item->type,
  6203. 'product' => (int)$item->product,
  6204. 'pic_prompt' => $item->pic_prompt,
  6205. 'url' => $item->url,
  6206. 'pic_task_id' => $item->pic_task_id,
  6207. 'pic_task_status' => $item->pic_task_status,
  6208. 'episode_numbers' => [],
  6209. ];
  6210. }
  6211. // 添加 episode_number(去重)
  6212. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6213. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6214. }
  6215. }
  6216. // 将查询到的剧本资产合并到extra_products中
  6217. // 先构建extra_products的索引(以product_id为key,用于去重)
  6218. $extraProductsMap = [];
  6219. foreach ($extra_products as $item) {
  6220. $key = getProp($item, 'product_id');
  6221. if ($key) {
  6222. $extraProductsMap[$key] = $item;
  6223. }
  6224. }
  6225. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6226. foreach ($productMap as $product) {
  6227. $product_id = $product['product_id'];
  6228. // 如果不存在则添加(不带episode_number信息)
  6229. if (!isset($extraProductsMap[$product_id])) {
  6230. $extraProductsMap[$product_id] = [
  6231. 'product_id' => $product['product_id'],
  6232. 'product_name' => $product['product_name'],
  6233. 'type' => $product['type'],
  6234. 'product' => $product['product'],
  6235. 'pic_prompt' => $product['pic_prompt'],
  6236. 'url' => $product['url'],
  6237. 'pic_task_id' => $product['pic_task_id'],
  6238. 'pic_task_status' => $product['pic_task_status'],
  6239. ];
  6240. }
  6241. }
  6242. // 重新赋值给extra_products
  6243. $extra_products = array_values($extraProductsMap);
  6244. }
  6245. $user_anime_name = getProp($anime, 'anime_name');
  6246. // 处理提示词
  6247. if ($prompt && $extra_products) {
  6248. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6249. foreach($extra_products as $item) {
  6250. $product_name = getProp($item, 'product_name');
  6251. if ($product_name) {
  6252. // 替换 {product_name} 为 product_name
  6253. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6254. }
  6255. }
  6256. }
  6257. // 处理文本模型
  6258. $model = getProp($data, 'model');
  6259. if (!$model) {
  6260. // 用户没有输入,从anime表获取
  6261. $model = getProp($anime, 'model');
  6262. if (!$model) {
  6263. // anime表也没有,使用默认值
  6264. $model = 'deepseek-v4-pro';
  6265. }
  6266. }
  6267. // 验证模型是否在可用模型表中
  6268. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6269. $model = 'deepseek-v4-pro';
  6270. }
  6271. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6272. if ($prompt) {
  6273. $question .= "本次修改要求如下:\n{$prompt}";
  6274. }
  6275. // if (!$file && !$content && !$bid) {
  6276. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  6277. // }
  6278. // 提取文件内容
  6279. if ($file) {
  6280. $content = $this->extractFileContent($file);
  6281. if (!$content) {
  6282. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6283. }
  6284. } elseif ($script_id) {
  6285. $content = $this->getContentByScriptId($script_id);
  6286. if (!$content) {
  6287. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6288. }
  6289. } elseif ($bid) {
  6290. $content = $this->getContentByBid($bid);
  6291. if (!$content) {
  6292. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6293. }
  6294. } elseif ($content) {
  6295. $content = filterContent($content);
  6296. } else {
  6297. $content = getProp($anime, 'content');
  6298. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6299. $need_generate_content = true;
  6300. }
  6301. }
  6302. // 美术风格
  6303. $input_art_style = getProp($data, 'art_style');
  6304. if (!$input_art_style) {
  6305. $mappedArtStyle = getProp($anime, 'art_style');
  6306. }else {
  6307. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6308. }
  6309. // 判断是否需要生成原文内容
  6310. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6311. // 如果需要生成原文内容,添加额外的要求
  6312. $content_generation_requirement = $need_generate_content
  6313. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6314. : "";
  6315. // 美术风格
  6316. if (!$mappedArtStyle) {
  6317. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6318. }else {
  6319. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6320. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6321. }else {
  6322. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6323. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6324. }
  6325. }
  6326. // 构建主体、场景和道具提示词
  6327. $extra_role_prompt = "\n";
  6328. $extra_scene_prompt = "\n";
  6329. $extra_prop_prompt = "\n";
  6330. $ref_products = []; // 参考资产
  6331. if ($extra_products) {
  6332. foreach($extra_products as $item) {
  6333. $product = getProp($item, 'product');
  6334. $product_name = getProp($item, 'product_name');
  6335. if ($product_name == '旁白') continue;
  6336. $ref_products[$product_name] = $item;
  6337. $pic_prompt = getProp($item, 'pic_prompt');
  6338. if ((int)$product === 1) {
  6339. // 拼接角色信息
  6340. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6341. } elseif ((int)$product === 2) {
  6342. // 拼接场景信息
  6343. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6344. } elseif ((int)$product === 3) {
  6345. // 拼接道具信息
  6346. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6347. }
  6348. }
  6349. // 优化提示词,融入剧本
  6350. if (!empty(trim($extra_role_prompt))) {
  6351. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6352. }
  6353. if (!empty(trim($extra_scene_prompt))) {
  6354. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6355. }
  6356. if (!empty(trim($extra_prop_prompt))) {
  6357. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6358. }
  6359. }
  6360. if ($anime_script_id && $is_single) {
  6361. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6362. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6363. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6364. }else {
  6365. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6366. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6367. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6368. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6369. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6370. {$extra_role_prompt}";
  6371. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6372. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6373. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6374. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6375. {$extra_scene_prompt}";
  6376. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6377. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6378. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6379. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6380. {$extra_prop_prompt}";
  6381. }
  6382. $systemPrompt = $is_single
  6383. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6384. 强制要求:
  6385. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6386. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6387. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6388. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6389. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6390. 普通要求:
  6391. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6392. $role_demo
  6393. $scene_demo
  6394. $prop_demo
  6395. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6396. 5.1片段分割逻辑(优先级从高到低):
  6397. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6398. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6399. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6400. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6401. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6402. - 片段数量格式为: 片段数量:8
  6403. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6404. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6405. 5.3分镜结构:每个分镜包含以下字段:
  6406. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6407. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6408. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6409. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6410. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6411. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6412. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6413. - 运镜:场景+画面描述+运镜
  6414. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  6415. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  6416. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6417. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6418. 6.{$mappedArtStyle_prompt}\n\n
  6419. 示例如下:\n
  6420. ###剧本名:西昆仑
  6421. ###故事梗概
  6422. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6423. ###剧本亮点
  6424. 亮点1:绝境奇药,生死一线
  6425. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6426. 亮点2:结拜兄妹,化解尴尬
  6427. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6428. 亮点3:纤发夺命,情愫暗涌
  6429. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6430. ###人物关系
  6431. 阿雪与梁萧之间存在兄妹之情。
  6432. ###核心矛盾
  6433. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6434. ###主体列表
  6435. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6436. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6437. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6438. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6439. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6440. 全景,正面拍摄,青年女性,亚洲人。
  6441. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6442. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6443. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6444. ###美术风格
  6445. 基础画风风格词:厚涂古风
  6446. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6447. ###场景列表
  6448. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6449. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6450. 无人物。}
  6451. ###分段剧本
  6452. 片段数量:8
  6453. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6454. ##片段1
  6455. 时长:12s
  6456. 分镜1
  6457. 出场角色:刀疤脸
  6458. 场景:边境小镇街道
  6459. 出场道具:酒杯-高脚杯
  6460. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6461. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6462. 配音台词:
  6463. 背景音效:
  6464. 分镜2
  6465. 出场角色:刀疤脸
  6466. 场景:悦来酒馆
  6467. 出场道具:酒杯-高脚杯
  6468. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6469. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6470. 配音台词:
  6471. 背景音效:
  6472. 分镜3
  6473. 出场角色:刀疤脸
  6474. 场景:悦来酒馆
  6475. 出场道具:酒杯-高脚杯
  6476. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6477. 运镜:从中景推向令牌特写。
  6478. 配音台词:
  6479. 背景音效:
  6480. 分镜4
  6481. 出场角色:刀疤脸
  6482. 场景:悦来酒馆
  6483. 出场道具:酒杯-高脚杯
  6484. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6485. 运镜:极速推向酒水溅起的瞬间。
  6486. 配音台词:
  6487. 背景音效:
  6488. 分镜5
  6489. 出场角色:刀疤脸
  6490. 场景:悦来酒馆
  6491. 出场道具:酒杯-高脚杯
  6492. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6493. 运镜:固定机位,利用倾斜构图制造压迫感。
  6494. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6495. 背景音效:
  6496. \n\n"
  6497. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6498. 强制要求:\n
  6499. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6500. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6501. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6502. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6503. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6504. 普通要求:\n
  6505. 1.剧本名(必须生成)必须与文档内容高度相关
  6506. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6507. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6508. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6509. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6510. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6511. {$extra_role_prompt}
  6512. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6513. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6514. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6515. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6516. {$extra_scene_prompt}
  6517. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6518. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6519. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6520. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6521. {$extra_prop_prompt}
  6522. 5.{$mappedArtStyle_prompt}\n\n
  6523. 示例如下:\n
  6524. ###剧本名:西昆仑
  6525. ###故事梗概
  6526. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6527. ###剧本亮点
  6528. 亮点1:绝境奇药,生死一线
  6529. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6530. 亮点2:结拜兄妹,化解尴尬
  6531. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6532. 亮点3:纤发夺命,情愫暗涌
  6533. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6534. ###人物关系
  6535. 阿雪与梁萧之间存在兄妹之情。
  6536. ###核心矛盾
  6537. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6538. ###主体列表
  6539. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6540. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6541. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6542. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6543. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6544. 全景,正面拍摄,青年女性,亚洲人。
  6545. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6546. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6547. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6548. ###美术风格
  6549. 基础画风风格词:厚涂古风
  6550. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6551. ###场景列表
  6552. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6553. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6554. 无人物。}
  6555. ###道具列表
  6556. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  6557. // 构建消息
  6558. $messages = [
  6559. [
  6560. 'role' => 'system',
  6561. 'content' => $systemPrompt
  6562. ],
  6563. [
  6564. 'role' => 'user',
  6565. 'content' => "以下是文档内容:
  6566. {$content}
  6567. 用户问题:
  6568. {$question}"
  6569. ]
  6570. ];
  6571. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6572. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6573. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6574. if ($model === 'deepseek-chat') {
  6575. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6576. $model = 'deepseek-v4-flash';
  6577. $thinkingMode = 'disabled';
  6578. } elseif ($model === 'deepseek-reasoner') {
  6579. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6580. $model = 'deepseek-v4-flash';
  6581. $thinkingMode = 'enabled';
  6582. }
  6583. $post_data = [
  6584. 'model' => $model,
  6585. 'messages' => $messages,
  6586. // 'max_tokens' => 8192,
  6587. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  6588. 'frequency_penalty' => 0,
  6589. 'presence_penalty' => 0,
  6590. 'response_format' => ['type' => 'text'],
  6591. 'thinking' => ['type'=>$thinkingMode],
  6592. 'stream' => true // 启用流式输出
  6593. ];
  6594. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6595. // 根据模型类型选择调用方法
  6596. $fullContent = '';
  6597. $fullReasoningContent = '';
  6598. $usage = [];
  6599. try {
  6600. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6601. // DeepSeek 官方模型使用 DeepSeek API
  6602. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6603. } else if (in_array($model, $this->gpt_text_models)) {
  6604. // GPT-5.4 模型使用 TokenRouter API
  6605. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6606. } else if (in_array($model, $this->gemini_text_models)) {
  6607. // Gemini 模型使用 Gemini API
  6608. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6609. } else {
  6610. // 其他模型使用火山引擎API
  6611. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6612. }
  6613. // 验证返回值类型
  6614. if (!is_iterable($streamGenerator)) {
  6615. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6616. dLog('deepseek')->error('addChat流式生成器无效', [
  6617. 'generator_type' => $errorType,
  6618. 'model' => $model,
  6619. 'anime_id' => $anime_id
  6620. ]);
  6621. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  6622. 'type' => $errorType,
  6623. 'model' => $model
  6624. ]);
  6625. yield [
  6626. 'type' => 'error',
  6627. 'script' => [],
  6628. 'episode' => [],
  6629. 'answer' => '',
  6630. 'reasoning' => '',
  6631. 'usage' => [],
  6632. 'error' => '接口返回数据异常,请重新请求'
  6633. ];
  6634. return;
  6635. }
  6636. // 处理流式输出
  6637. foreach ($streamGenerator as $chunk) {
  6638. if (isset($chunk['type'])) {
  6639. if ($chunk['type'] === 'done') {
  6640. // 最终结果
  6641. $fullContent = $chunk['full_content'];
  6642. $fullReasoningContent = $chunk['full_reasoning'];
  6643. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6644. } else {
  6645. // 逐块yield数据
  6646. yield $chunk;
  6647. }
  6648. }
  6649. }
  6650. } catch (\Exception $e) {
  6651. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  6652. 'model' => $model,
  6653. 'anime_id' => $anime_id,
  6654. 'trace' => $e->getTraceAsString()
  6655. ]);
  6656. logDB('deepseek', 'error', 'addChat流式处理失败', [
  6657. 'error' => $e->getMessage(),
  6658. 'model' => $model
  6659. ]);
  6660. yield [
  6661. 'type' => 'error',
  6662. 'script' => [],
  6663. 'episode' => [],
  6664. 'answer' => '',
  6665. 'reasoning' => '',
  6666. 'usage' => [],
  6667. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6668. ];
  6669. return;
  6670. }
  6671. dLog('deepseek')->info('完整内容: '.$fullContent);
  6672. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6673. // 处理完整内容并返回最终结果
  6674. $script_arr = [];
  6675. if ($fullContent) {
  6676. $script_arr = handleScriptContentForAce($fullContent);
  6677. dLog('deepseek')->info('解析内容', $script_arr);
  6678. logDB('deepseek', 'info', '解析内容', $script_arr);
  6679. }
  6680. if (empty($script_arr['roles'])) {
  6681. // 未生成剧本相关内容,保存对话记录并返回提示
  6682. dLog('deepseek')->info('未生成剧本相关的内容');
  6683. try {
  6684. DB::beginTransaction();
  6685. $now = date('Y-m-d H:i:s');
  6686. // 保存对话记录
  6687. $records = [
  6688. [
  6689. 'uid' => $uid,
  6690. 'anime_id' => $anime_id,
  6691. 'sequence' => 0,
  6692. 'role' => 'user',
  6693. 'content' => $prompt,
  6694. 'created_at' => $now,
  6695. 'updated_at' => $now
  6696. ],
  6697. [
  6698. 'uid' => $uid,
  6699. 'anime_id' => $anime_id,
  6700. 'sequence' => 0,
  6701. 'role' => 'assistant',
  6702. // 'content' => $fullContent,
  6703. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  6704. 'created_at' => $now,
  6705. 'updated_at' => $now
  6706. ]
  6707. ];
  6708. DB::table('mp_anime_records')->insert($records);
  6709. DB::commit();
  6710. } catch (\Exception $e) {
  6711. DB::rollBack();
  6712. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6713. }
  6714. yield [
  6715. 'type' => 'done',
  6716. 'script' => [],
  6717. 'episode' => [],
  6718. 'answer' => $fullContent,
  6719. 'reasoning' => $fullReasoningContent,
  6720. 'usage' => $usage,
  6721. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6722. ];
  6723. return;
  6724. }
  6725. // 如果需要生成原文内容,从script_arr中提取
  6726. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6727. $content = $script_arr['content'];
  6728. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  6729. if (!$content) {
  6730. yield [
  6731. 'type' => 'done',
  6732. 'script' => [],
  6733. 'episode' => [],
  6734. 'answer' => $fullContent,
  6735. 'reasoning' => $fullReasoningContent,
  6736. 'usage' => $usage,
  6737. 'error' => '未生成剧本内容,请调整提示词再试'
  6738. ];
  6739. return;
  6740. }
  6741. }
  6742. // 替换美术风格
  6743. if ($mappedArtStyle !== '') {
  6744. $script_arr['art_style'] = $mappedArtStyle;
  6745. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6746. }
  6747. // 新建动漫
  6748. if ($user_anime_name == '新剧本策划') {
  6749. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6750. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6751. // if (!$anime_name) {
  6752. // // 未识别到剧本名,保存对话记录并返回提示
  6753. // dLog('deepseek')->info('未能识别到剧本名称');
  6754. // try {
  6755. // DB::beginTransaction();
  6756. // $now = date('Y-m-d H:i:s');
  6757. // // 保存对话记录
  6758. // $records = [
  6759. // [
  6760. // 'uid' => $uid,
  6761. // 'anime_id' => $anime_id,
  6762. // 'sequence' => 0,
  6763. // 'role' => 'user',
  6764. // 'content' => $prompt,
  6765. // 'created_at' => $now,
  6766. // 'updated_at' => $now
  6767. // ],
  6768. // [
  6769. // 'uid' => $uid,
  6770. // 'anime_id' => $anime_id,
  6771. // 'sequence' => 0,
  6772. // 'role' => 'assistant',
  6773. // 'content' => '未能生成剧本名称,请重试',
  6774. // 'created_at' => $now,
  6775. // 'updated_at' => $now
  6776. // ]
  6777. // ];
  6778. // DB::table('mp_anime_records')->insert($records);
  6779. // DB::commit();
  6780. // } catch (\Exception $e) {
  6781. // DB::rollBack();
  6782. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6783. // }
  6784. // yield [
  6785. // 'type' => 'done',
  6786. // 'script' => [],
  6787. // 'episode' => [],
  6788. // 'answer' => $fullContent,
  6789. // 'reasoning' => $fullReasoningContent,
  6790. // 'usage' => $usage,
  6791. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  6792. // ];
  6793. // return;
  6794. // }
  6795. // 确认对话名称唯一性
  6796. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6797. $anime_name = $anime_name . '_' . date('YmdHis');
  6798. }
  6799. }else {
  6800. $anime_name = $user_anime_name;
  6801. }
  6802. $table_data = [
  6803. 'user_id' => $uid,
  6804. 'anime_name' => $anime_name,
  6805. 'model' => $model,
  6806. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6807. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6808. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6809. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6810. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6811. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6812. 'art_style_type' => $input_art_style,
  6813. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6814. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6815. 'status' => '解析完成',
  6816. 'content' => $content,
  6817. 'is_multi' => $is_multi,
  6818. 'ace_mode' => $ace_mode,
  6819. 'generate_status' => '待执行',
  6820. 'updated_at' => date('Y-m-d H:i:s')
  6821. ];
  6822. if ($table_data['content']) {
  6823. $chapters = splitContent($table_data['content']);
  6824. $chapter_count = count($chapters);
  6825. if ($chapter_count > 0) {
  6826. $table_data['start_episode_sequence'] = 1;
  6827. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6828. }
  6829. }
  6830. if ($extra_products) {
  6831. $table_data['extra_products'] = json_encode($extra_products, 256);
  6832. }
  6833. // 如果有剧本ID则进行绑定
  6834. if ($script_id) {
  6835. $table_data['script_id'] = $script_id;
  6836. }
  6837. $single_episode = [];
  6838. try {
  6839. DB::beginTransaction();
  6840. $now = date('Y-m-d H:i:s');
  6841. // 更新动漫大纲
  6842. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6843. if (!$boolen) {
  6844. dLog('deepseek')->info('动漫保存失败', $table_data);
  6845. Utils::throwError('20003:动漫保存失败');
  6846. }
  6847. // 保存对话记录
  6848. $records = [
  6849. [
  6850. 'uid' => $uid,
  6851. 'anime_id' => $anime_id,
  6852. 'sequence' => 0,
  6853. 'role' => 'user',
  6854. 'content' => $prompt,
  6855. 'created_at' => date('Y-m-d H:i:s'),
  6856. 'updated_at' => date('Y-m-d H:i:s')
  6857. ],
  6858. [
  6859. 'uid' => $uid,
  6860. 'anime_id' => $anime_id,
  6861. 'sequence' => 0,
  6862. 'role' => 'assistant',
  6863. 'content' => $fullContent,
  6864. 'created_at' => date('Y-m-d H:i:s'),
  6865. 'updated_at' => date('Y-m-d H:i:s')
  6866. ]
  6867. ];
  6868. // 保存对话记录
  6869. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6870. if (!$boolen3) {
  6871. Utils::throwError('20003:对话记录保存失败');
  6872. }
  6873. if ($is_single) {
  6874. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6875. if (empty($episode_arr['acts'])) {
  6876. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6877. }
  6878. $saveResult = $this->saveEpisodeVersionData(
  6879. $anime_id,
  6880. 1,
  6881. $episode_arr,
  6882. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6883. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6884. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6885. null,
  6886. null,
  6887. false,
  6888. $content,
  6889. $now,
  6890. $ref_products
  6891. );
  6892. $single_episode = $saveResult['episode'];
  6893. $episode_id = $saveResult['episode_id'];
  6894. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6895. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6896. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6897. 'props' => json_encode($saveResult['merged_props'], 256),
  6898. 'updated_at' => $now
  6899. ]);
  6900. if ($boolen5 === false) {
  6901. Utils::throwError('20003:单剧集主表资源同步失败');
  6902. }
  6903. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6904. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6905. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6906. $episode_record_content = '确认分镜大纲';
  6907. if ($content !== '') {
  6908. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6909. }
  6910. $episode_records = [
  6911. [
  6912. 'uid' => $uid,
  6913. 'anime_id' => $anime_id,
  6914. 'role' => 'user',
  6915. 'content' => $episode_record_content,
  6916. 'sequence' => 1,
  6917. 'episode_id' => $episode_id,
  6918. 'created_at' => $now,
  6919. 'updated_at' => $now
  6920. ],
  6921. [
  6922. 'uid' => $uid,
  6923. 'anime_id' => $anime_id,
  6924. 'role' => 'assistant',
  6925. 'content' => $fullContent,
  6926. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6927. 'sequence' => 1,
  6928. 'episode_id' => $episode_id,
  6929. 'created_at' => $now,
  6930. 'updated_at' => $now
  6931. ]
  6932. ];
  6933. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6934. if (!$boolen4) {
  6935. Utils::throwError('20003:单剧集分镜记录保存失败');
  6936. }
  6937. }
  6938. }catch (\Exception $e) {
  6939. DB::rollBack();
  6940. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6941. yield [
  6942. 'type' => 'done',
  6943. 'answer' => $fullContent,
  6944. 'reasoning' => $fullReasoningContent,
  6945. 'usage' => $usage,
  6946. 'error' => $e->getMessage(),
  6947. ];
  6948. return;
  6949. }
  6950. DB::commit();
  6951. dLog('deepseek')->info('保存完毕');
  6952. if ($is_single && !empty($single_episode)) {
  6953. // $this->batchSetGlobalRoleImg([
  6954. // 'anime_id' => $anime_id,
  6955. // ]);
  6956. // $this->batchSetGlobalSceneImg([
  6957. // 'anime_id' => $anime_id,
  6958. // ]);
  6959. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6960. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6961. }
  6962. $table_data['anime_id'] = $anime_id;
  6963. $table_data['roles'] = json_decode($table_data['roles'], true);
  6964. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6965. // $table_data['episodes'] = $script_arr['episodes'];
  6966. unset($table_data['created_at']);
  6967. unset($table_data['updated_at']);
  6968. unset($table_data['status']);
  6969. dLog('deepseek')->info('开始返回');
  6970. yield [
  6971. 'type' => 'done',
  6972. 'script' => $table_data,
  6973. 'episode' => $single_episode,
  6974. 'answer' => $fullContent,
  6975. 'reasoning' => $fullReasoningContent,
  6976. 'usage' => $usage
  6977. ];
  6978. }
  6979. public function reGenerateAnimeForAce($data) {
  6980. $uid = Site::getUid();
  6981. $file = getProp($data, 'file');
  6982. $content = getProp($data, 'content', '');
  6983. $bid = getProp($data, 'bid', 0);
  6984. $script_id = getProp($data, 'script_id', 0);
  6985. $anime_id = getProp($data, 'anime_id');
  6986. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6987. if (!$anime) {
  6988. Utils::throwError('20003:该对话不存在');
  6989. }
  6990. $is_multi = getProp($anime, 'is_multi', 1);
  6991. $is_single = (int)$is_multi !== 1;
  6992. $extra_products = getProp($data, 'products', []);
  6993. if (!$extra_products) {
  6994. $extra_products = getProp($anime, 'extra_products');
  6995. if ($extra_products) {
  6996. $extra_products = json_decode($extra_products, true);
  6997. }else {
  6998. $extra_products = [];
  6999. }
  7000. }else {
  7001. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7002. }
  7003. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7004. $anime_script_id = getProp($anime, 'script_id');
  7005. if ($anime_script_id && $is_single) {
  7006. $cpid = Site::getCpid();
  7007. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7008. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7009. ->where('mapping.script_id', $anime_script_id)
  7010. ->where('product.cpid', $cpid)
  7011. ->where('product.is_deleted', 0);
  7012. $mappings = $script_products_mappings->select(
  7013. 'mapping.product_id',
  7014. 'mapping.episode_number',
  7015. 'product.product_name',
  7016. 'product.type',
  7017. 'product.product',
  7018. 'product.pic_prompt',
  7019. 'product.url',
  7020. 'product.pic_task_id',
  7021. 'product.pic_task_status',
  7022. 'product.three_view_image_url'
  7023. )
  7024. ->get();
  7025. // 按 product_id 分组,合并 episode_number
  7026. $productMap = [];
  7027. foreach ($mappings as $item) {
  7028. $product_id = $item->product_id;
  7029. $product_name = $item->product_name;
  7030. // 处理product_name两边的符号
  7031. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7032. if (!isset($productMap[$product_id])) {
  7033. $productMap[$product_id] = [
  7034. 'product_id' => $product_id,
  7035. 'product_name' => $product_name,
  7036. 'type' => (int)$item->type,
  7037. 'product' => (int)$item->product,
  7038. 'pic_prompt' => $item->pic_prompt,
  7039. 'url' => $item->url,
  7040. 'pic_task_id' => $item->pic_task_id,
  7041. 'pic_task_status' => $item->pic_task_status,
  7042. 'episode_numbers' => [],
  7043. ];
  7044. }
  7045. // 添加 episode_number(去重)
  7046. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7047. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7048. }
  7049. }
  7050. // 将查询到的剧本资产合并到extra_products中
  7051. // 先构建extra_products的索引(以product_id为key,用于去重)
  7052. $extraProductsMap = [];
  7053. foreach ($extra_products as $item) {
  7054. $key = getProp($item, 'product_id');
  7055. if ($key) {
  7056. $extraProductsMap[$key] = $item;
  7057. }
  7058. }
  7059. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7060. foreach ($productMap as $product) {
  7061. $product_id = $product['product_id'];
  7062. // 如果不存在则添加(不带episode_number信息)
  7063. if (!isset($extraProductsMap[$product_id])) {
  7064. $extraProductsMap[$product_id] = [
  7065. 'product_id' => $product['product_id'],
  7066. 'product_name' => $product['product_name'],
  7067. 'type' => $product['type'],
  7068. 'product' => $product['product'],
  7069. 'pic_prompt' => $product['pic_prompt'],
  7070. 'url' => $product['url'],
  7071. 'pic_task_id' => $product['pic_task_id'],
  7072. 'pic_task_status' => $product['pic_task_status'],
  7073. ];
  7074. }
  7075. }
  7076. // 重新赋值给extra_products
  7077. $extra_products = array_values($extraProductsMap);
  7078. }
  7079. $user_anime_name = getProp($anime, 'anime_name');
  7080. $prompt = getProp($data, 'prompt');
  7081. // 处理提示词
  7082. if ($prompt && $extra_products) {
  7083. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7084. foreach($extra_products as $item) {
  7085. $product_name = getProp($item, 'product_name');
  7086. if ($product_name) {
  7087. // 替换 {product_name} 为 product_name
  7088. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7089. }
  7090. }
  7091. }
  7092. // 处理文本模型
  7093. $model = getProp($data, 'model');
  7094. if (!$model) {
  7095. // 用户没有输入,从anime表获取
  7096. $model = getProp($anime, 'model');
  7097. if (!$model) {
  7098. // anime表也没有,使用默认值
  7099. $model = 'deepseek-v4-pro';
  7100. }
  7101. }
  7102. // 验证模型是否在可用模型表中
  7103. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7104. $model = 'deepseek-v4-pro';
  7105. }
  7106. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  7107. if ($is_single) {
  7108. $episode_exists = DB::table('mp_anime_episodes')
  7109. ->where('anime_id', $anime_id)
  7110. ->where('sequence', 1)
  7111. ->exists();
  7112. if ($episode_exists) {
  7113. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  7114. }
  7115. }
  7116. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7117. if ($prompt) {
  7118. $question .= "本次修改要求如下:\n{$prompt}";
  7119. }
  7120. // 提取文件内容
  7121. if ($file) {
  7122. $content = $this->extractFileContent($file);
  7123. if (!$content) {
  7124. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7125. }
  7126. } elseif ($script_id) {
  7127. $content = $this->getContentByScriptId($script_id);
  7128. if (!$content) {
  7129. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7130. }
  7131. } elseif ($bid) {
  7132. $content = $this->getContentByBid($bid);
  7133. if (!$content) {
  7134. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7135. }
  7136. } elseif ($content) {
  7137. $content = filterContent($content);
  7138. }else {
  7139. $content = filterContent(getProp($anime, 'content'));
  7140. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7141. $need_generate_content = true;
  7142. }
  7143. }
  7144. // 判断是否需要生成原文内容
  7145. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7146. // 如果需要生成原文内容,添加额外的要求
  7147. $content_generation_requirement = $need_generate_content
  7148. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7149. : "";
  7150. // 美术风格
  7151. $input_art_style = getProp($data, 'art_style');
  7152. if (!$input_art_style) {
  7153. $mappedArtStyle = getProp($anime, 'art_style');
  7154. }else {
  7155. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7156. }
  7157. if (!$mappedArtStyle) {
  7158. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7159. }else {
  7160. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7161. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7162. }else {
  7163. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7164. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7165. }
  7166. }
  7167. // 构建主体、场景和道具提示词
  7168. $extra_role_prompt = "\n";
  7169. $extra_scene_prompt = "\n";
  7170. $extra_prop_prompt = "\n";
  7171. $ref_products = []; // 参考资产
  7172. if ($extra_products) {
  7173. foreach($extra_products as $item) {
  7174. $product = getProp($item, 'product');
  7175. $product_name = getProp($item, 'product_name');
  7176. if ($product_name == '旁白') continue;
  7177. $ref_products[$product_name] = $item;
  7178. $pic_prompt = getProp($item, 'pic_prompt');
  7179. if ((int)$product === 1) {
  7180. // 拼接角色信息
  7181. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7182. } elseif ((int)$product === 2) {
  7183. // 拼接场景信息
  7184. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7185. } elseif ((int)$product === 3) {
  7186. // 拼接道具信息
  7187. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7188. }
  7189. }
  7190. // 优化提示词,融入剧本
  7191. if (!empty(trim($extra_role_prompt))) {
  7192. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7193. }
  7194. if (!empty(trim($extra_scene_prompt))) {
  7195. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7196. }
  7197. if (!empty(trim($extra_prop_prompt))) {
  7198. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7199. }
  7200. }
  7201. if ($anime_script_id && $is_single) {
  7202. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7203. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7204. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7205. }else {
  7206. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7207. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7208. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7209. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7210. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7211. {$extra_role_prompt}";
  7212. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7213. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7214. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7215. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7216. {$extra_scene_prompt}";
  7217. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7218. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7219. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7220. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7221. {$extra_prop_prompt}";
  7222. }
  7223. $system_message = ['role'=>'system', 'content'=>$is_single
  7224. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7225. 强制要求:
  7226. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7227. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7228. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7229. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7230. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7231. 普通要求:
  7232. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7233. $role_demo
  7234. $scene_demo
  7235. $prop_demo
  7236. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7237. 5.1片段分割逻辑(优先级从高到低):
  7238. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7239. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7240. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7241. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7242. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7243. - 片段数量格式为: 片段数量:8
  7244. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7245. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7246. 5.3分镜结构:每个分镜包含以下字段:
  7247. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7248. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7249. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7250. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7251. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7252. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7253. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7254. - 运镜:场景+画面描述+运镜
  7255. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7256. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7257. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7258. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7259. 6.{$mappedArtStyle_prompt}\n\n
  7260. 示例如下:\n
  7261. ###剧本名:西昆仑
  7262. ###故事梗概
  7263. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7264. ###剧本亮点
  7265. 亮点1:绝境奇药,生死一线
  7266. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7267. 亮点2:结拜兄妹,化解尴尬
  7268. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7269. 亮点3:纤发夺命,情愫暗涌
  7270. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7271. ###人物关系
  7272. 阿雪与梁萧之间存在兄妹之情。
  7273. ###核心矛盾
  7274. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7275. ###主体列表
  7276. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7277. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7278. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7279. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7280. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7281. 全景,正面拍摄,青年女性,亚洲人。
  7282. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7283. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7284. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7285. ###美术风格
  7286. 基础画风风格词:厚涂古风
  7287. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7288. ###场景列表
  7289. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7290. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7291. 无人物。}
  7292. ###分段剧本
  7293. 片段数量:8
  7294. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7295. ##片段1
  7296. 时长:12s
  7297. 分镜1
  7298. 出场角色:刀疤脸
  7299. 场景:边境小镇街道
  7300. 出场道具:酒杯-高脚杯
  7301. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7302. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7303. 配音台词:
  7304. 背景音效:
  7305. 分镜2
  7306. 出场角色:刀疤脸
  7307. 场景:悦来酒馆
  7308. 出场道具:酒杯-高脚杯
  7309. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7310. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7311. 配音台词:
  7312. 背景音效:
  7313. 分镜3
  7314. 出场角色:刀疤脸
  7315. 场景:悦来酒馆
  7316. 出场道具:酒杯-高脚杯
  7317. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7318. 运镜:从中景推向令牌特写。
  7319. 配音台词:
  7320. 背景音效:
  7321. 分镜4
  7322. 出场角色:刀疤脸
  7323. 场景:悦来酒馆
  7324. 出场道具:酒杯-高脚杯
  7325. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7326. 运镜:极速推向酒水溅起的瞬间。
  7327. 配音台词:
  7328. 背景音效:
  7329. 分镜5
  7330. 出场角色:刀疤脸
  7331. 场景:悦来酒馆
  7332. 出场道具:酒杯-高脚杯
  7333. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7334. 运镜:固定机位,利用倾斜构图制造压迫感。
  7335. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7336. 背景音效:
  7337. \n\n"
  7338. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7339. 强制要求:\n
  7340. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7341. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7342. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7343. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7344. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7345. 普通要求:\n
  7346. 1.剧本名(必须生成)必须与文档内容高度相关
  7347. $role_demo
  7348. $scene_demo
  7349. $prop_demo
  7350. 5.{$mappedArtStyle_prompt}\n\n
  7351. 示例如下:\n
  7352. ###剧本名:西昆仑
  7353. ###故事梗概
  7354. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7355. ###剧本亮点
  7356. 亮点1:绝境奇药,生死一线
  7357. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7358. 亮点2:结拜兄妹,化解尴尬
  7359. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7360. 亮点3:纤发夺命,情愫暗涌
  7361. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7362. ###人物关系
  7363. 阿雪与梁萧之间存在兄妹之情。
  7364. ###核心矛盾
  7365. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7366. ###主体列表
  7367. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7368. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7369. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7370. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7371. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7372. 全景,正面拍摄,青年女性,亚洲人。
  7373. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7374. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7375. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7376. ###美术风格
  7377. 基础画风风格词:厚涂古风
  7378. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7379. ###场景列表
  7380. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7381. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7382. 无人物。}
  7383. ###道具列表
  7384. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  7385. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  7386. $episode_count = $this->extractEpisodeNumber($prompt);
  7387. if ((int)getProp($anime, 'is_multi') !== 1) {
  7388. yield [
  7389. 'type' => 'done',
  7390. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  7391. 'reasoning' => '',
  7392. 'usage' => []
  7393. ];
  7394. return;
  7395. }
  7396. if ($episode_count) {
  7397. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  7398. $system_message = [
  7399. 'role' => 'system',
  7400. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7401. 强制要求:\n
  7402. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7403. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7404. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7405. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7406. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7407. 普通要求:\n
  7408. 1.<故事梗概>控制在200-300字左右
  7409. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7410. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7411. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7412. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7413. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7414. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7415. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7416. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7417. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7418. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  7419. 示例如下:\n
  7420. ###剧本名:西昆仑
  7421. ###故事梗概
  7422. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7423. ###剧本亮点
  7424. 亮点1:绝境奇药,生死一线
  7425. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7426. 亮点2:结拜兄妹,化解尴尬
  7427. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7428. 亮点3:纤发夺命,情愫暗涌
  7429. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7430. ###人物关系
  7431. 阿雪与梁萧之间存在兄妹之情。
  7432. ###核心矛盾
  7433. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7434. ###主体列表
  7435. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7436. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7437. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7438. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7439. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7440. 全景,正面拍摄,青年女性,亚洲人。
  7441. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7442. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7443. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7444. ###美术风格
  7445. 基础画风风格词:厚涂古风
  7446. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7447. ###场景列表
  7448. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7449. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7450. 无人物。}
  7451. ###分集详细内容
  7452. ##第1章 重生
  7453. 我重生了。
  7454. 源于一个男人偏执的暗恋。
  7455. ##第2章 相救
  7456. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  7457. 我眼睛扫向站在锅炉后的卞大伟。"
  7458. ];
  7459. // 构建消息
  7460. $messages = [
  7461. $system_message,
  7462. [
  7463. 'role' => 'user',
  7464. 'content' => "以下是文档内容:
  7465. {$content}
  7466. 用户问题:
  7467. {$question}"
  7468. ]
  7469. ];
  7470. }else {
  7471. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  7472. // 构建消息
  7473. $messages = [
  7474. $system_message,
  7475. [
  7476. 'role' => 'user',
  7477. 'content' => "以下是文档内容:
  7478. {$content}
  7479. 用户问题:
  7480. {$question}"
  7481. ]
  7482. ];
  7483. }else {
  7484. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  7485. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  7486. return (array)$value;
  7487. })->toArray();
  7488. array_unshift($messages, $system_message);
  7489. $messages[] = [
  7490. 'role' => 'user',
  7491. 'content' => $prompt
  7492. ];
  7493. }
  7494. }
  7495. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7496. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7497. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7498. if ($model === 'deepseek-chat') {
  7499. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7500. $model = 'deepseek-v4-flash';
  7501. $thinkingMode = 'disabled';
  7502. } elseif ($model === 'deepseek-reasoner') {
  7503. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7504. $model = 'deepseek-v4-flash';
  7505. $thinkingMode = 'enabled';
  7506. }
  7507. $post_data = [
  7508. 'model' => $model,
  7509. 'messages' => $messages,
  7510. // 'max_tokens' => 8192,
  7511. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7512. 'frequency_penalty' => 0,
  7513. 'presence_penalty' => 0,
  7514. 'response_format' => ['type' => 'text'],
  7515. 'thinking' => ['type' => $thinkingMode],
  7516. 'stream' => true // 启用流式输出
  7517. ];
  7518. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7519. // 根据模型类型选择调用方法
  7520. $fullContent = '';
  7521. $fullReasoningContent = '';
  7522. $usage = [];
  7523. // dd($post_data);
  7524. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  7525. try {
  7526. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7527. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7528. } else if (in_array($model, $this->gpt_text_models)) {
  7529. // GPT-5.4 模型使用 TokenRouter API
  7530. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7531. } else if (in_array($model, $this->gemini_text_models)) {
  7532. // Gemini 模型使用 Gemini API
  7533. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  7534. } else {
  7535. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7536. }
  7537. // 验证返回值类型
  7538. if (!is_iterable($streamGenerator)) {
  7539. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7540. dLog('deepseek')->error('方法名流式生成器无效', [
  7541. 'generator_type' => $errorType,
  7542. 'model' => $model,
  7543. // 添加其他上下文信息
  7544. ]);
  7545. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  7546. 'type' => $errorType,
  7547. 'model' => $model
  7548. ]);
  7549. yield [
  7550. 'type' => 'error',
  7551. // 根据方法返回相应的空数据结构
  7552. 'answer' => '',
  7553. 'reasoning' => '',
  7554. 'usage' => [],
  7555. 'error' => '接口返回数据异常,请重新请求'
  7556. ];
  7557. return;
  7558. }
  7559. // 处理流式输出
  7560. foreach ($streamGenerator as $chunk) {
  7561. if (isset($chunk['type'])) {
  7562. if ($chunk['type'] === 'done') {
  7563. $fullContent = $chunk['full_content'];
  7564. $fullReasoningContent = $chunk['full_reasoning'];
  7565. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7566. } else {
  7567. yield $chunk;
  7568. }
  7569. }
  7570. }
  7571. } catch (\Exception $e) {
  7572. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  7573. 'model' => $model,
  7574. 'trace' => $e->getTraceAsString()
  7575. ]);
  7576. logDB('deepseek', 'error', '方法名流式处理失败', [
  7577. 'error' => $e->getMessage(),
  7578. 'model' => $model
  7579. ]);
  7580. yield [
  7581. 'type' => 'error',
  7582. // 根据方法返回相应的空数据结构
  7583. 'answer' => '',
  7584. 'reasoning' => '',
  7585. 'usage' => [],
  7586. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7587. ];
  7588. return;
  7589. }
  7590. dLog('deepseek')->info('完整内容: '.$fullContent);
  7591. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7592. // 处理完整内容并返回最终结果
  7593. $script_arr = [];
  7594. if ($fullContent) {
  7595. $script_arr = handleScriptContentForAce($fullContent);
  7596. dLog('deepseek')->info('解析内容', $script_arr);
  7597. logDB('deepseek', 'info', '解析内容', $script_arr);
  7598. }
  7599. if (empty($script_arr['roles'])) {
  7600. // 未生成剧本相关内容,保存对话记录并返回提示
  7601. dLog('deepseek')->info('未生成剧本相关的内容');
  7602. try {
  7603. $now = date('Y-m-d H:i:s');
  7604. // 保存对话记录
  7605. $records = [
  7606. [
  7607. 'uid' => $uid,
  7608. 'anime_id' => $anime_id,
  7609. 'sequence' => 0,
  7610. 'role' => 'user',
  7611. 'content' => $prompt,
  7612. 'created_at' => $now,
  7613. 'updated_at' => $now
  7614. ],
  7615. [
  7616. 'uid' => $uid,
  7617. 'anime_id' => $anime_id,
  7618. 'sequence' => 0,
  7619. 'role' => 'assistant',
  7620. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  7621. 'created_at' => $now,
  7622. 'updated_at' => $now
  7623. ]
  7624. ];
  7625. DB::table('mp_anime_records')->insert($records);
  7626. } catch (\Exception $e) {
  7627. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7628. }
  7629. yield [
  7630. 'type' => 'done',
  7631. 'script' => [],
  7632. 'episode' => [],
  7633. 'answer' => $fullContent,
  7634. 'reasoning' => $fullReasoningContent,
  7635. 'usage' => $usage,
  7636. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  7637. ];
  7638. return;
  7639. }
  7640. // 替换美术风格
  7641. if ($mappedArtStyle !== '') {
  7642. $script_arr['art_style'] = $mappedArtStyle;
  7643. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  7644. }
  7645. if ($user_anime_name != '新剧本策划') {
  7646. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  7647. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  7648. // 确认对话名称唯一性
  7649. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  7650. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  7651. }
  7652. }else {
  7653. $anime_name = $user_anime_name;
  7654. }
  7655. $table_data = [
  7656. 'user_id' => $uid,
  7657. 'model' => $model,
  7658. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  7659. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  7660. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  7661. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  7662. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  7663. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  7664. 'art_style_type' => $input_art_style,
  7665. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  7666. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  7667. 'status' => '解析完成',
  7668. 'generate_status' => '待执行',
  7669. 'updated_at' => date('Y-m-d H:i:s')
  7670. ];
  7671. if ($anime_name) $table_data['anime_name'] = $anime_name;
  7672. // 如果是修改集数,则将content内容更新(会改变原文)
  7673. if (isset($episode_count) && $episode_count > 0) {
  7674. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  7675. $table_data['start_episode_sequence'] = 1;
  7676. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  7677. }else {
  7678. // 如果需要生成原文内容,从script_arr中提取
  7679. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  7680. $table_data['content'] = $script_arr['content'];
  7681. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  7682. if (!$table_data['content']) {
  7683. yield [
  7684. 'type' => 'done',
  7685. 'script' => [],
  7686. 'episode' => [],
  7687. 'answer' => $fullContent,
  7688. 'reasoning' => $fullReasoningContent,
  7689. 'usage' => $usage,
  7690. 'error' => '未生成剧本内容,请调整提示词再试'
  7691. ];
  7692. return;
  7693. }
  7694. }
  7695. if (isset($table_data['content']) && $table_data['content']) {
  7696. $chapters = splitContent($table_data['content']);
  7697. $chapter_count = count($chapters);
  7698. if ($chapter_count > 0) {
  7699. $table_data['start_episode_sequence'] = 1;
  7700. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  7701. }
  7702. }
  7703. }
  7704. if ($extra_products) {
  7705. $table_data['extra_products'] = json_encode($extra_products, 256);
  7706. }
  7707. $single_episode = [];
  7708. try {
  7709. DB::beginTransaction();
  7710. $now = date('Y-m-d H:i:s');
  7711. // 更新动漫大纲
  7712. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7713. if (!$boolen) {
  7714. dLog('deepseek')->info('对话修改失败', $table_data);
  7715. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  7716. Utils::throwError('20003:对话修改失败');
  7717. }
  7718. // 保存对话记录
  7719. $records = [
  7720. [
  7721. 'uid' => $uid,
  7722. 'anime_id' => $anime_id,
  7723. 'sequence' => 0,
  7724. 'role' => 'user',
  7725. 'content' => $prompt,
  7726. 'created_at' => $now,
  7727. 'updated_at' => $now
  7728. ],
  7729. [
  7730. 'uid' => $uid,
  7731. 'anime_id' => $anime_id,
  7732. 'sequence' => 0,
  7733. 'role' => 'assistant',
  7734. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7735. 'content' => $fullContent,
  7736. 'created_at' => $now,
  7737. 'updated_at' => $now
  7738. ]
  7739. ];
  7740. // 保存对话记录
  7741. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7742. if (!$boolen3) {
  7743. Utils::throwError('20003:对话记录保存失败');
  7744. }
  7745. // 单剧集模式:生成并保存剧集信息
  7746. if ($is_single) {
  7747. $anime_name = getProp($anime, 'anime_name', '未命名');
  7748. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7749. if (empty($episode_arr['acts'])) {
  7750. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7751. }
  7752. $saveResult = $this->saveEpisodeVersionData(
  7753. $anime_id,
  7754. 1,
  7755. $episode_arr,
  7756. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7757. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7758. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7759. null,
  7760. null,
  7761. false,
  7762. $content,
  7763. $now,
  7764. $ref_products
  7765. );
  7766. $single_episode = $saveResult['episode'];
  7767. $episode_id = $saveResult['episode_id'];
  7768. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7769. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7770. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7771. 'props' => json_encode($saveResult['merged_props'], 256),
  7772. 'updated_at' => $now
  7773. ]);
  7774. if ($boolen5 === false) {
  7775. Utils::throwError('20003:单剧集主表资源同步失败');
  7776. }
  7777. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7778. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7779. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7780. $episode_record_content = '确认分镜大纲';
  7781. if ($content !== '') {
  7782. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7783. }
  7784. $episode_records = [
  7785. [
  7786. 'uid' => $uid,
  7787. 'anime_id' => $anime_id,
  7788. 'role' => 'user',
  7789. 'content' => $episode_record_content,
  7790. 'sequence' => 1,
  7791. 'episode_id' => $episode_id,
  7792. 'created_at' => $now,
  7793. 'updated_at' => $now
  7794. ],
  7795. [
  7796. 'uid' => $uid,
  7797. 'anime_id' => $anime_id,
  7798. 'role' => 'assistant',
  7799. 'content' => $fullContent,
  7800. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7801. 'sequence' => 1,
  7802. 'episode_id' => $episode_id,
  7803. 'created_at' => $now,
  7804. 'updated_at' => $now
  7805. ]
  7806. ];
  7807. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7808. if (!$boolen4) {
  7809. Utils::throwError('20003:单剧集分镜记录保存失败');
  7810. }
  7811. }
  7812. }catch (\Exception $e) {
  7813. DB::rollBack();
  7814. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  7815. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  7816. yield [
  7817. 'type' => 'done',
  7818. 'answer' => $fullContent,
  7819. 'reasoning' => $fullReasoningContent,
  7820. 'usage' => $usage,
  7821. 'error' => $e->getMessage(),
  7822. ];
  7823. return;
  7824. }
  7825. DB::commit();
  7826. dLog('deepseek')->info('保存完毕');
  7827. if ($is_single && !empty($single_episode)) {
  7828. // $this->batchSetGlobalRoleImg([
  7829. // 'anime_id' => $anime_id,
  7830. // ]);
  7831. // $this->batchSetGlobalSceneImg([
  7832. // 'anime_id' => $anime_id,
  7833. // ]);
  7834. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7835. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7836. }
  7837. $table_data['anime_id'] = $anime_id;
  7838. $table_data['roles'] = json_decode($table_data['roles'], true);
  7839. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7840. $table_data['props'] = json_decode($table_data['props'], true);
  7841. unset($table_data['updated_at']);
  7842. unset($table_data['status']);
  7843. yield [
  7844. 'type' => 'done',
  7845. 'script' => $table_data,
  7846. 'episode' => $single_episode,
  7847. 'answer' => $fullContent,
  7848. 'reasoning' => $fullReasoningContent,
  7849. 'usage' => $usage
  7850. ];
  7851. }
  7852. public function chatForAce($data) {
  7853. $uid = Site::getUid();
  7854. $anime_id = getProp($data, 'anime_id');
  7855. $file = getProp($data, 'file');
  7856. $content = getProp($data, 'content', '');
  7857. $bid = getProp($data, 'bid', 0);
  7858. $script_id = getProp($data, 'script_id', 0);
  7859. $episode_number = getProp($data, 'episode_number', 1);
  7860. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7861. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7862. if (!$anime) Utils::throwError('20003:该对话不存在!');
  7863. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  7864. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  7865. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  7866. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  7867. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  7868. $roles = is_array($roles) ? $roles : [];
  7869. $scenes = is_array($scenes) ? $scenes : [];
  7870. $extra_products = getProp($data, 'products', []);
  7871. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7872. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7873. $anime_script_id = getProp($anime, 'script_id');
  7874. if ($anime_script_id) {
  7875. $cpid = Site::getCpid();
  7876. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7877. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7878. ->where('mapping.script_id', $anime_script_id)
  7879. ->where('product.cpid', $cpid)
  7880. ->where('product.is_deleted', 0);
  7881. // 如果提供了 episode_number,则过滤指定集数
  7882. if ($episode_number !== null && $episode_number !== '') {
  7883. $script_products_mappings->where('mapping.episode_number', $episode_number);
  7884. }
  7885. $mappings = $script_products_mappings->select(
  7886. 'mapping.product_id',
  7887. 'mapping.episode_number',
  7888. 'product.product_name',
  7889. 'product.type',
  7890. 'product.product',
  7891. 'product.pic_prompt',
  7892. 'product.url',
  7893. 'product.pic_task_id',
  7894. 'product.pic_task_status',
  7895. 'product.three_view_image_url'
  7896. )
  7897. ->get();
  7898. // 按 product_id 分组,合并 episode_number
  7899. $productMap = [];
  7900. foreach ($mappings as $item) {
  7901. $product_id = $item->product_id;
  7902. $product_name = $item->product_name;
  7903. // 处理product_name两边的符号
  7904. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7905. if (!isset($productMap[$product_id])) {
  7906. $productMap[$product_id] = [
  7907. 'product_id' => $product_id,
  7908. 'product_name' => $product_name,
  7909. 'type' => (int)$item->type,
  7910. 'product' => (int)$item->product,
  7911. 'pic_prompt' => $item->pic_prompt,
  7912. 'url' => $item->url,
  7913. 'pic_task_id' => $item->pic_task_id,
  7914. 'pic_task_status' => $item->pic_task_status,
  7915. 'episode_numbers' => [],
  7916. ];
  7917. }
  7918. // 添加 episode_number(去重)
  7919. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7920. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7921. }
  7922. }
  7923. // 将查询到的剧本资产合并到extra_products中
  7924. // 先构建extra_products的索引(以product_id+episode_number为key)
  7925. $extraProductsMap = [];
  7926. foreach ($extra_products as $item) {
  7927. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  7928. $extraProductsMap[$key] = $item;
  7929. }
  7930. // 合并剧本资产(去重:product_id+episode_number)
  7931. foreach ($productMap as $product) {
  7932. foreach ($product['episode_numbers'] as $ep_num) {
  7933. $key = $product['product_id'] . '_' . $ep_num;
  7934. // 如果不存在则添加
  7935. if (!isset($extraProductsMap[$key])) {
  7936. $extraProductsMap[$key] = [
  7937. 'product_id' => $product['product_id'],
  7938. 'product_name' => $product['product_name'],
  7939. 'type' => $product['type'],
  7940. 'product' => $product['product'],
  7941. 'pic_prompt' => $product['pic_prompt'],
  7942. 'url' => $product['url'],
  7943. 'pic_task_id' => $product['pic_task_id'],
  7944. 'pic_task_status' => $product['pic_task_status'],
  7945. 'episode_number' => $ep_num,
  7946. ];
  7947. }
  7948. }
  7949. }
  7950. // 重新赋值给extra_products
  7951. $extra_products = array_values($extraProductsMap);
  7952. }
  7953. // 处理提示词
  7954. if ($prompt && $extra_products) {
  7955. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7956. foreach($extra_products as $item) {
  7957. $product_name = getProp($item, 'product_name');
  7958. if ($product_name) {
  7959. // 替换 {product_name} 为 product_name
  7960. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7961. }
  7962. }
  7963. }
  7964. // 获取最后一集序号
  7965. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  7966. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  7967. // 转换主体列表和场景列表的格式
  7968. // 获取参考主体或场景
  7969. if ((int)$episode_number === 1) {
  7970. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  7971. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  7972. }else {
  7973. $prev_episode_number = $episode_number - 1;
  7974. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  7975. }
  7976. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  7977. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  7978. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  7979. // 合并anime_products和extra_products(extra_products优先,去重)
  7980. $anime_products = getProp($anime, 'extra_products');
  7981. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  7982. $ref_products = [];
  7983. foreach($anime_products as $item) {
  7984. $product_name = getProp($item, 'product_name');
  7985. $ref_products[$product_name] = $item;
  7986. }
  7987. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  7988. $extra_roles = []; // 从extra_products中提取的角色
  7989. $extra_scenes = []; // 从extra_products中提取的场景
  7990. $extra_props = []; // 从extra_products中提取的道具
  7991. if ($extra_products && is_array($extra_products)) {
  7992. foreach($extra_products as $item) {
  7993. $product = (int)getProp($item, 'product');
  7994. $product_name = getProp($item, 'product_name');
  7995. if ($product_name == '旁白') continue;
  7996. $pic_prompt = getProp($item, 'pic_prompt');
  7997. $ref_products[$product_name] = $item;
  7998. if ($product === 1) {
  7999. // 角色
  8000. $extra_roles[$product_name] = [
  8001. 'role' => $product_name,
  8002. 'pic_prompt' => $pic_prompt,
  8003. 'url' => getProp($item, 'url', ''),
  8004. ];
  8005. } elseif ($product === 2) {
  8006. // 场景
  8007. $extra_scenes[$product_name] = [
  8008. 'scene' => $product_name,
  8009. 'pic_prompt' => $pic_prompt,
  8010. 'url' => getProp($item, 'url', ''),
  8011. ];
  8012. } elseif ($product === 3) {
  8013. // 道具
  8014. $extra_props[$product_name] = [
  8015. 'prop' => $product_name,
  8016. 'pic_prompt' => $pic_prompt,
  8017. 'url' => getProp($item, 'url', ''),
  8018. ];
  8019. }
  8020. }
  8021. }
  8022. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  8023. $merged_roles = [];
  8024. foreach($ref_roles as $role) {
  8025. $role_name = getProp($role, 'role');
  8026. if (!isset($extra_roles[$role_name])) {
  8027. $merged_roles[$role_name] = $role;
  8028. }
  8029. }
  8030. // 添加extra_roles
  8031. foreach($extra_roles as $role_name => $role) {
  8032. $merged_roles[$role_name] = $role;
  8033. }
  8034. $ref_roles = array_values($merged_roles);
  8035. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  8036. $merged_scenes = [];
  8037. foreach($ref_scenes as $scene) {
  8038. $scene_name = getProp($scene, 'scene');
  8039. if (!isset($extra_scenes[$scene_name])) {
  8040. $merged_scenes[$scene_name] = $scene;
  8041. }
  8042. }
  8043. // 添加extra_scenes
  8044. foreach($extra_scenes as $scene_name => $scene) {
  8045. $merged_scenes[$scene_name] = $scene;
  8046. }
  8047. $ref_scenes = array_values($merged_scenes);
  8048. // 合并ref_props和extra_props(extra_props优先,去重)
  8049. $merged_props = [];
  8050. foreach($ref_props as $prop) {
  8051. $prop_name = getProp($prop, 'prop');
  8052. if (!isset($extra_props[$prop_name])) {
  8053. $merged_props[$prop_name] = $prop;
  8054. }
  8055. }
  8056. // 添加extra_props
  8057. foreach($extra_props as $prop_name => $prop) {
  8058. $merged_props[$prop_name] = $prop;
  8059. }
  8060. $ref_props = array_values($merged_props);
  8061. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  8062. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  8063. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  8064. // 构建强制主体、场景和道具提示词
  8065. $forced_roles_prompt = "";
  8066. $forced_scenes_prompt = "";
  8067. $forced_props_prompt = "";
  8068. if (!empty($extra_roles)) {
  8069. $forced_roles_list = "";
  8070. foreach($extra_roles as $role_name => $role) {
  8071. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  8072. }
  8073. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  8074. }
  8075. if (!empty($extra_scenes)) {
  8076. $forced_scenes_list = "";
  8077. foreach($extra_scenes as $scene_name => $scene) {
  8078. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  8079. }
  8080. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  8081. }
  8082. if (!empty($extra_props)) {
  8083. $forced_props_list = "";
  8084. foreach($extra_props as $prop_name => $prop) {
  8085. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  8086. }
  8087. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  8088. }
  8089. if ($anime_script_id) {
  8090. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  8091. }else if ($roles_content) {
  8092. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  8093. 主体范围:\n {$roles_content}\n
  8094. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  8095. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8096. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8097. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8098. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8099. }else {
  8100. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8101. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8102. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8103. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8104. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8105. }
  8106. if ($anime_script_id) {
  8107. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  8108. }else if ($scenes_content) {
  8109. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8110. 场景范围:\n {$scenes_content}\n
  8111. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  8112. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  8113. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8114. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8115. }else {
  8116. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8117. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8118. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8119. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8120. }
  8121. if ($anime_script_id) {
  8122. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  8123. }else if ($props_content) {
  8124. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8125. 道具范围:\n {$props_content}\n
  8126. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  8127. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  8128. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8129. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8130. }else {
  8131. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8132. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  8133. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8134. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8135. }
  8136. // 提取文件内容
  8137. if ($file) {
  8138. $uploaded_content = $this->extractFileContent($file);
  8139. if (!$uploaded_content) {
  8140. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8141. }
  8142. } elseif ($script_id) {
  8143. $uploaded_content = $this->getContentByScriptId($script_id);
  8144. if (!$uploaded_content) {
  8145. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  8146. }
  8147. } elseif ($bid) {
  8148. $uploaded_content = $this->getContentByBid($bid);
  8149. if (!$uploaded_content) {
  8150. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  8151. }
  8152. } elseif ($content) {
  8153. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  8154. }
  8155. // elseif ($prompt) {
  8156. // $uploaded_content = filterContent($prompt);
  8157. // }
  8158. else {
  8159. $uploaded_content = '';
  8160. }
  8161. // 美术风格
  8162. $input_art_style = getProp($data, 'art_style');
  8163. if (!$input_art_style) {
  8164. $mappedArtStyle = getProp($anime, 'art_style');
  8165. }else {
  8166. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  8167. }
  8168. if (!$mappedArtStyle) {
  8169. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  8170. }else {
  8171. if (strstr($mappedArtStyle, '基础画风风格词')) {
  8172. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  8173. }else {
  8174. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  8175. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  8176. }
  8177. }
  8178. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8179. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8180. // 强制要求:
  8181. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8182. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8183. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8184. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  8185. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  8186. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  8187. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  8188. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  8189. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  8190. // 10.分镜要和场景列表、人物主体保持一致\n
  8191. // 普通要求:
  8192. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8193. // {$role_demo}
  8194. // {$scene_demo}
  8195. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8196. // 4.1片段分割逻辑(优先级从高到低):
  8197. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8198. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8199. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8200. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8201. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8202. // - 片段数量格式为: 片段数量:8
  8203. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8204. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8205. // 4.3分镜结构:每个分镜包含以下字段:
  8206. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  8207. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  8208. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8209. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  8210. // - 运镜:场景+画面描述+运镜
  8211. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  8212. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8213. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8214. // 5.$mappedArtStyle_prompt\n\n
  8215. // 示例格式:\n
  8216. // 第1集:隐形的守护者
  8217. // ###故事梗概
  8218. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8219. // ###美术风格
  8220. // 基础画风风格词:胡金铨武侠
  8221. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8222. // ###主体列表
  8223. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8224. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8225. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8226. // ###场景列表
  8227. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8228. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8229. // ###分段剧本
  8230. // 片段数量:8
  8231. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8232. // ##片段1
  8233. // 时长:12s
  8234. // 分镜1
  8235. // 场景:边境小镇街道
  8236. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8237. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8238. // 配音台词:
  8239. // 背景音效:
  8240. // 分镜2
  8241. // 场景:悦来酒馆
  8242. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8243. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8244. // 配音台词:
  8245. // 背景音效:
  8246. // 分镜3
  8247. // 场景:悦来酒馆
  8248. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8249. // 运镜:从中景推向令牌特写。
  8250. // 配音台词:
  8251. // 背景音效:
  8252. // 分镜4
  8253. // 场景:悦来酒馆
  8254. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8255. // 运镜:极速推向酒水溅起的瞬间。
  8256. // 配音台词:
  8257. // 背景音效:
  8258. // 分镜5
  8259. // 镜头描述
  8260. // 场景:悦来酒馆
  8261. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8262. // 运镜:固定机位,利用倾斜构图制造压迫感。
  8263. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8264. // 背景音效:
  8265. // \n\n";
  8266. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  8267. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  8268. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  8269. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  8270. 普通要求:
  8271. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8272. {$role_demo}
  8273. {$scene_demo}
  8274. {$prop_demo}
  8275. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8276. 5.1片段分割逻辑(优先级从高到低):
  8277. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8278. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8279. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8280. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8281. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8282. - 片段数量格式为: 片段数量:8
  8283. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8284. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8285. 5.3分镜结构:每个分镜包含以下字段:
  8286. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8287. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8288. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8289. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8290. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8291. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8292. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8293. - 运镜:场景+画面描述+运镜
  8294. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8295. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8296. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8297. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8298. 6.《情绪-视听语言映射表》:
  8299. 6.1 场景空间与时间心理学 (Scene & Temporality)
  8300. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8301. -----|---------|------------|----------------
  8302. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  8303. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  8304. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  8305. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  8306. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  8307. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8308. -----|---------|------------|----------------
  8309. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  8310. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  8311. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  8312. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  8313. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  8314. --------|---------|--------------|-------------
  8315. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  8316. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  8317. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  8318. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  8319. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  8320. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  8321. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  8322. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  8323. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  8324. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  8325. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  8326. -----|---------|------------|------------
  8327. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  8328. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  8329. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  8330. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  8331. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  8332. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  8333. --------|---------|--------------|----------
  8334. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  8335. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  8336. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  8337. 6.6 声音设计与潜意识影响 (Soundscape)
  8338. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  8339. -----|---------|------------|------------------
  8340. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  8341. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  8342. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  8343. 理论基石:
  8344. - The Five C's of Cinematography by Joseph V. Mascelli
  8345. - Film Art: An Introduction by David Bordwell
  8346. - Sight, Sound, Motion by Herbert Zettl
  8347. - Notes on the Cinematograph by Robert Bresson
  8348. \n\n
  8349. 7.{$mappedArtStyle_prompt}
  8350. 示例格式:\n
  8351. 第1集:隐形的守护者
  8352. ###故事梗概
  8353. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8354. ###美术风格
  8355. 基础画风风格词:胡金铨武侠
  8356. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8357. ###主体列表
  8358. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8359. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8360. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8361. ###场景列表
  8362. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8363. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8364. ###道具列表
  8365. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  8366. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  8367. ###分段剧本
  8368. 片段数量:8
  8369. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8370. ##片段1
  8371. 时长:12s
  8372. 分镜1
  8373. 出场角色:刀疤脸
  8374. 场景:边境小镇街道
  8375. 出场道具:酒杯-高脚杯
  8376. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8377. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8378. 配音台词:
  8379. 背景音效:
  8380. 分镜2
  8381. 出场角色:刀疤脸
  8382. 场景:悦来酒馆
  8383. 出场道具:酒杯-高脚杯
  8384. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8385. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8386. 配音台词:
  8387. 背景音效:
  8388. 分镜3
  8389. 出场角色:刀疤脸
  8390. 场景:悦来酒馆
  8391. 出场道具:酒杯-高脚杯
  8392. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8393. 运镜:从中景推向令牌特写。
  8394. 配音台词:
  8395. 背景音效:
  8396. 分镜4
  8397. 出场角色:刀疤脸
  8398. 场景:悦来酒馆
  8399. 出场道具:酒杯-高脚杯
  8400. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8401. 运镜:极速推向酒水溅起的瞬间。
  8402. 配音台词:
  8403. 背景音效:
  8404. 分镜5
  8405. 出场角色:刀疤脸
  8406. 场景:悦来酒馆
  8407. 出场道具:酒杯-高脚杯
  8408. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8409. 运镜:固定机位,利用倾斜构图制造压迫感。
  8410. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8411. 背景音效:
  8412. \n\n";
  8413. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8414. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  8415. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  8416. $prompt = $origin_prompt;
  8417. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  8418. // 获取章节内容
  8419. $full_content = getProp($anime, 'content');
  8420. if ($uploaded_content) {
  8421. $full_content = $uploaded_content;
  8422. }
  8423. // 根据章节内容拆分章节
  8424. $chapters = splitContent($full_content);
  8425. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  8426. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  8427. $messages = [];
  8428. if ($prompt == '确认分镜大纲') {
  8429. // 暂时保留
  8430. $content = $chapter_content;
  8431. if ($is_single) $content = $full_content; // 单剧集使用全文
  8432. if (!$content) {
  8433. Utils::throwError('20003:章节内容无法获取,请确认');
  8434. }
  8435. $question = $is_single
  8436. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  8437. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  8438. // 构建消息
  8439. $messages[] =
  8440. [
  8441. 'role' => 'user',
  8442. 'content' => $question
  8443. ];
  8444. }else if ($prompt == '继续策划下一集') {
  8445. if ($is_single) {
  8446. Utils::throwError('20003:单剧集不支持继续策划下一集');
  8447. }
  8448. $content = $chapter_content;
  8449. if (!$content) {
  8450. Utils::throwError('20003:章节内容无法获取,请确认');
  8451. }
  8452. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  8453. // 获取上一集最后记录
  8454. $prev_sequence = $episode_number - 1;
  8455. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  8456. // 构建消息
  8457. $messages[] =
  8458. [
  8459. 'role' => 'user',
  8460. 'content' => $question
  8461. ];
  8462. // dd($messages);
  8463. }else {
  8464. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  8465. if (!$content) {
  8466. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  8467. }
  8468. if (!$content) {
  8469. Utils::throwError('20003:章节内容无法获取,请确认');
  8470. }
  8471. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  8472. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  8473. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  8474. if ($origin_prompt) {
  8475. $question .= "本次修改要求如下:\n{$origin_prompt}";
  8476. }
  8477. $messages[] =
  8478. [
  8479. 'role' => 'user',
  8480. 'content' => $question
  8481. ];
  8482. }
  8483. // 处理文本模型
  8484. $model = getProp($data, 'model');
  8485. if (!$model) {
  8486. // 用户没有输入,从anime表获取
  8487. $model = getProp($anime, 'model');
  8488. if (!$model) {
  8489. // anime表也没有,使用默认值
  8490. $model = 'deepseek-v4-pro';
  8491. }
  8492. }
  8493. // 验证模型是否在可用模型表中
  8494. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8495. $model = 'deepseek-v4-pro';
  8496. }
  8497. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8498. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  8499. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8500. if ($model === 'deepseek-chat') {
  8501. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8502. $model = 'deepseek-v4-flash';
  8503. $thinkingMode = 'disabled';
  8504. } elseif ($model === 'deepseek-reasoner') {
  8505. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8506. $model = 'deepseek-v4-flash';
  8507. $thinkingMode = 'enabled';
  8508. }
  8509. $post_data = [
  8510. 'model' => $model,
  8511. 'messages' => $messages,
  8512. // 'max_tokens' => 8192,
  8513. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8514. 'frequency_penalty' => 0,
  8515. 'presence_penalty' => 0,
  8516. 'response_format' => ['type' => 'text'],
  8517. 'thinking' => ['type' => $thinkingMode],
  8518. 'stream' => true // 启用流式输出
  8519. ];
  8520. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8521. // 根据模型类型选择调用方法
  8522. $fullContent = '';
  8523. $fullReasoningContent = '';
  8524. $usage = [];
  8525. try {
  8526. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8527. // DeepSeek 官方模型使用 DeepSeek API
  8528. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8529. } else if (in_array($model, $this->gpt_text_models)) {
  8530. // GPT-5.4 模型使用 TokenRouter API
  8531. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8532. } else if (in_array($model, $this->gemini_text_models)) {
  8533. // Gemini 模型使用 Gemini API
  8534. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8535. } else {
  8536. // 其他模型使用火山引擎API
  8537. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8538. }
  8539. // 验证返回值类型
  8540. if (!is_iterable($streamGenerator)) {
  8541. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8542. dLog('deepseek')->error('chat流式生成器无效', [
  8543. 'generator_type' => $errorType,
  8544. 'model' => $model,
  8545. 'anime_id' => $anime_id,
  8546. 'episode_number' => $episode_number
  8547. ]);
  8548. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  8549. 'type' => $errorType,
  8550. 'model' => $model
  8551. ]);
  8552. yield [
  8553. 'type' => 'error',
  8554. 'episode' => [],
  8555. 'answer' => '',
  8556. 'reasoning' => '',
  8557. 'usage' => [],
  8558. 'error' => '接口返回数据异常,请重新请求'
  8559. ];
  8560. return;
  8561. }
  8562. // 处理流式输出
  8563. foreach ($streamGenerator as $chunk) {
  8564. if (isset($chunk['type'])) {
  8565. if ($chunk['type'] === 'done') {
  8566. // 最终结果
  8567. $fullContent = $chunk['full_content'];
  8568. $fullReasoningContent = $chunk['full_reasoning'];
  8569. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8570. } else {
  8571. // 逐块yield数据
  8572. yield $chunk;
  8573. }
  8574. }
  8575. }
  8576. } catch (\Exception $e) {
  8577. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  8578. 'model' => $model,
  8579. 'anime_id' => $anime_id,
  8580. 'episode_number' => $episode_number,
  8581. 'trace' => $e->getTraceAsString()
  8582. ]);
  8583. logDB('deepseek', 'error', 'chat流式处理失败', [
  8584. 'error' => $e->getMessage(),
  8585. 'model' => $model
  8586. ]);
  8587. yield [
  8588. 'type' => 'error',
  8589. 'episode' => [],
  8590. 'answer' => '',
  8591. 'reasoning' => '',
  8592. 'usage' => [],
  8593. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8594. ];
  8595. return;
  8596. }
  8597. dLog('deepseek')->info('完整内容: '.$fullContent);
  8598. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8599. // 处理完整内容并返回最终结果
  8600. $episode_arr = handleEpisodeContentForAce($fullContent);
  8601. logDB('deepseek', 'info', '解析内容', $episode_arr);
  8602. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  8603. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  8604. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  8605. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  8606. // }
  8607. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  8608. $max_retries = 3;
  8609. $retry_count = 0;
  8610. $validation_failed = false;
  8611. $validation_error_msg = '';
  8612. // 验证生成的内容
  8613. if ($anime_script_id) {
  8614. // 检查是否有acts数据
  8615. if (empty($episode_arr['acts'])) {
  8616. $validation_failed = true;
  8617. $validation_error_msg = '未生成分镜剧本相关的内容';
  8618. } else {
  8619. // 仅当存在强制主体设定时校验主体列表
  8620. if (!empty($extra_roles)) {
  8621. $generated_roles = array_column($episode_arr['roles'], 'role');
  8622. // 过滤掉"旁白"角色
  8623. $generated_roles = array_filter($generated_roles, function($role) {
  8624. return $role !== '旁白';
  8625. });
  8626. $expected_roles = array_keys($extra_roles);
  8627. // 找出生成的主体中不在预期列表中的主体
  8628. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8629. if (!empty($invalid_roles)) {
  8630. $validation_failed = true;
  8631. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8632. }
  8633. }
  8634. // 仅当存在强制场景设定时校验场景列表
  8635. if (!$validation_failed && !empty($extra_scenes)) {
  8636. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  8637. $expected_scenes = array_keys($extra_scenes);
  8638. // 找出生成的场景中不在预期列表中的场景
  8639. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8640. if (!empty($invalid_scenes)) {
  8641. $validation_failed = true;
  8642. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8643. }
  8644. }
  8645. // 仅当存在强制道具设定时校验道具列表
  8646. if (!$validation_failed && !empty($extra_props)) {
  8647. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8648. $expected_props = array_keys($extra_props);
  8649. // 找出生成的道具中不在预期列表中的道具
  8650. $invalid_props = array_diff($generated_props, $expected_props);
  8651. if (!empty($invalid_props)) {
  8652. $validation_failed = true;
  8653. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8654. }
  8655. }
  8656. }
  8657. } else {
  8658. // 如果没有anime_script_id,只检查是否有acts数据
  8659. if (empty($episode_arr['acts'])) {
  8660. $validation_failed = true;
  8661. $validation_error_msg = '未生成分镜剧本相关的内容';
  8662. }
  8663. }
  8664. // 重试逻辑
  8665. while ($validation_failed && $retry_count < $max_retries) {
  8666. $retry_count++;
  8667. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  8668. 'reason' => $validation_error_msg,
  8669. 'anime_id' => $anime_id,
  8670. 'episode_number' => $episode_number
  8671. ]);
  8672. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  8673. 'reason' => $validation_error_msg,
  8674. 'anime_id' => $anime_id
  8675. ]);
  8676. // 发送流式重试提示
  8677. yield [
  8678. 'type' => 'retry',
  8679. 'retry_count' => $retry_count,
  8680. 'reason' => $validation_error_msg
  8681. ];
  8682. // 构建重试提示词
  8683. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  8684. if ($anime_script_id) {
  8685. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  8686. $retry_prompt .= "2. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  8687. $retry_prompt .= "3. 必须包含完整的分镜剧本内容\n";
  8688. } else {
  8689. $retry_prompt .= "1. 必须包含完整的分镜剧本内容\n";
  8690. }
  8691. // 添加重试消息到messages
  8692. $messages[] = [
  8693. 'role' => 'assistant',
  8694. 'content' => $fullContent
  8695. ];
  8696. $messages[] = [
  8697. 'role' => 'user',
  8698. 'content' => $retry_prompt
  8699. ];
  8700. // 更新post_data的messages
  8701. $post_data['messages'] = $messages;
  8702. // 重新调用API
  8703. try {
  8704. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8705. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8706. } else if (in_array($model, $this->gpt_text_models)) {
  8707. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8708. } else if (in_array($model, $this->gemini_text_models)) {
  8709. // Gemini 模型使用 Gemini API
  8710. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8711. } else {
  8712. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8713. }
  8714. // 处理流式输出
  8715. $fullContent = '';
  8716. $fullReasoningContent = '';
  8717. foreach ($streamGenerator as $chunk) {
  8718. if (isset($chunk['type'])) {
  8719. if ($chunk['type'] === 'done') {
  8720. $fullContent = $chunk['full_content'];
  8721. $fullReasoningContent = $chunk['full_reasoning'];
  8722. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8723. } else {
  8724. yield $chunk;
  8725. }
  8726. }
  8727. }
  8728. // 重新解析内容
  8729. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  8730. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  8731. $episode_arr = handleEpisodeContentForAce($fullContent);
  8732. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  8733. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  8734. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  8735. // }
  8736. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  8737. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  8738. // 重新验证
  8739. $validation_failed = false;
  8740. $validation_error_msg = '';
  8741. if ($anime_script_id) {
  8742. if (empty($episode_arr['acts'])) {
  8743. $validation_failed = true;
  8744. $validation_error_msg = '未生成分镜剧本相关的内容';
  8745. } else {
  8746. // 仅当存在强制主体设定时校验主体列表
  8747. if (!empty($extra_roles)) {
  8748. $generated_roles = array_column($episode_arr['roles'], 'role');
  8749. // 过滤掉"旁白"角色
  8750. $generated_roles = array_filter($generated_roles, function($role) {
  8751. return $role !== '旁白';
  8752. });
  8753. $expected_roles = array_keys($extra_roles);
  8754. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8755. if (!empty($invalid_roles)) {
  8756. $validation_failed = true;
  8757. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8758. }
  8759. }
  8760. // 仅当存在强制场景设定时校验场景列表
  8761. if (!$validation_failed && !empty($extra_scenes)) {
  8762. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  8763. $expected_scenes = array_keys($extra_scenes);
  8764. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8765. if (!empty($invalid_scenes)) {
  8766. $validation_failed = true;
  8767. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8768. }
  8769. }
  8770. // 仅当存在强制道具设定时校验道具列表
  8771. if (!$validation_failed && !empty($extra_props)) {
  8772. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8773. $expected_props = array_keys($extra_props);
  8774. $invalid_props = array_diff($generated_props, $expected_props);
  8775. if (!empty($invalid_props)) {
  8776. $validation_failed = true;
  8777. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8778. }
  8779. }
  8780. }
  8781. } else {
  8782. if (empty($episode_arr['acts'])) {
  8783. $validation_failed = true;
  8784. $validation_error_msg = '未生成分镜剧本相关的内容';
  8785. }
  8786. }
  8787. } catch (\Exception $e) {
  8788. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  8789. 'trace' => $e->getTraceAsString()
  8790. ]);
  8791. break;
  8792. }
  8793. }
  8794. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  8795. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  8796. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  8797. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  8798. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  8799. if ($validation_failed && $retry_count >= $max_retries) {
  8800. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  8801. 'retry_count' => $retry_count,
  8802. 'last_error' => $validation_error_msg
  8803. ]);
  8804. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  8805. 'error' => $validation_error_msg,
  8806. 'anime_id' => $anime_id
  8807. ]);
  8808. $validation_failed = false;
  8809. $validation_error_msg = '';
  8810. }
  8811. // 如果重试后仍然失败
  8812. if ($validation_failed) {
  8813. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  8814. 'retry_count' => $retry_count,
  8815. 'last_error' => $validation_error_msg
  8816. ]);
  8817. try {
  8818. $now = date('Y-m-d H:i:s');
  8819. $records = [
  8820. [
  8821. 'uid' => $uid,
  8822. 'anime_id' => $anime_id,
  8823. 'sequence' => $episode_number,
  8824. 'role' => 'user',
  8825. 'content' => $prompt,
  8826. 'created_at' => $now,
  8827. 'updated_at' => $now
  8828. ],
  8829. [
  8830. 'uid' => $uid,
  8831. 'anime_id' => $anime_id,
  8832. 'sequence' => $episode_number,
  8833. 'role' => 'assistant',
  8834. 'content' => $fullContent,
  8835. 'created_at' => $now,
  8836. 'updated_at' => $now
  8837. ]
  8838. ];
  8839. DB::table('mp_anime_records')->insert($records);
  8840. } catch (\Exception $e) {
  8841. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8842. }
  8843. yield [
  8844. 'type' => 'done',
  8845. 'episode' => [],
  8846. 'answer' => $fullContent,
  8847. 'reasoning' => $fullReasoningContent,
  8848. 'usage' => $usage,
  8849. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  8850. ];
  8851. return;
  8852. }
  8853. // 验证成功,记录日志
  8854. if ($retry_count > 0) {
  8855. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  8856. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  8857. }
  8858. // 老逻辑
  8859. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  8860. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  8861. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  8862. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  8863. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  8864. $existing_props = is_array($existing_props) ? $existing_props : [];
  8865. $now = date('Y-m-d H:i:s');
  8866. try {
  8867. DB::beginTransaction();
  8868. $saveResult = $this->saveEpisodeVersionData(
  8869. $anime_id,
  8870. $episode_number,
  8871. $episode_arr,
  8872. $existing_roles,
  8873. $existing_scenes,
  8874. $existing_props,
  8875. $current_episode,
  8876. $base_episode,
  8877. $is_regenerate_version,
  8878. $content,
  8879. $now,
  8880. $ref_products
  8881. );
  8882. $episode = $saveResult['episode'];
  8883. $episode_id = $saveResult['episode_id'];
  8884. $merged_roles = $saveResult['merged_roles'];
  8885. $merged_scenes = $saveResult['merged_scenes'];
  8886. $merged_props = $saveResult['merged_props'];
  8887. $record_content = $origin_prompt;
  8888. if ($uploaded_content !== '') {
  8889. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  8890. }
  8891. $records = [
  8892. [
  8893. 'uid' => $uid,
  8894. 'anime_id' => $anime_id,
  8895. 'role' => 'user',
  8896. 'content' => $record_content,
  8897. 'sequence' => $episode_number,
  8898. 'episode_id' => $episode_id,
  8899. 'created_at' => $now,
  8900. 'updated_at' => $now
  8901. ],
  8902. [
  8903. 'uid' => $uid,
  8904. 'anime_id' => $anime_id,
  8905. 'role' => 'assistant',
  8906. 'content' => $fullContent,
  8907. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8908. 'sequence' => $episode_number,
  8909. 'episode_id' => $episode_id,
  8910. 'created_at' => $now,
  8911. 'updated_at' => $now
  8912. ]
  8913. ];
  8914. $boolen4 = DB::table('mp_anime_records')->insert($records);
  8915. if (!$boolen4) {
  8916. Utils::throwError('20003:对话记录保存失败');
  8917. }
  8918. // 保存模型到anime表
  8919. $update_anime_data = [
  8920. 'model' => $model,
  8921. 'updated_at' => $now
  8922. ];
  8923. if ($uploaded_content) {
  8924. $update_anime_data['content'] = $uploaded_content;
  8925. }
  8926. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  8927. }catch (\Exception $e) {
  8928. DB::rollBack();
  8929. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  8930. yield [
  8931. 'type' => 'done',
  8932. 'answer' => $fullContent,
  8933. 'reasoning' => $fullReasoningContent,
  8934. 'usage' => $usage,
  8935. 'error' => $e->getMessage(),
  8936. ];
  8937. return;
  8938. }
  8939. DB::commit();
  8940. if ($is_global_generate_pics) {
  8941. // // 批量生成全局角色图片
  8942. // $this->batchSetGlobalRoleImg([
  8943. // 'anime_id' => $anime_id,
  8944. // ], true);
  8945. // // 批量生成全局场景图片
  8946. // $this->batchSetGlobalSceneImg([
  8947. // 'anime_id' => $anime_id,
  8948. // ], true);
  8949. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8950. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8951. }
  8952. $episode['episode_id'] = $episode_id;
  8953. $episode['roles'] = $merged_roles;
  8954. $episode['scenes'] = $merged_scenes;
  8955. $episode['props'] = $merged_props;
  8956. $episode['end_episode_sequence'] = $end_episode_sequence;
  8957. // 获取mp_animes表中的视频参数
  8958. $episode['video_params'] = [
  8959. 'video_model' => getProp($anime, 'video_model'),
  8960. 'video_resolution' => getProp($anime, 'video_resolution'),
  8961. 'ratio' => getProp($anime, 'video_ratio'),
  8962. ];
  8963. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  8964. yield [
  8965. 'type' => 'done',
  8966. 'episode' => $episode,
  8967. 'answer' => $fullContent,
  8968. 'reasoning' => $fullReasoningContent,
  8969. 'usage' => $usage
  8970. ];
  8971. }
  8972. /**
  8973. * chatForAce的非流式版本 - 用于定时任务
  8974. * 只获取最终 type=done 的数据,并验证必要字段
  8975. *
  8976. * @param array $data 请求数据
  8977. * @return array 生成结果
  8978. */
  8979. public function chatForAceNonStream($data) {
  8980. $finalResult = null;
  8981. // 调用流式方法,只保存 type=done 的数据
  8982. foreach ($this->chatForAce($data) as $chunk) {
  8983. // 只关注最终结果
  8984. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  8985. $finalResult = $chunk;
  8986. break; // 找到 done 就退出循环
  8987. }
  8988. }
  8989. // 验证最终结果
  8990. if (!$finalResult) {
  8991. return ['error' => '生成失败:未获取到最终结果'];
  8992. }
  8993. // 检查是否有错误
  8994. if (isset($finalResult['error']) && $finalResult['error']) {
  8995. return $finalResult;
  8996. }
  8997. // 验证必要字段
  8998. $episode = $finalResult['episode'] ?? [];
  8999. // 验证 roles
  9000. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  9001. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  9002. }
  9003. // 验证 scenes
  9004. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  9005. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  9006. }
  9007. // 验证 props(道具可以为空,但必须存在且为数组)
  9008. if (!isset($episode['props']) || !is_array($episode['props'])) {
  9009. $episode['props'] = [];
  9010. }
  9011. // 验证 acts(分镜剧本)
  9012. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  9013. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  9014. }
  9015. // 更新验证后的 episode 数据
  9016. $finalResult['episode'] = $episode;
  9017. // 记录验证成功日志
  9018. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  9019. 'roles_count' => count($episode['roles']),
  9020. 'scenes_count' => count($episode['scenes']),
  9021. 'props_count' => count($episode['props']),
  9022. 'acts_count' => count($episode['acts'])
  9023. ]);
  9024. return $finalResult;
  9025. }
  9026. /**
  9027. * 批量生成多个分集
  9028. *
  9029. * @param array $data 请求数据
  9030. * @return array 任务信息
  9031. */
  9032. public function batchGenerateEpisodes($data) {
  9033. $uid = Site::getUid();
  9034. $cpid = Site::getCpid();
  9035. $anime_id = getProp($data, 'anime_id');
  9036. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  9037. if (!$anime_id) {
  9038. Utils::throwError('20003:anime_id参数缺失');
  9039. }
  9040. if ($generate_episode_number < 1) {
  9041. Utils::throwError('20003:生成集数必须大于0');
  9042. }
  9043. // 获取动漫信息
  9044. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9045. if (!$anime) {
  9046. Utils::throwError('20003:该剧集不存在');
  9047. }
  9048. // 检查是否是全能模式
  9049. if ((int)getProp($anime, 'ace_mode') !== 1) {
  9050. Utils::throwError('20003:只有全能模式才支持批量生成');
  9051. }
  9052. // 检查是否是多剧集模式
  9053. if ((int)getProp($anime, 'is_multi') !== 1) {
  9054. Utils::throwError('20003:单剧集不支持批量生成');
  9055. }
  9056. // 获取当前已生成的最大集数
  9057. $currentMaxEpisode = DB::table('mp_anime_episodes')
  9058. ->where('anime_id', $anime_id)
  9059. ->where('is_default', 1)
  9060. ->max('episode_number');
  9061. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  9062. // 确定起始集数
  9063. $startEpisodeNumber = $currentMaxEpisode + 1;
  9064. // 计算结束集数
  9065. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  9066. // 检查是否超过总集数限制
  9067. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  9068. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  9069. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  9070. }
  9071. $now = date('Y-m-d H:i:s');
  9072. $createdTasks = [];
  9073. $skippedTasks = [];
  9074. // 为每一集创建详情记录
  9075. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  9076. // 检查是否已有该集的任务记录
  9077. $existingTask = DB::table('mp_batch_episode_generation_details')
  9078. ->where('anime_id', $anime_id)
  9079. ->where('episode_number', $episodeNumber)
  9080. ->first();
  9081. if ($existingTask) {
  9082. // 如果已存在且未完成,跳过
  9083. if (in_array($existingTask->status, ['pending', 'processing'])) {
  9084. $skippedTasks[] = $episodeNumber;
  9085. continue;
  9086. }
  9087. // 如果是失败状态,可以重新创建(删除旧记录)
  9088. if ($existingTask->status === 'failed') {
  9089. DB::table('mp_batch_episode_generation_details')
  9090. ->where('id', $existingTask->id)
  9091. ->delete();
  9092. }
  9093. // 如果是已完成状态,也跳过
  9094. if ($existingTask->status === 'completed') {
  9095. $skippedTasks[] = $episodeNumber;
  9096. continue;
  9097. }
  9098. }
  9099. // 准备任务数据
  9100. $taskData = [
  9101. 'anime_id' => $anime_id,
  9102. 'uid' => $uid,
  9103. 'cpid' => $cpid,
  9104. 'episode_number' => $episodeNumber,
  9105. 'status' => 'pending',
  9106. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  9107. 'retry_count' => 0,
  9108. 'created_at' => $now,
  9109. 'updated_at' => $now
  9110. ];
  9111. // 创建任务记录
  9112. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  9113. if ($taskId) {
  9114. $createdTasks[] = $episodeNumber;
  9115. }
  9116. }
  9117. if (empty($createdTasks)) {
  9118. if (!empty($skippedTasks)) {
  9119. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  9120. } else {
  9121. Utils::throwError('20003:创建批量生成任务失败');
  9122. }
  9123. }
  9124. return [
  9125. 'anime_id' => $anime_id,
  9126. 'start_episode' => $startEpisodeNumber,
  9127. 'end_episode' => $endEpisodeNumber,
  9128. 'total_episodes' => $generate_episode_number,
  9129. 'created_episodes' => $createdTasks,
  9130. 'skipped_episodes' => $skippedTasks,
  9131. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集。" .
  9132. "已创建: " . implode(',', $createdTasks) .
  9133. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : "")
  9134. ];
  9135. }
  9136. /**
  9137. * 获取批量生成任务状态
  9138. *
  9139. * @param array $data 请求数据
  9140. * @return array 任务状态信息
  9141. */
  9142. public function getBatchGenerationTaskStatus($data) {
  9143. $anime_id = getProp($data, 'anime_id');
  9144. if (!$anime_id) {
  9145. Utils::throwError('20003:anime_id参数缺失');
  9146. }
  9147. // 获取该anime的所有任务
  9148. $tasks = DB::table('mp_batch_episode_generation_details')
  9149. ->where('anime_id', $anime_id)
  9150. ->orderBy('episode_number')
  9151. ->get()
  9152. ->map(function($item) {
  9153. return [
  9154. 'id' => $item->id,
  9155. 'episode_number' => $item->episode_number,
  9156. 'status' => $item->status,
  9157. 'error_message' => $item->error_message,
  9158. 'retry_count' => $item->retry_count,
  9159. 'created_at' => $item->created_at,
  9160. 'updated_at' => $item->updated_at,
  9161. 'completed_at' => $item->completed_at
  9162. ];
  9163. })
  9164. ->toArray();
  9165. if (empty($tasks)) {
  9166. Utils::throwError('20003:该剧集没有批量生成任务');
  9167. }
  9168. // 统计各状态数量
  9169. $totalCount = count($tasks);
  9170. $pendingCount = 0;
  9171. $processingCount = 0;
  9172. $completedCount = 0;
  9173. $failedCount = 0;
  9174. foreach ($tasks as $task) {
  9175. switch ($task['status']) {
  9176. case 'pending':
  9177. $pendingCount++;
  9178. break;
  9179. case 'processing':
  9180. $processingCount++;
  9181. break;
  9182. case 'completed':
  9183. $completedCount++;
  9184. break;
  9185. case 'failed':
  9186. $failedCount++;
  9187. break;
  9188. }
  9189. }
  9190. // 计算进度百分比
  9191. $progress = 0;
  9192. if ($totalCount > 0) {
  9193. $progress = round(($completedCount / $totalCount) * 100, 2);
  9194. }
  9195. // 判断整体状态
  9196. $overallStatus = 'processing';
  9197. if ($completedCount === $totalCount) {
  9198. $overallStatus = 'completed';
  9199. } elseif ($pendingCount === $totalCount) {
  9200. $overallStatus = 'pending';
  9201. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  9202. $overallStatus = 'failed';
  9203. }
  9204. return [
  9205. 'anime_id' => $anime_id,
  9206. 'total_episodes' => $totalCount,
  9207. 'pending_count' => $pendingCount,
  9208. 'processing_count' => $processingCount,
  9209. 'completed_count' => $completedCount,
  9210. 'failed_count' => $failedCount,
  9211. 'progress' => $progress,
  9212. 'overall_status' => $overallStatus,
  9213. 'tasks' => $tasks
  9214. ];
  9215. }
  9216. /**
  9217. * 将生成内容中不在强制列表中的资源合并进强制列表
  9218. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  9219. *
  9220. * @param array $generated 生成内容中的资源列表
  9221. * @param array $forced 强制资源列表(key为资源名称)
  9222. * @param string $type 资源类型:role、scene、prop
  9223. * @return array
  9224. */
  9225. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  9226. {
  9227. foreach ($generated as $item) {
  9228. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  9229. if ($name === null || $name === '') {
  9230. continue;
  9231. }
  9232. if ($name === '旁白') {
  9233. continue;
  9234. }
  9235. if (!isset($forced[$name])) {
  9236. $forced[$name] = $item;
  9237. }
  9238. }
  9239. return $forced;
  9240. }
  9241. /**
  9242. * 智能匹配并替换主体和场景名称
  9243. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  9244. *
  9245. * @param array $episode_arr 解析后的剧集数据
  9246. * @param array $extra_roles 强制主体设定(key为主体名称)
  9247. * @param array $extra_scenes 强制场景设定(key为场景名称)
  9248. * @return array 替换后的剧集数据
  9249. */
  9250. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  9251. $replaced_count = 0;
  9252. // 1. 处理主体列表
  9253. if (!empty($episode_arr['roles'])) {
  9254. foreach ($episode_arr['roles'] as &$role) {
  9255. $generated_role_name = $role['role'] ?? '';
  9256. // 跳过旁白
  9257. if ($generated_role_name === '旁白') {
  9258. continue;
  9259. }
  9260. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  9261. if (!isset($extra_roles[$generated_role_name])) {
  9262. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  9263. if ($matched_role) {
  9264. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  9265. $role['role'] = $matched_role;
  9266. $replaced_count++;
  9267. }
  9268. }
  9269. }
  9270. }
  9271. // 2. 处理场景列表
  9272. if (!empty($episode_arr['scenes'])) {
  9273. foreach ($episode_arr['scenes'] as &$scene) {
  9274. $generated_scene_name = $scene['scene'] ?? '';
  9275. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  9276. if (!isset($extra_scenes[$generated_scene_name])) {
  9277. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  9278. if ($matched_scene) {
  9279. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  9280. $scene['scene'] = $matched_scene;
  9281. $replaced_count++;
  9282. }
  9283. }
  9284. }
  9285. }
  9286. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  9287. if (!empty($episode_arr['acts'])) {
  9288. foreach ($episode_arr['acts'] as &$act) {
  9289. if (!empty($act['segments'])) {
  9290. foreach ($act['segments'] as &$segment) {
  9291. if (!empty($segment['segment_content'])) {
  9292. $original_content = $segment['segment_content'];
  9293. $replaced_content = $original_content;
  9294. // 替换场景名 - 在文本中查找并替换
  9295. foreach (array_keys($extra_scenes) as $full_scene_name) {
  9296. // 尝试找到可能的短名称
  9297. $potential_short_names = [];
  9298. // 提取场景名的主要部分(冒号之前)
  9299. if (mb_strpos($full_scene_name, ':') !== false) {
  9300. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  9301. $potential_short_names[] = $short_name;
  9302. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  9303. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  9304. $potential_short_names[] = $short_name;
  9305. }
  9306. // 替换场景字段中的短名称
  9307. foreach ($potential_short_names as $short_name) {
  9308. if ($short_name !== $full_scene_name) {
  9309. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  9310. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  9311. if ($new_content !== $replaced_content) {
  9312. $replaced_content = $new_content;
  9313. $replaced_count++;
  9314. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  9315. }
  9316. }
  9317. }
  9318. }
  9319. // 替换配音角色名(跳过旁白)
  9320. foreach (array_keys($extra_roles) as $full_role_name) {
  9321. if ($full_role_name === '旁白') {
  9322. continue;
  9323. }
  9324. // 尝试找到可能的短名称
  9325. $potential_short_names = [];
  9326. // 提取角色名的主要部分(短横线之前)
  9327. if (mb_strpos($full_role_name, '-') !== false) {
  9328. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  9329. $potential_short_names[] = $short_name;
  9330. }
  9331. // 替换配音台词中的短名称
  9332. foreach ($potential_short_names as $short_name) {
  9333. if ($short_name !== $full_role_name) {
  9334. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  9335. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  9336. if ($new_content !== $replaced_content) {
  9337. $replaced_content = $new_content;
  9338. $replaced_count++;
  9339. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  9340. }
  9341. }
  9342. }
  9343. }
  9344. // 如果有替换,更新segment_content
  9345. if ($replaced_content !== $original_content) {
  9346. $segment['segment_content'] = $replaced_content;
  9347. }
  9348. }
  9349. }
  9350. }
  9351. }
  9352. }
  9353. if ($replaced_count > 0) {
  9354. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  9355. 'replaced_count' => $replaced_count
  9356. ]);
  9357. }
  9358. return $episode_arr;
  9359. }
  9360. /**
  9361. * 查找匹配的名称
  9362. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  9363. *
  9364. * @param string $generated_name 生成的名称
  9365. * @param array $expected_names 预期的名称列表
  9366. * @return string|null 匹配到的名称,如果没有匹配则返回null
  9367. */
  9368. private function findMatchingName($generated_name, $expected_names) {
  9369. if (empty($generated_name)) {
  9370. return null;
  9371. }
  9372. // 尝试精确匹配
  9373. if (in_array($generated_name, $expected_names)) {
  9374. return $generated_name;
  9375. }
  9376. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  9377. foreach ($expected_names as $expected_name) {
  9378. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  9379. if (mb_strpos($expected_name, $generated_name) === 0) {
  9380. return $expected_name;
  9381. }
  9382. }
  9383. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  9384. // 这样可以处理一些变体,但优先级较低
  9385. foreach ($expected_names as $expected_name) {
  9386. if (mb_strpos($expected_name, $generated_name) !== false) {
  9387. return $expected_name;
  9388. }
  9389. }
  9390. return null;
  9391. }
  9392. /**
  9393. * 重新生成分段剧本
  9394. * @param array $data 包含以下字段:
  9395. * - prompt: string|null 用户修改要求(可选)
  9396. * - template_id: int|null 提示词模板ID(可选)
  9397. * - act_id: int|null 单个片段ID(与episode_id二选一)
  9398. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  9399. * @return array 返回生成结果
  9400. */
  9401. public function regenerateSegmentScript($data) {
  9402. $uid = Site::getUid();
  9403. $prompt = trim((string)getProp($data, 'prompt', ''));
  9404. $template_id = getProp($data, 'template_id', 0);
  9405. $act_id = getProp($data, 'act_id', 0);
  9406. $episode_id = getProp($data, 'episode_id', 0);
  9407. // 验证:prompt和template_id至少提供一个
  9408. if (empty($prompt) && empty($template_id)) {
  9409. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  9410. }
  9411. // 验证:act_id和episode_id二选一
  9412. if (empty($act_id) && empty($episode_id)) {
  9413. Utils::throwError('20003:请提供片段ID或剧集ID');
  9414. }
  9415. if (!empty($act_id) && !empty($episode_id)) {
  9416. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  9417. }
  9418. // 如果提供了template_id,获取模板提示词
  9419. $template_prompt = '';
  9420. if ($template_id > 0) {
  9421. $template = DB::table('mp_prompt_templates')
  9422. ->where('id', $template_id)
  9423. ->where('is_deleted', 0)
  9424. ->first();
  9425. if (!$template) {
  9426. Utils::throwError('20003:提示词模板不存在或已删除');
  9427. }
  9428. $template_prompt = $template->template_prompt ?? '';
  9429. }
  9430. // 合并用户提示词和模板提示词
  9431. $final_prompt = '';
  9432. if (!empty($template_prompt)) {
  9433. $final_prompt = $template_prompt;
  9434. if (!empty($prompt)) {
  9435. $final_prompt .= "\n\n补充要求:" . $prompt;
  9436. }
  9437. } else {
  9438. $final_prompt = $prompt;
  9439. }
  9440. // 获取需要重新生成的内容参考
  9441. $reference_content = '';
  9442. $target_episode_id = 0;
  9443. $target_anime_id = 0;
  9444. $target_episode_number = 0;
  9445. if ($act_id > 0) {
  9446. // 单个片段模式:获取该片段的内容
  9447. $segment = DB::table('mp_episode_segments')
  9448. ->where('id', $act_id)
  9449. ->first();
  9450. if (!$segment) {
  9451. Utils::throwError('20003:片段不存在');
  9452. }
  9453. $target_episode_id = $segment->episode_id;
  9454. $target_anime_id = $segment->anime_id;
  9455. $target_episode_number = $segment->episode_number;
  9456. $reference_content = $segment->act_content ?? '';
  9457. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  9458. } else {
  9459. // 整个剧集模式:获取所有片段的内容
  9460. $segments = DB::table('mp_episode_segments')
  9461. ->where('episode_id', $episode_id)
  9462. ->orderBy('act_number')
  9463. ->get();
  9464. if ($segments->isEmpty()) {
  9465. Utils::throwError('20003:该剧集没有片段数据');
  9466. }
  9467. $target_episode_id = $episode_id;
  9468. $target_anime_id = $segments[0]->anime_id;
  9469. $target_episode_number = $segments[0]->episode_number;
  9470. // 拼接所有片段内容,保留格式用于AI理解
  9471. $act_contents = [];
  9472. foreach ($segments as $seg) {
  9473. $act_number = $seg->act_number;
  9474. $act_content = $seg->act_content ?? '';
  9475. if (!empty($act_content)) {
  9476. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  9477. }
  9478. }
  9479. $reference_content = implode("\n\n", $act_contents);
  9480. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  9481. if ($episode_content) {
  9482. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  9483. }else {
  9484. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  9485. }
  9486. }
  9487. if (empty($reference_content)) {
  9488. Utils::throwError('20003:没有可参考的片段内容');
  9489. }
  9490. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  9491. $episode = DB::table('mp_anime_episodes')
  9492. ->where('id', $target_episode_id)
  9493. ->first();
  9494. if (!$episode) {
  9495. Utils::throwError('20003:剧集不存在');
  9496. }
  9497. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  9498. $anime_script_id = getProp($anime, 'script_id');
  9499. $intro = $episode->intro ?? '';
  9500. $art_style = $episode->art_style ?? '';
  9501. $roles = json_decode($episode->roles ?? '[]', true);
  9502. $scenes = json_decode($episode->scenes ?? '[]', true);
  9503. $props = json_decode($episode->props ?? '[]', true);
  9504. // 构建提示词中的主体列表和场景列表参考
  9505. $roles_ref = '';
  9506. if (!empty($roles) && is_array($roles)) {
  9507. $roles_list = [];
  9508. foreach ($roles as $role) {
  9509. $role_name = getProp($role, 'role', '');
  9510. $role_desc = getProp($role, 'description', '');
  9511. $pic_prompt = getProp($role, 'pic_prompt', '');
  9512. $voice_prompt = getProp($role, 'voice_prompt', '');
  9513. if (!empty($role_name)) {
  9514. $role_line = $role_name;
  9515. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  9516. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  9517. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  9518. $roles_list[] = $role_line;
  9519. }
  9520. }
  9521. if (!empty($roles_list)) {
  9522. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  9523. }
  9524. }
  9525. $scenes_ref = '';
  9526. if (!empty($scenes) && is_array($scenes)) {
  9527. $scenes_list = [];
  9528. foreach ($scenes as $scene) {
  9529. $scene_name = getProp($scene, 'scene', '');
  9530. $scene_desc = getProp($scene, 'description', '');
  9531. $pic_prompt = getProp($scene, 'pic_prompt', '');
  9532. if (!empty($scene_name)) {
  9533. $scene_line = $scene_name;
  9534. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  9535. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  9536. $scenes_list[] = $scene_line;
  9537. }
  9538. }
  9539. if (!empty($scenes_list)) {
  9540. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  9541. }
  9542. }
  9543. $props_ref = '';
  9544. if (!empty($props) && is_array($props)) {
  9545. $props_list = [];
  9546. foreach ($props as $prop) {
  9547. $prop_name = getProp($prop, 'prop', '');
  9548. $prop_desc = getProp($prop, 'description', '');
  9549. $pic_prompt = getProp($prop, 'pic_prompt', '');
  9550. if (!empty($prop_name)) {
  9551. $prop_line = $prop_name;
  9552. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  9553. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  9554. $props_list[] = $prop_line;
  9555. }
  9556. }
  9557. if (!empty($props_list)) {
  9558. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  9559. }
  9560. }
  9561. // 构建美术风格参考
  9562. $art_style_ref = '';
  9563. if (!empty($art_style)) {
  9564. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  9565. }
  9566. // 构建内容简介参考
  9567. $intro_ref = '';
  9568. if (!empty($intro)) {
  9569. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  9570. }
  9571. // 构建完整的AI提示词
  9572. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  9573. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  9574. $user_prompt .= $intro_ref;
  9575. $user_prompt .= $art_style_ref;
  9576. $user_prompt .= $reference_content;
  9577. // $user_prompt .= $roles_ref;
  9578. // $user_prompt .= $scenes_ref;
  9579. $system_prompt = "\n\n【强制要求】\n";
  9580. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  9581. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  9582. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  9583. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  9584. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  9585. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  9586. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  9587. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  9588. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  9589. ###分段剧本
  9590. 片段数量:8
  9591. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9592. ##片段1
  9593. 时长:12s
  9594. 分镜1
  9595. 出场角色:刀疤脸
  9596. 场景:边境小镇街道
  9597. 出场道具:酒杯-高脚杯
  9598. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9599. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9600. 配音台词:
  9601. 背景音效:
  9602. 分镜2
  9603. 出场角色:刀疤脸
  9604. 场景:悦来酒馆
  9605. 出场道具:酒杯-高脚杯
  9606. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9607. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9608. 配音台词:
  9609. 背景音效:
  9610. 分镜3
  9611. 出场角色:刀疤脸
  9612. 场景:悦来酒馆
  9613. 出场道具:酒杯-高脚杯
  9614. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9615. 运镜:从中景推向令牌特写。
  9616. 配音台词:
  9617. 背景音效:
  9618. 分镜4
  9619. 出场角色:刀疤脸
  9620. 场景:悦来酒馆
  9621. 出场道具:酒杯-高脚杯
  9622. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9623. 运镜:极速推向酒水溅起的瞬间。
  9624. 配音台词:
  9625. 背景音效:
  9626. 分镜5
  9627. 出场角色:刀疤脸
  9628. 场景:悦来酒馆
  9629. 出场道具:酒杯-高脚杯
  9630. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9631. 运镜:固定机位,利用倾斜构图制造压迫感。
  9632. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9633. 背景音效:";
  9634. // 获取模型配置
  9635. $model = getProp($data, 'model');
  9636. if (!$model) {
  9637. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  9638. }
  9639. // 验证模型是否在可用模型表中
  9640. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9641. $model = 'deepseek-v4-pro';
  9642. }
  9643. // 模型兼容性处理
  9644. $thinkingMode = 'disabled';
  9645. $reasoningEffort = 'high';
  9646. if ($model === 'deepseek-chat') {
  9647. $model = 'deepseek-v4-flash';
  9648. $thinkingMode = 'disabled';
  9649. } elseif ($model === 'deepseek-reasoner') {
  9650. $model = 'deepseek-v4-flash';
  9651. $thinkingMode = 'enabled';
  9652. }
  9653. // 构建消息
  9654. $messages = [
  9655. [
  9656. 'role' => 'system',
  9657. 'content' => $system_prompt
  9658. ],
  9659. [
  9660. 'role' => 'user',
  9661. 'content' => $user_prompt
  9662. ]
  9663. ];
  9664. // dd($messages);
  9665. // 构建请求参数
  9666. $post_data = [
  9667. 'model' => $model,
  9668. 'messages' => $messages,
  9669. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9670. 'frequency_penalty' => 0,
  9671. 'presence_penalty' => 0,
  9672. 'response_format' => ['type' => 'text'],
  9673. 'thinking' => ['type' => $thinkingMode],
  9674. 'stream' => false // 非流式输出
  9675. ];
  9676. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9677. // 调用AI生成新的分段剧本
  9678. try {
  9679. $fullContent = '';
  9680. $usage = [];
  9681. // 根据模型类型选择调用方法
  9682. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9683. // DeepSeek 官方模型使用 DeepSeek API
  9684. $chatResult = $this->chatOnly($post_data);
  9685. } else if (in_array($model, $this->gpt_text_models)) {
  9686. // GPT 模型使用 TokenRouter API
  9687. $chatResult = $this->gpt54ChatOnly($post_data);
  9688. } else {
  9689. // 其他模型使用火山引擎API
  9690. $chatResult = $this->volcEngineChatCompletion($post_data);
  9691. }
  9692. if (is_array($chatResult)) {
  9693. $fullContent = $chatResult['fullContent'] ?? '';
  9694. $usage = $chatResult['usage'] ?? [];
  9695. }
  9696. $generated_content = $fullContent;
  9697. if (empty($generated_content)) {
  9698. Utils::throwError('20003:AI生成内容为空,请重试');
  9699. }
  9700. // 解析生成的内容 - 按片段分割
  9701. $parsed_segments = [];
  9702. // 先在开头添加换行符,确保第1片段也能被正确分割
  9703. $normalizedText = "\n" . $generated_content;
  9704. $parts = preg_split('/\n\s*##/', $normalizedText);
  9705. foreach ($parts as $part) {
  9706. $part = trim($part);
  9707. if (empty($part)) continue;
  9708. // 匹配"片段X"格式
  9709. if (!preg_match('/^片段\d+/', $part)) {
  9710. continue;
  9711. }
  9712. // 分离标题和内容
  9713. $lines = explode("\n", $part, 2);
  9714. $actTitle = trim($lines[0]);
  9715. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  9716. // 解析标题,提取序号
  9717. $actNumber = 0;
  9718. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  9719. $actNumber = intval($segmentTitleMatch[1]);
  9720. } else {
  9721. $actNumber = count($parsed_segments) + 1;
  9722. }
  9723. // 提取时长(仅保留数字)
  9724. $actDuration = 0;
  9725. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  9726. $actDurationStr = trim($actDurationMatch[1]);
  9727. // 提取数字部分(支持整数和小数)
  9728. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  9729. $actDuration = (float)$numMatch[1];
  9730. }
  9731. }
  9732. // 清理act_content:去除时长、旁白音色等非分镜内容行
  9733. // 只保留分镜内容,并确保分镜标记使用【】格式
  9734. $cleaned_content = '';
  9735. $content_lines = explode("\n", $actContent);
  9736. $is_capturing = false; // 标记是否开始捕获分镜内容
  9737. $count = 0;
  9738. foreach ($content_lines as $line) {
  9739. $trimmed_line = trim($line);
  9740. // 跳过时长和旁白音色行
  9741. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  9742. continue;
  9743. }
  9744. // 检测是否是分镜开始
  9745. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  9746. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  9747. $count++;
  9748. $is_capturing = true;
  9749. // 如果没有【】,则添加
  9750. if (!preg_match('/^【/u', $trimmed_line)) {
  9751. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  9752. }
  9753. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  9754. }
  9755. // 如果已经开始捕获,则添加该行
  9756. if ($is_capturing && !empty($trimmed_line)) {
  9757. $cleaned_content .= $trimmed_line."\n";
  9758. }
  9759. }
  9760. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  9761. $parsed_segments[] = [
  9762. 'act_number' => $actNumber,
  9763. 'act_title' => $actTitle,
  9764. 'act_duration' => $actDuration,
  9765. 'act_content' => $cleaned_content,
  9766. ];
  9767. }
  9768. if (empty($parsed_segments)) {
  9769. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  9770. }
  9771. // 收集所有资产名称(角色、场景、道具)
  9772. $product_names = [];
  9773. // 收集角色名称
  9774. if (!empty($roles) && is_array($roles)) {
  9775. foreach ($roles as $role) {
  9776. $role_name = getProp($role, 'role', '');
  9777. if (!empty($role_name)) {
  9778. $product_names[] = $role_name;
  9779. }
  9780. }
  9781. }
  9782. // 收集场景名称
  9783. if (!empty($scenes) && is_array($scenes)) {
  9784. foreach ($scenes as $scene) {
  9785. $scene_name = getProp($scene, 'scene', '');
  9786. if (!empty($scene_name)) {
  9787. $product_names[] = $scene_name;
  9788. }
  9789. }
  9790. }
  9791. // 收集道具名称
  9792. if (!empty($props) && is_array($props)) {
  9793. foreach ($props as $prop) {
  9794. $prop_name = getProp($prop, 'prop', '');
  9795. if (!empty($prop_name)) {
  9796. $product_names[] = $prop_name;
  9797. }
  9798. }
  9799. }
  9800. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  9801. $product_names = array_unique($product_names);
  9802. usort($product_names, function($a, $b) {
  9803. return mb_strlen($b) - mb_strlen($a);
  9804. });
  9805. // 处理每个片段的 act_show_content
  9806. foreach ($parsed_segments as &$segment) {
  9807. $act_content = getProp($segment, 'act_content', '');
  9808. if (empty($act_content)) {
  9809. $segment['act_show_content'] = '';
  9810. continue;
  9811. }
  9812. $processed_content = $act_content;
  9813. // 统一替换所有资产名称为 {资产名} 格式
  9814. // 使用占位符避免嵌套替换问题
  9815. $placeholder_map = [];
  9816. $placeholder_index = 0;
  9817. foreach ($product_names as $product_name) {
  9818. // 转义特殊字符
  9819. $escaped_product = preg_quote($product_name, '/');
  9820. // 检查是否匹配且未被 {} 包裹
  9821. $processed_content = preg_replace_callback(
  9822. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  9823. function($matches) use (&$placeholder_map, &$placeholder_index) {
  9824. // 使用唯一占位符
  9825. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  9826. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  9827. $placeholder_index++;
  9828. return $placeholder;
  9829. },
  9830. $processed_content
  9831. );
  9832. }
  9833. // 将所有占位符替换回实际内容
  9834. foreach ($placeholder_map as $placeholder => $replacement) {
  9835. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  9836. }
  9837. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  9838. $shot_counter = 0;
  9839. $processed_content = preg_replace_callback(
  9840. '/【(?:镜头|分镜)(\d+)】/u',
  9841. function($matches) use (&$shot_counter) {
  9842. $shot_counter++;
  9843. return '【镜头' . $shot_counter . '】';
  9844. },
  9845. $processed_content
  9846. );
  9847. $segment['act_show_content'] = $processed_content;
  9848. }
  9849. unset($segment); // 解除引用
  9850. // 保存到数据库
  9851. $now = date('Y-m-d H:i:s');
  9852. $saved_acts = []; // 用于记录保存后的片段信息
  9853. if ($act_id > 0) {
  9854. // 单个片段模式:更新单条记录
  9855. if (count($parsed_segments) > 0) {
  9856. $new_segment = $parsed_segments[0];
  9857. $update_data = [
  9858. 'act_content' => getProp($new_segment, 'act_content', ''),
  9859. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  9860. 'act_title' => getProp($new_segment, 'act_title', ''),
  9861. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  9862. 'updated_at' => $now,
  9863. ];
  9864. DB::table('mp_episode_segments')
  9865. ->where('id', $act_id)
  9866. ->update($update_data);
  9867. // 获取更新后的记录
  9868. $updated_act = DB::table('mp_episode_segments')
  9869. ->where('id', $act_id)
  9870. ->first();
  9871. if ($updated_act) {
  9872. $saved_acts[] = [
  9873. 'act_id' => $updated_act->id,
  9874. 'act_number' => $updated_act->act_number,
  9875. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  9876. 'act_content' => $updated_act->act_content,
  9877. 'act_show_content' => $updated_act->act_show_content,
  9878. 'video_url' => $updated_act->video_url ?? '',
  9879. 'video_duration' => $updated_act->video_duration ?? 0,
  9880. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  9881. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  9882. ];
  9883. }
  9884. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  9885. }
  9886. } else {
  9887. // 整个剧集模式:删除原有记录并批量保存新记录
  9888. DB::beginTransaction();
  9889. try {
  9890. // 删除原有的所有片段记录
  9891. DB::table('mp_episode_segments')
  9892. ->where('episode_id', $target_episode_id)
  9893. ->delete();
  9894. // 批量插入新的片段记录
  9895. $segments_to_insert = [];
  9896. foreach ($parsed_segments as $index => $segment) {
  9897. $act_number = $index + 1;
  9898. $segments_to_insert[] = [
  9899. 'anime_id' => $target_anime_id,
  9900. 'episode_id' => $target_episode_id,
  9901. 'episode_number' => $target_episode_number,
  9902. 'act_number' => $act_number,
  9903. 'act_title' => getProp($segment, 'act_title', ''),
  9904. 'act_duration' => getProp($segment, 'act_duration', 0),
  9905. 'act_content' => getProp($segment, 'act_content', ''),
  9906. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  9907. 'created_at' => $now,
  9908. 'updated_at' => $now,
  9909. ];
  9910. }
  9911. if (!empty($segments_to_insert)) {
  9912. DB::table('mp_episode_segments')->insert($segments_to_insert);
  9913. }
  9914. DB::commit();
  9915. // 查询保存后的所有片段记录
  9916. $saved_segments = DB::table('mp_episode_segments')
  9917. ->where('episode_id', $target_episode_id)
  9918. ->orderBy('act_number')
  9919. ->get();
  9920. foreach ($saved_segments as $saved_segment) {
  9921. $saved_acts[] = [
  9922. 'act_id' => $saved_segment->id,
  9923. 'act_number' => $saved_segment->act_number,
  9924. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  9925. 'act_content' => $saved_segment->act_content,
  9926. 'act_show_content' => $saved_segment->act_show_content,
  9927. 'video_url' => $saved_segment->video_url ?? '',
  9928. 'video_duration' => $saved_segment->video_duration ?? 0,
  9929. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  9930. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  9931. ];
  9932. }
  9933. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  9934. 'episode_id' => $target_episode_id,
  9935. 'segments_count' => count($segments_to_insert)
  9936. ]);
  9937. } catch (\Exception $e) {
  9938. DB::rollBack();
  9939. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  9940. Utils::throwError('20003:保存失败,请重试');
  9941. }
  9942. }
  9943. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  9944. return [
  9945. 'anime_id' => $target_anime_id,
  9946. 'episode_id' => $target_episode_id,
  9947. 'title' => getProp($episode, 'title', ''),
  9948. 'episode_number' => $target_episode_number,
  9949. 'is_generated' => getProp($episode, 'is_generated', 0),
  9950. 'acts' => $saved_acts,
  9951. ];
  9952. } catch (\Exception $e) {
  9953. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  9954. throw $e;
  9955. }
  9956. }
  9957. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  9958. {
  9959. $episode_arr = [
  9960. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  9961. 'intro' => getProp($script_arr, 'intro'),
  9962. 'art_style' => getProp($script_arr, 'art_style'),
  9963. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  9964. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  9965. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  9966. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  9967. ];
  9968. if (empty($episode_arr['acts'])) {
  9969. $fallback_episode_arr = handleEpisodeContent($fullContent);
  9970. if (!empty($fallback_episode_arr['acts'])) {
  9971. $episode_arr = array_merge($fallback_episode_arr, [
  9972. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  9973. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  9974. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  9975. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  9976. ]);
  9977. }
  9978. }
  9979. // if (!getProp($episode_arr, 'episode_title')) {
  9980. // $episode_title = '';
  9981. // $episodes = getProp($script_arr, 'episodes', []);
  9982. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  9983. // $episode_title = '第1集:' . $episodes[0]['title'];
  9984. // }
  9985. // if (!$episode_title) {
  9986. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  9987. // }
  9988. // $episode_arr['episode_title'] = $episode_title;
  9989. // }
  9990. return $episode_arr;
  9991. }
  9992. private function saveEpisodeVersionData(
  9993. int $anime_id,
  9994. int $episode_number,
  9995. array $episode_arr,
  9996. array $existing_roles,
  9997. array $existing_scenes,
  9998. array $existing_props,
  9999. $current_episode,
  10000. $base_episode,
  10001. bool $is_regenerate_version,
  10002. string $content,
  10003. string $now,
  10004. array $ref_products = []
  10005. ): array {
  10006. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  10007. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  10008. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  10009. // 过滤掉关键字段为空的条目
  10010. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  10011. return !empty($item['role'] ?? null);
  10012. }));
  10013. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  10014. return !empty($item['scene'] ?? null);
  10015. }));
  10016. $merged_props = array_values(array_filter($generated_props, function ($item) {
  10017. return !empty($item['prop'] ?? null);
  10018. }));
  10019. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  10020. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  10021. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  10022. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10023. $ace_mode = getProp($anime, 'ace_mode');
  10024. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  10025. $global_roles = json_decode(getProp($anime, 'roles'), true);
  10026. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  10027. $global_roles = is_array($global_roles) ? $global_roles : [];
  10028. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  10029. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  10030. $art_style_type = getProp($anime, 'art_style_type');
  10031. // 检查并创建 roles 的图片生成任务
  10032. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  10033. // 检查并创建 scenes 的图片生成任务
  10034. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  10035. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  10036. if ($arr && is_array($arr)) {
  10037. $merged_roles = $arr['roles'];
  10038. $merged_scenes = $arr['scenes'];
  10039. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  10040. }
  10041. // 确保数据是数组类型
  10042. if (!is_array($merged_roles)) {
  10043. dLog('deepseek')->error('merged_roles不是数组类型', [
  10044. 'type' => gettype($merged_roles),
  10045. 'value' => $merged_roles
  10046. ]);
  10047. $merged_roles = [];
  10048. }
  10049. if (!is_array($merged_scenes)) {
  10050. dLog('deepseek')->error('merged_scenes不是数组类型', [
  10051. 'type' => gettype($merged_scenes),
  10052. 'value' => $merged_scenes
  10053. ]);
  10054. $merged_scenes = [];
  10055. }
  10056. if (!is_array($merged_props)) {
  10057. dLog('deepseek')->error('merged_props不是数组类型', [
  10058. 'type' => gettype($merged_props),
  10059. 'value' => $merged_props
  10060. ]);
  10061. $merged_props = [];
  10062. }
  10063. // 同步新出现的主体和场景到全局
  10064. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  10065. $role_arr = [];
  10066. foreach ($merged_roles as $item) {
  10067. $role_arr[$item['role']] = $item;
  10068. }
  10069. $version_count = DB::table('mp_anime_episodes')
  10070. ->where('anime_id', $anime_id)
  10071. ->where('episode_number', $episode_number)
  10072. ->count('id');
  10073. $episode = [
  10074. 'anime_id' => $anime_id,
  10075. 'episode_number' => $episode_number,
  10076. 'title' => getProp($episode_arr, 'episode_title'),
  10077. 'content' => $content,
  10078. 'intro' => getProp($episode_arr, 'intro'),
  10079. 'art_style' => getProp($episode_arr, 'art_style'),
  10080. 'roles' => json_encode($merged_roles, 256),
  10081. 'scenes' => json_encode($merged_scenes, 256),
  10082. 'props' => json_encode($merged_props, 256),
  10083. 'generate_status' => '待执行',
  10084. 'generate_at' => $now,
  10085. 'is_default' => 1,
  10086. 'updated_at' => $now,
  10087. ];
  10088. $del_flag = false;
  10089. if ($is_regenerate_version) {
  10090. DB::table('mp_anime_episodes')
  10091. ->where('anime_id', $anime_id)
  10092. ->where('episode_number', $episode_number)
  10093. ->update(['is_default' => 0, 'updated_at' => $now]);
  10094. $episode['sequence'] = $version_count + 1;
  10095. $episode['created_at'] = $now;
  10096. $episode['cpid'] = Site::getCpid();
  10097. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  10098. if (!$episode_id) {
  10099. Utils::throwError('20003:创建剧集版本失败');
  10100. }
  10101. } else {
  10102. $target_episode = $current_episode ?: $base_episode;
  10103. if ($target_episode) {
  10104. $episode_id = getProp($target_episode, 'id');
  10105. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  10106. DB::table('mp_anime_episodes')
  10107. ->where('anime_id', $anime_id)
  10108. ->where('episode_number', $episode_number)
  10109. ->where('id', '<>', $episode_id)
  10110. ->update(['is_default' => 0, 'updated_at' => $now]);
  10111. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  10112. if ($boolen === false) {
  10113. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  10114. Utils::throwError('20003:分集内容保存失败');
  10115. }
  10116. $del_flag = true;
  10117. } else {
  10118. DB::table('mp_anime_episodes')
  10119. ->where('anime_id', $anime_id)
  10120. ->where('episode_number', $episode_number)
  10121. ->update(['is_default' => 0, 'updated_at' => $now]);
  10122. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  10123. $episode['created_at'] = $now;
  10124. $episode['cpid'] = Site::getCpid();
  10125. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  10126. if (!$episode_id) {
  10127. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  10128. Utils::throwError('20003:分集内容保存失败');
  10129. }
  10130. }
  10131. }
  10132. $segments = [];
  10133. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  10134. // 如果是第2集及以后,获取上一集的主体音色数据
  10135. $previous_roles_voice = [];
  10136. if ($episode_number >= 2) {
  10137. $previous_episode = DB::table('mp_anime_episodes')
  10138. ->where('anime_id', $anime_id)
  10139. ->where('episode_number', $episode_number - 1)
  10140. ->where('is_default', 1)
  10141. ->first();
  10142. if ($previous_episode) {
  10143. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  10144. if (is_array($previous_roles)) {
  10145. foreach ($previous_roles as $prev_role) {
  10146. $role_name = getProp($prev_role, 'role');
  10147. if ($role_name) {
  10148. $previous_roles_voice[$role_name] = [
  10149. 'voice_name' => getProp($prev_role, 'voice_name'),
  10150. 'voice_type' => getProp($prev_role, 'voice_type'),
  10151. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  10152. ];
  10153. $voice_prompt = getProp($prev_role, 'voice_prompt');
  10154. if ($voice_prompt) {
  10155. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  10156. }
  10157. }
  10158. }
  10159. }
  10160. }
  10161. }
  10162. // 将继承的音色数据同步到当前集的主体列表
  10163. if (!empty($previous_roles_voice)) {
  10164. foreach ($merged_roles as &$role) {
  10165. $role_name = getProp($role, 'role');
  10166. if ($role_name && isset($previous_roles_voice[$role_name])) {
  10167. // 强制继承上一集的音色数据
  10168. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  10169. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  10170. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  10171. // 如果上一集有 voice_prompt 则继承,否则跳过
  10172. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  10173. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  10174. }
  10175. }
  10176. }
  10177. unset($role); // 解除引用
  10178. // 更新 role_arr 以便后续使用
  10179. $role_arr = [];
  10180. foreach ($merged_roles as $item) {
  10181. $role_arr[$item['role']] = $item;
  10182. }
  10183. }
  10184. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  10185. $emotion_list = array_flip($emotion_list);
  10186. foreach ($acts as $act) {
  10187. $act_segments = getProp($act, 'segments', []);
  10188. if (!is_array($act_segments)) {
  10189. continue;
  10190. }
  10191. if ((int)$ace_mode === 1) {
  10192. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  10193. $merged_parts = [];
  10194. foreach ($act_segments as $seg) {
  10195. $seg_num = getProp($seg, 'segment_number');
  10196. $seg_content = getProp($seg, 'segment_content');
  10197. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  10198. }
  10199. $act_content = implode("\n", $merged_parts);
  10200. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  10201. $segments[] = [
  10202. 'anime_id' => $anime_id,
  10203. 'episode_id' => $episode_id,
  10204. 'episode_number' => $episode_number,
  10205. 'act_number' => getProp($act, 'act_number'),
  10206. 'act_title' => getProp($act, 'act_title'),
  10207. 'act_duration' => getProp($act, 'act_duration'),
  10208. 'act_content' => $act_content,
  10209. 'created_at' => $now,
  10210. 'updated_at' => $now
  10211. ];
  10212. } else {
  10213. foreach ($act_segments as $segment) {
  10214. $voice_actor = getProp($segment, 'voice_actor');
  10215. // 优先从上一集继承音色数据
  10216. $timbre_info = [];
  10217. if (isset($previous_roles_voice[$voice_actor])) {
  10218. // 从上一集继承音色数据
  10219. $timbre_info = $previous_roles_voice[$voice_actor];
  10220. } elseif (isset($role_arr[$voice_actor])) {
  10221. // 使用当前集的主体音色数据
  10222. $timbre_info = $role_arr[$voice_actor];
  10223. }
  10224. $voice_type = getProp($timbre_info, 'voice_type');
  10225. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  10226. if ($timbre_emotion) {
  10227. $timbre_emotion = explode(',', $timbre_emotion);
  10228. } else {
  10229. $timbre_emotion = [];
  10230. }
  10231. $emotion = getProp($segment, 'emotion', '中性');
  10232. if (!in_array($emotion, $timbre_emotion)) {
  10233. $emotion = '中性';
  10234. }
  10235. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  10236. $segments[] = [
  10237. 'anime_id' => $anime_id,
  10238. 'episode_id' => $episode_id,
  10239. 'episode_number' => $episode_number,
  10240. 'act_number' => getProp($act, 'act_number'),
  10241. 'act_title' => getProp($act, 'act_title'),
  10242. 'act_duration' => getProp($act, 'act_duration'),
  10243. 'segment_id' => getProp($segment, 'segment_id'),
  10244. 'segment_number' => getProp($segment, 'segment_number'),
  10245. 'segment_content' => getProp($segment, 'segment_content'),
  10246. 'description' => getProp($segment, 'description'),
  10247. 'composition' => getProp($segment, 'composition'),
  10248. 'camera_movement' => getProp($segment, 'camera_movement'),
  10249. 'voice_actor' => $voice_actor,
  10250. 'dialogue' => getProp($segment, 'dialogue'),
  10251. 'frame_type' => getProp($segment, 'frame_type'),
  10252. 'scene' => getProp($segment, 'scene'),
  10253. 'characters' => getProp($segment, 'characters'),
  10254. 'tail_frame' => getProp($segment, 'tail_frame'),
  10255. 'voice_name' => getProp($timbre_info, 'voice_name'),
  10256. 'voice_type' => $voice_type,
  10257. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  10258. 'emotion' => $emotion,
  10259. 'emotion_type' => $emotion_type,
  10260. 'gender' => getProp($segment, 'gender', '0'),
  10261. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  10262. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  10263. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  10264. 'pitch' => getProp($segment, 'pitch', 0),
  10265. 'created_at' => $now,
  10266. 'updated_at' => $now
  10267. ];
  10268. }
  10269. }
  10270. }
  10271. if ($segments) {
  10272. if ($del_flag) {
  10273. DB::table('mp_episode_segments')
  10274. ->where('anime_id', $anime_id)
  10275. ->where('episode_id', $episode_id)
  10276. ->delete();
  10277. }
  10278. $boolen = DB::table('mp_episode_segments')->insert($segments);
  10279. if (!$boolen) {
  10280. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  10281. Utils::throwError('20003:分镜内容保存失败');
  10282. }
  10283. }
  10284. dLog('deepseek')->info('segments', $segments);
  10285. // ace_mode=1: acts 返回值按合并格式调整
  10286. if ((int)$ace_mode === 1) {
  10287. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  10288. $act_map = [];
  10289. foreach ($table_act_data as $item) {
  10290. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  10291. }
  10292. $restructured_acts = [];
  10293. foreach ($acts as $act) {
  10294. $act_segments = getProp($act, 'segments', []);
  10295. if (!is_array($act_segments)) {
  10296. continue;
  10297. }
  10298. $merged_parts = [];
  10299. foreach ($act_segments as $seg) {
  10300. $seg_num = getProp($seg, 'segment_number');
  10301. $seg_content = getProp($seg, 'segment_content');
  10302. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  10303. }
  10304. $act_content = implode("\n", $merged_parts);
  10305. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  10306. $restructured_acts[] = [
  10307. 'anime_id' => $anime_id,
  10308. 'episode_id' => $episode_id,
  10309. 'episode_number' => $episode_number,
  10310. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  10311. 'act_number' => getProp($act, 'act_number'),
  10312. 'act_title' => getProp($act, 'act_title'),
  10313. 'act_duration' => getProp($act, 'act_duration'),
  10314. 'act_content' => $act_content,
  10315. 'created_at' => $now,
  10316. 'updated_at' => $now,
  10317. ];
  10318. }
  10319. $acts = $restructured_acts;
  10320. }
  10321. $episode['episode_id'] = $episode_id;
  10322. $episode['roles'] = $merged_roles;
  10323. $episode['scenes'] = $merged_scenes;
  10324. $episode['props'] = $merged_props;
  10325. $episode['acts'] = $acts;
  10326. return [
  10327. 'episode' => $episode,
  10328. 'episode_id' => $episode_id,
  10329. 'merged_roles' => $merged_roles,
  10330. 'merged_scenes' => $merged_scenes,
  10331. 'merged_props' => $merged_props,
  10332. ];
  10333. }
  10334. private function buildEpisodeItemContent(array $items, string $nameKey): string
  10335. {
  10336. $content = '';
  10337. foreach ($items as $item) {
  10338. $name = trim((string)getProp($item, $nameKey));
  10339. if ($name === '' || $name === '旁白') {
  10340. continue;
  10341. }
  10342. $description = trim((string)getProp($item, 'description'));
  10343. $content .= $name . ': ' . $description;
  10344. if ($nameKey == 'role') {
  10345. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  10346. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10347. $voice_name = trim(getProp($item, 'voice_name'));
  10348. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  10349. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  10350. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  10351. }else {
  10352. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  10353. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10354. }
  10355. $content .= "\n";
  10356. }
  10357. return trim($content);
  10358. }
  10359. private function getEpisodeChatContent($animeId, $sequence, $content) {
  10360. if ((int)$sequence <= 0) {
  10361. return [];
  10362. }
  10363. $origin_content = '';
  10364. if ($content) {
  10365. $origin_content = '本集剧情内容:'.$content;
  10366. }else {
  10367. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  10368. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  10369. }
  10370. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  10371. // 获取分集信息
  10372. $episode = DB::table('mp_anime_episodes')
  10373. ->where('anime_id', $animeId)
  10374. ->where('episode_number', $sequence)
  10375. ->where('is_default', 1)
  10376. ->first();
  10377. if (!$episode) {
  10378. return [];
  10379. }
  10380. $episode_id = getProp($episode, 'id');
  10381. $episode_number = getProp($episode, 'episode_number');
  10382. $title = getProp($episode, 'title');
  10383. $intro = getProp($episode, 'intro');
  10384. $art_style = getProp($episode, 'art_style');
  10385. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10386. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10387. // 组装纯文本内容
  10388. $content = '';
  10389. // 添加分集标题和梗概
  10390. $content .= "###第{$episode_number}集:{$title}\n\n";
  10391. $content .= "###故事梗概\n";
  10392. $content .= trim($intro) . "\n\n";
  10393. // 添加美术风格
  10394. $content .= "###美术风格\n";
  10395. $content .= trim($art_style) . "\n\n";
  10396. // 添加主体列表
  10397. $content .= "###主体列表\n";
  10398. $pangbai_voice_prompt = "";
  10399. foreach ($roles as $role) {
  10400. $name = getProp($role, 'role');
  10401. $description = getProp($role, 'description');
  10402. $pic_prompt = getProp($role, 'pic_prompt');
  10403. $voice_prompt = getProp($role, 'voice_prompt');
  10404. $voice_name = getProp($role, 'voice_name');
  10405. $content .= "{$name}: {$description}";
  10406. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10407. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  10408. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  10409. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  10410. $content .= "\n";
  10411. }
  10412. $content .= "\n";
  10413. // 添加场景列表
  10414. $content .= "###场景列表\n";
  10415. foreach ($scenes as $scene) {
  10416. $name = getProp($scene, 'scene');
  10417. $description = getProp($scene, 'description');
  10418. $pic_prompt = getProp($scene, 'pic_prompt');
  10419. $content .= "{$name}: {$description}";
  10420. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10421. $content .= "\n";
  10422. }
  10423. $content .= "\n";
  10424. // 获取分镜信息
  10425. $segments = DB::table('mp_episode_segments')
  10426. ->where('anime_id', $animeId)
  10427. ->where('episode_id', $episode_id)
  10428. ->orderBy('segment_number')
  10429. ->get();
  10430. if ($segments && count($segments) > 0) {
  10431. if ((int)$ace_mode === 1) {
  10432. $content .= "###分段剧本\n";
  10433. // 获取片段数量
  10434. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  10435. $content .= "片段数量:{$act_count}\n";
  10436. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  10437. $content .= "\n";
  10438. }else {
  10439. $content .= "###分镜剧本\n";
  10440. }
  10441. // 按幕分组
  10442. $currentAct = null;
  10443. foreach ($segments as $segment) {
  10444. $act_number = getProp($segment, 'act_number');
  10445. $act_title = getProp($segment, 'act_title');
  10446. $act_duration = getProp($segment, 'act_duration');
  10447. $segment_number = getProp($segment, 'segment_number');
  10448. $segment_content = getProp($segment, 'segment_content');
  10449. $scene_description = getProp($segment, 'scene_description');
  10450. $scene_name = getProp($segment, 'scene_name');
  10451. $composition = getProp($segment, 'composition');
  10452. $camera_movement = getProp($segment, 'camera_movement');
  10453. $voice_type = getProp($segment, 'voice_type');
  10454. $characters = getProp($segment, 'characters');
  10455. $dialogue = getProp($segment, 'dialogue');
  10456. $frame_type = getProp($segment, 'frame_type');
  10457. $tail_frame_description = getProp($segment, 'tail_frame_description');
  10458. // 判断是否是全能模式
  10459. if ((int)$ace_mode === 1) { // 全能模式
  10460. // 如果是新的分段,添加分段标题
  10461. if ($act_number !== $currentAct) {
  10462. $currentAct = $act_number;
  10463. $content .= "##{$act_title}\n";
  10464. $content .= "时长:{$act_duration}s\n";
  10465. }
  10466. }else {
  10467. // 如果是新的幕,添加幕标题
  10468. if ($act_number !== $currentAct) {
  10469. $currentAct = $act_number;
  10470. $content .= "##第{$act_number}幕:{$scene_name}\n";
  10471. }
  10472. }
  10473. // 添加分镜信息
  10474. $content .= "分镜{$segment_number}\n";
  10475. $content .= "分镜内容:\n{$segment_content}\n";
  10476. // $content .= "画面描述:{$scene_description}\n";
  10477. // $content .= "场景:{$scene_name}\n";
  10478. // $content .= "构图设计:{$composition}\n";
  10479. // $content .= "运镜调度:{$camera_movement}\n";
  10480. // if (!empty($voice_type)) {
  10481. // $content .= "配音角色:{$voice_type}\n";
  10482. // }
  10483. // if (!empty($characters)) {
  10484. // $content .= "出镜角色:{$characters}\n";
  10485. // }
  10486. // if (!empty($dialogue)) {
  10487. // $content .= "台词内容:\"{$dialogue}\"\n";
  10488. // }
  10489. // $content .= "画面类型:{$frame_type}\n";
  10490. // $content .= "尾帧描述:{$tail_frame_description}\n";
  10491. $content .= "\n";
  10492. }
  10493. }
  10494. $content = trim($content);
  10495. if($content) $content = "上集剧本内容:\n{$content}";
  10496. return [
  10497. [
  10498. 'role' => 'user',
  10499. 'content' => $origin_content
  10500. ],
  10501. [
  10502. 'role' => 'assistant',
  10503. 'content' => $content
  10504. ]
  10505. ];
  10506. }
  10507. private function getEpisodeChatMessages($animeId, $sequence): array
  10508. {
  10509. if ((int)$sequence <= 0) {
  10510. return [];
  10511. }
  10512. return DB::table('mp_anime_records')
  10513. ->where('anime_id', $animeId)
  10514. ->where('sequence', $sequence)
  10515. ->where('episode_id', '>', 0)
  10516. ->select('role', 'content')
  10517. ->orderBy('created_at')
  10518. ->orderBy('id')
  10519. ->get()
  10520. ->map(function ($value) {
  10521. return (array)$value;
  10522. })
  10523. ->toArray();
  10524. }
  10525. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  10526. {
  10527. $existingMap = [];
  10528. foreach ($existingItems as $item) {
  10529. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  10530. if ($itemKey === '') {
  10531. continue;
  10532. }
  10533. $existingMap[$itemKey] = $item;
  10534. }
  10535. if (!$generatedItems) {
  10536. return array_values($existingItems);
  10537. }
  10538. $merged = [];
  10539. foreach ($generatedItems as $item) {
  10540. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  10541. if ($itemKey === '') {
  10542. continue;
  10543. }
  10544. if (isset($existingMap[$itemKey])) {
  10545. if (trim((string)getProp($item, 'description')) === '') {
  10546. $merged[] = $existingMap[$itemKey];
  10547. continue;
  10548. }
  10549. // 检查内容是否发生变化
  10550. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  10551. if (!$isChanged) {
  10552. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  10553. $mergedItem = [
  10554. $nameKey => trim((string)getProp($item, $nameKey)),
  10555. 'description' => trim((string)getProp($item, 'description')),
  10556. ];
  10557. // 如果有 pic_prompt,添加到合并项中
  10558. $picPrompt = getProp($item, 'pic_prompt');
  10559. if (!empty($picPrompt)) {
  10560. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  10561. }
  10562. // 继承现有项的 URL
  10563. $existingUrl = getProp($existingMap[$itemKey], 'url');
  10564. if (!empty($existingUrl)) {
  10565. $mergedItem['url'] = $existingUrl;
  10566. }
  10567. // 继承现有项的 task_id
  10568. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  10569. if (!empty($existingTaskId)) {
  10570. $mergedItem['task_id'] = $existingTaskId;
  10571. }
  10572. // 继承现有项的 task_status
  10573. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  10574. if (!empty($existingTaskStatus)) {
  10575. $mergedItem['task_status'] = $existingTaskStatus;
  10576. }
  10577. // 保留生成项的音色字段
  10578. $voiceName = getProp($item, 'voice_name');
  10579. if (!empty($voiceName)) {
  10580. $mergedItem['voice_name'] = $voiceName;
  10581. }
  10582. $voiceType = getProp($item, 'voice_type');
  10583. if (!empty($voiceType)) {
  10584. $mergedItem['voice_type'] = $voiceType;
  10585. }
  10586. $audioUrl = getProp($item, 'voice_audio_url');
  10587. if (!empty($audioUrl)) {
  10588. $mergedItem['voice_audio_url'] = $audioUrl;
  10589. }
  10590. $merged[] = $mergedItem;
  10591. } else {
  10592. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  10593. $mergedItem = [
  10594. $nameKey => trim((string)getProp($item, $nameKey)),
  10595. 'description' => trim((string)getProp($item, 'description')),
  10596. ];
  10597. // 如果有 pic_prompt,添加到合并项中
  10598. $picPrompt = getProp($item, 'pic_prompt');
  10599. if (!empty($picPrompt)) {
  10600. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  10601. }
  10602. // 保留生成项的音色字段
  10603. $voiceName = getProp($item, 'voice_name');
  10604. if (!empty($voiceName)) {
  10605. $mergedItem['voice_name'] = $voiceName;
  10606. }
  10607. $voiceType = getProp($item, 'voice_type');
  10608. if (!empty($voiceType)) {
  10609. $mergedItem['voice_type'] = $voiceType;
  10610. }
  10611. $audioUrl = getProp($item, 'voice_audio_url');
  10612. if (!empty($audioUrl)) {
  10613. $mergedItem['voice_audio_url'] = $audioUrl;
  10614. }
  10615. // 不继承 URL、task_id 和 task_status(重置状态)
  10616. $merged[] = $mergedItem;
  10617. }
  10618. } else {
  10619. // 新增项,保留生成项的所有字段
  10620. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  10621. }
  10622. }
  10623. return $merged ?: array_values($existingItems);
  10624. }
  10625. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  10626. {
  10627. $resetItem = [
  10628. $nameKey => trim((string)getProp($item, $nameKey)),
  10629. 'description' => trim((string)getProp($item, 'description')),
  10630. ];
  10631. // 保留指定的字段
  10632. foreach ($preserveFields as $field) {
  10633. $value = getProp($item, $field);
  10634. if (!empty($value)) {
  10635. $resetItem[$field] = $value;
  10636. }
  10637. }
  10638. return $resetItem;
  10639. }
  10640. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  10641. {
  10642. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  10643. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  10644. if ($existingKey !== $generatedKey) {
  10645. return true;
  10646. }
  10647. // 比较 description 是否变化
  10648. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  10649. return true;
  10650. }
  10651. // 比较 pic_prompt 是否变化
  10652. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  10653. }
  10654. private function normalizeEpisodeResourceKey($value): string
  10655. {
  10656. $value = trim((string)$value);
  10657. if ($value === '') {
  10658. return '';
  10659. }
  10660. return strtolower((string)preg_replace('/\s+/u', '', $value));
  10661. }
  10662. // 生成全局角色图片
  10663. private function batchSetGlobalRoleImg($data, $is_force=false) {
  10664. $anime_id = getProp($data, 'anime_id');
  10665. if (!$anime_id) Utils::throwError('1002:请选择对话');
  10666. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10667. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10668. $art_style = getProp($anime, 'art_style');
  10669. $update_flag = false;
  10670. foreach ($roles as &$role) {
  10671. $role_name = getProp($role, 'role');
  10672. if ($role_name == '旁白') continue;
  10673. // 优先使用 pic_prompt,如果没有则使用 description
  10674. $pic_prompt = getProp($role, 'pic_prompt');
  10675. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  10676. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  10677. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  10678. // 参考图地址
  10679. $ref_img_url = getProp($role, 'url');
  10680. if (!$is_force && $ref_img_url) continue;
  10681. $update_flag = true;
  10682. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  10683. try {
  10684. $params = [
  10685. 'prompt' => $description,
  10686. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  10687. 'ref_img_urls' => []
  10688. ];
  10689. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10690. $task_id = $task->id;
  10691. if (!$task_id) {
  10692. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  10693. }
  10694. $role['task_id'] = $task_id;
  10695. $role['task_status'] = 'processing';
  10696. } catch (\Exception $e) {
  10697. Utils::throwError("20003:" . $e->getMessage());
  10698. }
  10699. }
  10700. if (!$update_flag) return true;
  10701. // 保存角色信息
  10702. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  10703. 'roles' => json_encode($roles, 256),
  10704. 'generate_status' => '执行中',
  10705. 'generate_at' => date('Y-m-d H:i:s'),
  10706. 'updated_at' => date('Y-m-d H:i:s')
  10707. ]);
  10708. if (!$boolen) {
  10709. Utils::throwError('20003:保存角色信息失败');
  10710. }
  10711. return $boolen;
  10712. }
  10713. // 生成全局场景图片
  10714. private function batchSetGlobalSceneImg($data, $is_force=false) {
  10715. $anime_id = getProp($data, 'anime_id');
  10716. if (!$anime_id) Utils::throwError('1002:请选择对话');
  10717. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10718. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10719. $art_style = getProp($anime, 'art_style');
  10720. $update_flag = false;
  10721. foreach ($scenes as &$scene) {
  10722. $scene_name = getProp($scene, 'scene');
  10723. // 优先使用 pic_prompt,如果没有则使用 description
  10724. $pic_prompt = getProp($scene, 'pic_prompt');
  10725. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  10726. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  10727. // 参考图地址
  10728. $ref_img_url = getProp($scene, 'url');
  10729. if (!$is_force && $ref_img_url) continue;
  10730. $update_flag = true;
  10731. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  10732. try {
  10733. $params = [
  10734. 'prompt' => $description,
  10735. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  10736. 'ref_img_urls' => []
  10737. ];
  10738. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10739. $task_id = $task->id;
  10740. if (!$task_id) {
  10741. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  10742. }
  10743. $scene['task_id'] = $task_id;
  10744. $scene['task_status'] = 'processing';
  10745. } catch (\Exception $e) {
  10746. Utils::throwError("20003:" . $e->getMessage());
  10747. }
  10748. }
  10749. if (!$update_flag) return true;
  10750. // 保存角色信息
  10751. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  10752. 'scenes' => json_encode($scenes, 256),
  10753. 'generate_status' => '执行中',
  10754. 'generate_at' => date('Y-m-d H:i:s'),
  10755. 'updated_at' => date('Y-m-d H:i:s')
  10756. ]);
  10757. if (!$boolen) {
  10758. Utils::throwError('20003:保存角色信息失败');
  10759. }
  10760. return $boolen;
  10761. }
  10762. // 生成分镜主体、场景和道具图片
  10763. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  10764. $character_prefix = '';
  10765. $scene_prefix = '';
  10766. $prop_prefix = '';
  10767. if ($art_style_type) {
  10768. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  10769. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  10770. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  10771. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  10772. }
  10773. $update_flag = false;
  10774. // 获取上一集的roles、scenes和props数据
  10775. $prev_roles = [];
  10776. $prev_scenes = [];
  10777. $prev_props = [];
  10778. if ($episode_number > 1) {
  10779. $prev_episode = DB::table('mp_anime_episodes')
  10780. ->where('anime_id', $anime_id)
  10781. ->where('episode_number', $episode_number - 1)
  10782. ->where('is_default', 1)
  10783. ->first();
  10784. if ($prev_episode) {
  10785. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  10786. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  10787. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  10788. dLog('deepseek')->info("获取上一集数据成功", [
  10789. 'anime_id' => $anime_id,
  10790. 'prev_episode_number' => $episode_number - 1,
  10791. 'prev_roles_count' => count($prev_roles),
  10792. 'prev_scenes_count' => count($prev_scenes),
  10793. 'prev_props_count' => count($prev_props)
  10794. ]);
  10795. }
  10796. }
  10797. // 处理角色图片生成
  10798. foreach ($roles as &$role) {
  10799. $role_name = getProp($role, 'role');
  10800. if ($role_name == '旁白') continue;
  10801. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  10802. if (isset($ref_products[$role_name])) {
  10803. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  10804. if ($role['url']) continue;
  10805. }
  10806. $role_description = getProp($role, 'description');
  10807. $role_pic_prompt = getProp($role, 'pic_prompt');
  10808. $role_url = getProp($role, 'url');
  10809. // 检查是否可以从上一集继承
  10810. $inherited = false;
  10811. if (!$is_force && !empty($prev_roles)) {
  10812. foreach ($prev_roles as $prev_role) {
  10813. $prev_role_name = getProp($prev_role, 'role');
  10814. $prev_description = getProp($prev_role, 'description');
  10815. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  10816. $prev_url = getProp($prev_role, 'url');
  10817. $prev_task_id = getProp($prev_role, 'task_id');
  10818. $prev_task_status = getProp($prev_role, 'task_status');
  10819. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  10820. if ($role_name == $prev_role_name
  10821. && $role_description == $prev_description
  10822. && $role_pic_prompt == $prev_pic_prompt
  10823. && !empty($prev_url)) {
  10824. $role['task_id'] = $prev_task_id;
  10825. $role['task_status'] = $prev_task_status;
  10826. $role['url'] = $prev_url;
  10827. $inherited = true;
  10828. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  10829. 'anime_id' => $anime_id,
  10830. 'episode_number' => $episode_number,
  10831. 'task_id' => $prev_task_id,
  10832. 'url' => $prev_url
  10833. ]);
  10834. break;
  10835. }
  10836. }
  10837. }
  10838. // 如果已继承或已有url,跳过生成
  10839. if ($inherited || (!$is_force && $role_url)) {
  10840. continue;
  10841. }
  10842. // 优先使用 pic_prompt,如果没有则使用 description
  10843. $pic_prompt = getProp($role, 'pic_prompt');
  10844. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  10845. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10846. $update_flag = true;
  10847. // 调用AIImageGenerationService的生成图片任务接口
  10848. try {
  10849. $params = [
  10850. 'prompt' => $description,
  10851. 'ref_img_urls' => []
  10852. ];
  10853. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10854. $task_id = $task->id;
  10855. if (!$task_id) {
  10856. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  10857. continue; // 不中断,继续处理其他角色
  10858. }
  10859. $role['task_id'] = $task_id;
  10860. $role['task_status'] = 'processing';
  10861. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  10862. 'anime_id' => $anime_id,
  10863. 'episode_number' => $episode_number,
  10864. 'task_id' => $task_id
  10865. ]);
  10866. } catch (\Exception $e) {
  10867. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  10868. // 不抛出异常,继续处理其他角色
  10869. }
  10870. }
  10871. // 处理场景图片生成
  10872. foreach ($scenes as &$scene) {
  10873. $scene_name = getProp($scene, 'scene');
  10874. $scene_description = getProp($scene, 'description');
  10875. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  10876. $scene_url = getProp($scene, 'url');
  10877. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  10878. if (isset($ref_products[$scene_name])) {
  10879. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  10880. if ($scene['url']) continue;
  10881. }
  10882. // 检查是否可以从上一集继承
  10883. $inherited = false;
  10884. if (!$is_force && !empty($prev_scenes)) {
  10885. foreach ($prev_scenes as $prev_scene) {
  10886. $prev_scene_name = getProp($prev_scene, 'scene');
  10887. $prev_description = getProp($prev_scene, 'description');
  10888. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  10889. $prev_url = getProp($prev_scene, 'url');
  10890. $prev_task_id = getProp($prev_scene, 'task_id');
  10891. $prev_task_status = getProp($prev_scene, 'task_status');
  10892. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  10893. if ($scene_name == $prev_scene_name
  10894. && $scene_description == $prev_description
  10895. && $scene_pic_prompt == $prev_pic_prompt
  10896. && !empty($prev_url)) {
  10897. $scene['task_id'] = $prev_task_id;
  10898. $scene['task_status'] = $prev_task_status;
  10899. $scene['url'] = $prev_url;
  10900. $inherited = true;
  10901. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  10902. 'anime_id' => $anime_id,
  10903. 'episode_number' => $episode_number,
  10904. 'task_id' => $prev_task_id,
  10905. 'url' => $prev_url
  10906. ]);
  10907. break;
  10908. }
  10909. }
  10910. }
  10911. // 如果已继承或已有url,跳过生成
  10912. if ($inherited || (!$is_force && $scene_url)) {
  10913. continue;
  10914. }
  10915. // 优先使用 pic_prompt,如果没有则使用 description
  10916. $pic_prompt = getProp($scene, 'pic_prompt');
  10917. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  10918. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10919. $update_flag = true;
  10920. // 调用AIImageGenerationService的生成图片任务接口
  10921. try {
  10922. $params = [
  10923. 'prompt' => $description,
  10924. 'ref_img_urls' => []
  10925. ];
  10926. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10927. $task_id = $task->id;
  10928. if (!$task_id) {
  10929. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  10930. continue; // 不中断,继续处理其他场景
  10931. }
  10932. $scene['task_id'] = $task_id;
  10933. $scene['task_status'] = 'processing';
  10934. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  10935. 'anime_id' => $anime_id,
  10936. 'episode_number' => $episode_number,
  10937. 'task_id' => $task_id
  10938. ]);
  10939. } catch (\Exception $e) {
  10940. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  10941. // 不抛出异常,继续处理其他场景
  10942. }
  10943. }
  10944. // 处理道具图片生成(逻辑与场景一致)
  10945. foreach ($props as &$prop) {
  10946. $prop_name = getProp($prop, 'prop');
  10947. $prop_description = getProp($prop, 'description');
  10948. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  10949. $prop_url = getProp($prop, 'url');
  10950. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  10951. if (isset($ref_products[$prop_name])) {
  10952. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  10953. if ($prop['url']) continue;
  10954. }
  10955. // 检查是否可以从上一集继承
  10956. $inherited = false;
  10957. if (!$is_force && !empty($prev_props)) {
  10958. foreach ($prev_props as $prev_prop) {
  10959. $prev_prop_name = getProp($prev_prop, 'prop');
  10960. $prev_description = getProp($prev_prop, 'description');
  10961. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  10962. $prev_url = getProp($prev_prop, 'url');
  10963. $prev_task_id = getProp($prev_prop, 'task_id');
  10964. $prev_task_status = getProp($prev_prop, 'task_status');
  10965. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  10966. if ($prop_name == $prev_prop_name
  10967. && $prop_description == $prev_description
  10968. && $prop_pic_prompt == $prev_pic_prompt
  10969. && !empty($prev_url)) {
  10970. $prop['task_id'] = $prev_task_id;
  10971. $prop['task_status'] = $prev_task_status;
  10972. $prop['url'] = $prev_url;
  10973. $inherited = true;
  10974. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  10975. 'anime_id' => $anime_id,
  10976. 'episode_number' => $episode_number,
  10977. 'task_id' => $prev_task_id,
  10978. 'url' => $prev_url
  10979. ]);
  10980. break;
  10981. }
  10982. }
  10983. }
  10984. // 如果已继承或已有url,跳过生成
  10985. if ($inherited || (!$is_force && $prop_url)) {
  10986. continue;
  10987. }
  10988. // 优先使用 pic_prompt,如果没有则使用 description
  10989. $pic_prompt = getProp($prop, 'pic_prompt');
  10990. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  10991. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10992. $update_flag = true;
  10993. // 调用AIImageGenerationService的生成图片任务接口
  10994. try {
  10995. $params = [
  10996. 'prompt' => $description,
  10997. 'ref_img_urls' => []
  10998. ];
  10999. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11000. $task_id = $task->id;
  11001. if (!$task_id) {
  11002. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  11003. continue; // 不中断,继续处理其他道具
  11004. }
  11005. $prop['task_id'] = $task_id;
  11006. $prop['task_status'] = 'processing';
  11007. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  11008. 'anime_id' => $anime_id,
  11009. 'episode_number' => $episode_number,
  11010. 'task_id' => $task_id
  11011. ]);
  11012. } catch (\Exception $e) {
  11013. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  11014. // 不抛出异常,继续处理其他道具
  11015. }
  11016. }
  11017. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  11018. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  11019. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  11020. // // 保存剧集的角色和场景信息
  11021. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  11022. // 'roles' => json_encode($roles, 256),
  11023. // 'scenes' => json_encode($scenes, 256),
  11024. // 'generate_status' => '执行中',
  11025. // 'generate_at' => date('Y-m-d H:i:s'),
  11026. // 'updated_at' => date('Y-m-d H:i:s')
  11027. // ]);
  11028. // if (!$boolen) {
  11029. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  11030. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  11031. // }
  11032. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  11033. // 'episode_id' => $episode_id,
  11034. 'roles_count' => count($roles),
  11035. 'scenes_count' => count($scenes),
  11036. 'props_count' => count($props)
  11037. ]);
  11038. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  11039. }
  11040. /**
  11041. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  11042. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  11043. *
  11044. * @param int $anime_id 动漫对话ID
  11045. * @param array $episode_roles 剧集角色数据
  11046. * @param array $episode_scenes 剧集场景数据
  11047. * @param array $episode_props 剧集道具数据
  11048. * @return bool
  11049. */
  11050. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  11051. // 获取全局数据
  11052. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11053. if (!$anime) {
  11054. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  11055. return false;
  11056. }
  11057. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11058. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11059. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  11060. $roles_added = false;
  11061. $roles_updated = false;
  11062. $scenes_added = false;
  11063. $props_added = false;
  11064. // 处理角色同步
  11065. foreach ($episode_roles as $episode_role) {
  11066. $episode_role_name = getProp($episode_role, 'role');
  11067. $episode_description = getProp($episode_role, 'description');
  11068. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  11069. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  11070. // 跳过旁白
  11071. if ($episode_role_name == '旁白') {
  11072. continue;
  11073. }
  11074. // 检查全局中是否已存在相同的角色
  11075. $exists = false;
  11076. $global_role_index = -1;
  11077. foreach ($global_roles as $index => $global_role) {
  11078. $global_role_name = getProp($global_role, 'role');
  11079. $global_description = getProp($global_role, 'description');
  11080. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  11081. // 如果role、description、pic_prompt三项都一致,则认为已存在
  11082. if ($episode_role_name == $global_role_name
  11083. && $episode_description == $global_description
  11084. && $episode_pic_prompt == $global_pic_prompt) {
  11085. $exists = true;
  11086. $global_role_index = $index;
  11087. break;
  11088. }
  11089. }
  11090. // 如果不存在,则添加到全局
  11091. if (!$exists) {
  11092. $global_roles[] = $episode_role;
  11093. $roles_added = true;
  11094. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  11095. 'anime_id' => $anime_id,
  11096. 'role' => $episode_role_name
  11097. ]);
  11098. } else {
  11099. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  11100. if (!empty($episode_voice_prompt)) {
  11101. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  11102. // 如果全局没有voice_prompt或与剧集不一致,则更新
  11103. if ($global_voice_prompt !== $episode_voice_prompt) {
  11104. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  11105. $roles_updated = true;
  11106. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  11107. 'anime_id' => $anime_id,
  11108. 'role' => $episode_role_name,
  11109. 'voice_prompt' => $episode_voice_prompt
  11110. ]);
  11111. }
  11112. }
  11113. }
  11114. }
  11115. // 处理场景同步
  11116. foreach ($episode_scenes as $episode_scene) {
  11117. $episode_scene_name = getProp($episode_scene, 'scene');
  11118. $episode_description = getProp($episode_scene, 'description');
  11119. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  11120. // 检查全局中是否已存在相同的场景
  11121. $exists = false;
  11122. foreach ($global_scenes as $global_scene) {
  11123. $global_scene_name = getProp($global_scene, 'scene');
  11124. $global_description = getProp($global_scene, 'description');
  11125. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  11126. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  11127. if ($episode_scene_name == $global_scene_name
  11128. && $episode_description == $global_description
  11129. && $episode_pic_prompt == $global_pic_prompt) {
  11130. $exists = true;
  11131. break;
  11132. }
  11133. }
  11134. // 如果不存在,则添加到全局
  11135. if (!$exists) {
  11136. $global_scenes[] = $episode_scene;
  11137. $scenes_added = true;
  11138. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  11139. 'anime_id' => $anime_id,
  11140. 'scene' => $episode_scene_name
  11141. ]);
  11142. }
  11143. }
  11144. // 处理道具同步(逻辑与场景一致)
  11145. foreach ($episode_props as $episode_prop) {
  11146. $episode_prop_name = getProp($episode_prop, 'prop');
  11147. $episode_description = getProp($episode_prop, 'description');
  11148. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  11149. // 检查全局中是否已存在相同的道具
  11150. $exists = false;
  11151. foreach ($global_props as $global_prop) {
  11152. $global_prop_name = getProp($global_prop, 'prop');
  11153. $global_description = getProp($global_prop, 'description');
  11154. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  11155. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  11156. if ($episode_prop_name == $global_prop_name
  11157. && $episode_description == $global_description
  11158. && $episode_pic_prompt == $global_pic_prompt) {
  11159. $exists = true;
  11160. break;
  11161. }
  11162. }
  11163. // 如果不存在,则添加到全局
  11164. if (!$exists) {
  11165. $global_props[] = $episode_prop;
  11166. $props_added = true;
  11167. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  11168. 'anime_id' => $anime_id,
  11169. 'prop' => $episode_prop_name
  11170. ]);
  11171. }
  11172. }
  11173. // 如果有新增或更新,则更新全局数据
  11174. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  11175. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  11176. if ($roles_added || $roles_updated) {
  11177. $update_data['roles'] = json_encode($global_roles, 256);
  11178. }
  11179. if ($scenes_added) {
  11180. $update_data['scenes'] = json_encode($global_scenes, 256);
  11181. }
  11182. if ($props_added) {
  11183. $update_data['props'] = json_encode($global_props, 256);
  11184. }
  11185. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  11186. dLog('deepseek')->info('剧集数据同步到全局完成', [
  11187. 'anime_id' => $anime_id,
  11188. 'roles_added' => $roles_added,
  11189. 'roles_updated' => $roles_updated,
  11190. 'scenes_added' => $scenes_added,
  11191. 'props_added' => $props_added,
  11192. 'global_roles_count' => count($global_roles),
  11193. 'global_scenes_count' => count($global_scenes),
  11194. 'global_props_count' => count($global_props)
  11195. ]);
  11196. }
  11197. return true;
  11198. }
  11199. /**
  11200. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  11201. *
  11202. * @param int $anime_id 动漫对话ID
  11203. * @param int $episode_id 分集ID
  11204. * @return bool
  11205. */
  11206. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  11207. // 获取全局角色和场景数据
  11208. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11209. if (!$anime) {
  11210. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  11211. return false;
  11212. }
  11213. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11214. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11215. // 获取指定的分集
  11216. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  11217. if (!$episode) {
  11218. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  11219. return false;
  11220. }
  11221. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  11222. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  11223. $roles_updated = false;
  11224. $scenes_updated = false;
  11225. // 继承角色的task_id、task_status和url
  11226. foreach ($episode_roles as &$episode_role) {
  11227. $episode_role_name = getProp($episode_role, 'role');
  11228. $episode_description = getProp($episode_role, 'description');
  11229. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  11230. $episode_url = getProp($episode_role, 'url');
  11231. // 跳过旁白角色
  11232. if ($episode_role_name == '旁白') {
  11233. continue;
  11234. }
  11235. // 如果剧集中已有URL,跳过
  11236. if (!empty($episode_url)) {
  11237. continue;
  11238. }
  11239. // 遍历全局角色数据,查找匹配的角色
  11240. foreach ($global_roles as $global_role) {
  11241. $global_role_name = getProp($global_role, 'role');
  11242. $global_description = getProp($global_role, 'description');
  11243. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  11244. $global_url = getProp($global_role, 'url');
  11245. $global_task_id = getProp($global_role, 'task_id');
  11246. $global_task_status = getProp($global_role, 'task_status');
  11247. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  11248. if ($episode_role_name == $global_role_name
  11249. && $episode_description == $global_description
  11250. && $episode_pic_prompt == $global_pic_prompt) {
  11251. // 继承 task_id、task_status 和 url
  11252. if (!empty($global_task_id)) {
  11253. $episode_role['task_id'] = $global_task_id;
  11254. $episode_role['task_status'] = $global_task_status;
  11255. $roles_updated = true;
  11256. dLog('deepseek')->info('剧集角色继承全局task_id', [
  11257. 'episode_id' => $episode_id,
  11258. 'role' => $episode_role_name,
  11259. 'task_id' => $global_task_id,
  11260. 'task_status' => $global_task_status
  11261. ]);
  11262. }
  11263. if (!empty($global_url)) {
  11264. $episode_role['url'] = $global_url;
  11265. $roles_updated = true;
  11266. dLog('deepseek')->info('剧集角色继承全局url', [
  11267. 'episode_id' => $episode_id,
  11268. 'role' => $episode_role_name,
  11269. 'url' => $global_url
  11270. ]);
  11271. }
  11272. break;
  11273. }
  11274. }
  11275. }
  11276. // 继承场景的task_id、task_status和url
  11277. foreach ($episode_scenes as &$episode_scene) {
  11278. $episode_scene_name = getProp($episode_scene, 'scene');
  11279. $episode_description = getProp($episode_scene, 'description');
  11280. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  11281. $episode_url = getProp($episode_scene, 'url');
  11282. // 如果剧集中已有URL,跳过
  11283. if (!empty($episode_url)) {
  11284. continue;
  11285. }
  11286. // 遍历全局场景数据,查找匹配的场景
  11287. foreach ($global_scenes as $global_scene) {
  11288. $global_scene_name = getProp($global_scene, 'scene');
  11289. $global_description = getProp($global_scene, 'description');
  11290. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  11291. $global_url = getProp($global_scene, 'url');
  11292. $global_task_id = getProp($global_scene, 'task_id');
  11293. $global_task_status = getProp($global_scene, 'task_status');
  11294. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  11295. if ($episode_scene_name == $global_scene_name
  11296. && $episode_description == $global_description
  11297. && $episode_pic_prompt == $global_pic_prompt) {
  11298. // 继承 task_id、task_status 和 url
  11299. if (!empty($global_task_id)) {
  11300. $episode_scene['task_id'] = $global_task_id;
  11301. $episode_scene['task_status'] = $global_task_status;
  11302. $scenes_updated = true;
  11303. dLog('deepseek')->info('剧集场景继承全局task_id', [
  11304. 'episode_id' => $episode_id,
  11305. 'scene' => $episode_scene_name,
  11306. 'task_id' => $global_task_id,
  11307. 'task_status' => $global_task_status
  11308. ]);
  11309. }
  11310. if (!empty($global_url)) {
  11311. $episode_scene['url'] = $global_url;
  11312. $scenes_updated = true;
  11313. dLog('deepseek')->info('剧集场景继承全局url', [
  11314. 'episode_id' => $episode_id,
  11315. 'scene' => $episode_scene_name,
  11316. 'url' => $global_url
  11317. ]);
  11318. }
  11319. break;
  11320. }
  11321. }
  11322. }
  11323. // 如果有更新,则保存到数据库
  11324. if ($roles_updated || $scenes_updated) {
  11325. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  11326. if ($roles_updated) {
  11327. $update_data['roles'] = json_encode($episode_roles, 256);
  11328. }
  11329. if ($scenes_updated) {
  11330. $update_data['scenes'] = json_encode($episode_scenes, 256);
  11331. }
  11332. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  11333. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  11334. 'episode_id' => $episode_id,
  11335. 'roles_updated' => $roles_updated,
  11336. 'scenes_updated' => $scenes_updated
  11337. ]);
  11338. }
  11339. return true;
  11340. }
  11341. public function chatChangeImg($data) {
  11342. $segment = getProp($data, 'segment');
  11343. $segment_content = getProp($segment, 'segment_content');
  11344. $prompt = getProp($data, 'prompt');
  11345. $ref_img = getProp($data, 'ref_img');
  11346. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  11347. // 处理文本模型
  11348. $model = getProp($data, 'model');
  11349. if (!$model) {
  11350. // 用户没有输入,从anime表获取
  11351. $segment_id = getProp($segment, 'segment_id');
  11352. if ($segment_id) {
  11353. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  11354. if ($episode_id) {
  11355. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  11356. if ($anime_id) {
  11357. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  11358. }
  11359. }
  11360. }
  11361. if (!$model) {
  11362. // anime表也没有,使用默认值
  11363. $model = 'doubao-seed-2-0-mini-260215';
  11364. }
  11365. }
  11366. // 验证模型是否在可用模型表中
  11367. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  11368. $model = 'doubao-seed-2-0-mini-260215';
  11369. }
  11370. $messages[] =
  11371. [
  11372. 'role' => 'user',
  11373. 'content' => $question
  11374. ];
  11375. $post_data = [
  11376. 'model' => $model,
  11377. 'messages' => $messages,
  11378. // 'max_tokens' => 8192,
  11379. 'temperature' => 0.7,
  11380. 'frequency_penalty' => 0,
  11381. 'presence_penalty' => 0,
  11382. 'response_format' => ['type' => 'text'],
  11383. 'stream' => false // 是否启用流式输出
  11384. ];
  11385. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11386. // DeepSeek 官方模型使用 DeepSeek API
  11387. $chatResult = $this->chatOnly($post_data);
  11388. } else if (in_array($model, $this->gpt_text_models)) {
  11389. // GPT-5.4 模型使用 TokenRouter API
  11390. $chatResult = $this->gpt54ChatOnly($post_data);
  11391. } else {
  11392. // 其他模型使用火山引擎API
  11393. $chatResult = $this->volcEngineChatCompletion($post_data);
  11394. }
  11395. if (is_array($chatResult)) {
  11396. extract($chatResult);
  11397. }else {
  11398. Utils::throwError('20003: 接口调用失败!');
  11399. }
  11400. return [
  11401. 'type' => 'done',
  11402. // 'episode' => $episode,
  11403. 'answer' => $fullContent,
  11404. 'reasoning' => $fullReasoningContent,
  11405. 'usage' => $usage
  11406. ];
  11407. }
  11408. // 仅调用deepseek对话接口
  11409. private function chatOnly($post_data) {
  11410. $post_data['max_tokens'] = 300000;
  11411. $client = new Client(['timeout' => 1800, 'verify' => false]);
  11412. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  11413. $response = $result->getBody()->getContents();
  11414. $response_arr = json_decode($response, true);
  11415. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  11416. $fullContent = '';
  11417. $fullReasoningContent = [];
  11418. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  11419. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  11420. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  11421. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  11422. }
  11423. return [
  11424. 'fullContent' => $fullContent,
  11425. 'fullReasoningContent' => $fullReasoningContent,
  11426. 'usage' => $usage
  11427. ];
  11428. }
  11429. // 仅调用 GPT-5.4 对话接口(非流式)
  11430. private function gpt54ChatOnly($post_data) {
  11431. $apiKey = env('GPT_54_API_KEY');
  11432. if (empty($apiKey)) {
  11433. Utils::throwError('20003:GPT-5.4 API Key未配置');
  11434. }
  11435. // 先探活,服务不可用时自动重试
  11436. $this->ensureGptServiceAvailable();
  11437. $client = new Client(['timeout' => 1800, 'verify' => false]);
  11438. $headers = [
  11439. 'Authorization' => 'Bearer ' . $apiKey,
  11440. 'Content-Type' => 'application/json'
  11441. ];
  11442. // 移除 thinking 参数,GPT-5.4 不支持
  11443. if (isset($post_data['thinking'])) {
  11444. unset($post_data['thinking']);
  11445. }
  11446. if (isset($post_data['reasoning_effort'])) {
  11447. unset($post_data['reasoning_effort']);
  11448. }
  11449. $post_data['max_completion_tokens'] = 100000;
  11450. // 确保 stream 为 false
  11451. $post_data['stream'] = false;
  11452. $maxRetries = $this->gptRetryTimes();
  11453. $interval = $this->gptRetryInterval();
  11454. $attempt = 0;
  11455. while (true) {
  11456. try {
  11457. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  11458. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  11459. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  11460. 'json' => $post_data,
  11461. 'headers' => $headers
  11462. ]);
  11463. $response = $result->getBody()->getContents();
  11464. $response_arr = json_decode($response, true);
  11465. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  11466. $fullContent = '';
  11467. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  11468. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  11469. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  11470. }
  11471. return [
  11472. 'fullContent' => $fullContent,
  11473. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  11474. 'usage' => $usage
  11475. ];
  11476. } catch (\Exception $e) {
  11477. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  11478. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  11479. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  11480. throw $e;
  11481. }
  11482. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  11483. 'retry' => $attempt + 1,
  11484. 'max_retries' => $maxRetries,
  11485. 'error' => $e->getMessage()
  11486. ]);
  11487. sleep($interval);
  11488. $attempt++;
  11489. }
  11490. }
  11491. }
  11492. private function splitContent($content) {
  11493. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  11494. $chapters = [];
  11495. // 匹配章节标题格式:
  11496. // 1. 标题可能独占一行,也可能在正文末尾或中间
  11497. // 2. 格式支持:
  11498. // - **第一集**
  11499. // - 第一集:
  11500. // - ###第1章 重生
  11501. // - ##第2章 相救
  11502. // - 第三章 共处一室
  11503. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  11504. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  11505. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  11506. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  11507. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  11508. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  11509. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  11510. // 先在每个标题前插入换行符(如果前面不是换行的话)
  11511. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  11512. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  11513. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  11514. // 用正则找出所有章节标题的位置
  11515. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  11516. $titleCount = count($matches[0]);
  11517. for ($i = 0; $i < $titleCount; $i++) {
  11518. // 获取当前章节标题
  11519. $titleLine = trim($matches[0][$i][0]);
  11520. // 去除标题开头的特殊符号
  11521. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  11522. // 去除标题结尾的冒号和特殊符号
  11523. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  11524. $cleanTitle = trim($cleanTitle);
  11525. // 获取当前标题的结束位置
  11526. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  11527. // 获取下一个章节标题的开始位置(如果存在)
  11528. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  11529. // 提取章节内容(从标题结束到下一个标题开始)
  11530. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  11531. // 清理内容:去除前后空白和分隔线
  11532. $chapterContent = trim($chapterContent);
  11533. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  11534. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  11535. if (!empty($cleanTitle) && !empty($chapterContent)) {
  11536. $chapters[] = [
  11537. 'title' => $cleanTitle,
  11538. 'content' => $chapterContent
  11539. ];
  11540. }
  11541. }
  11542. } else {
  11543. // 如果没有匹配到章节,返回整个内容
  11544. $chapters[] = [
  11545. 'title' => '',
  11546. 'content' => $content
  11547. ];
  11548. }
  11549. return $chapters;
  11550. }
  11551. public function getContentByBid($bid) {
  11552. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  11553. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  11554. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  11555. $content = '';
  11556. foreach ($chapters as $chapter) {
  11557. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  11558. }
  11559. return $content;
  11560. }
  11561. public function getContentByScriptId($script_id) {
  11562. $content = '';
  11563. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  11564. if ($contents) {
  11565. $content = implode(PHP_EOL, $contents);
  11566. }else {
  11567. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  11568. }
  11569. return $content;
  11570. }
  11571. /**
  11572. * 根据文件类型提取文本内容
  11573. *
  11574. * @param mixed $file 文件对象或文件路径
  11575. * @return string
  11576. */
  11577. public function extractFileContent($file) {
  11578. // 获取文件路径和扩展名
  11579. if (is_string($file)) {
  11580. $filePath = $file;
  11581. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  11582. } else {
  11583. // Laravel UploadedFile 对象
  11584. $filePath = $file->getRealPath();
  11585. $extension = strtolower($file->getClientOriginalExtension());
  11586. }
  11587. $content = '';
  11588. switch ($extension) {
  11589. case 'txt':
  11590. $content = $this->extractTxtContent($filePath);
  11591. break;
  11592. case 'pdf':
  11593. $content = $this->extractPdfContent($filePath);
  11594. break;
  11595. case 'doc':
  11596. case 'docx':
  11597. $content = $this->extractWordContent($filePath);
  11598. break;
  11599. // case 'jpg':
  11600. // case 'jpeg':
  11601. // case 'png':
  11602. // case 'gif':
  11603. // case 'bmp':
  11604. // case 'webp':
  11605. // $content = $this->extractImageContent($filePath);
  11606. // break;
  11607. default:
  11608. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  11609. }
  11610. return $content;
  11611. }
  11612. /**
  11613. * 提取 TXT 文件内容
  11614. */
  11615. private function extractTxtContent($filePath) {
  11616. if (!file_exists($filePath)) {
  11617. Utils::throwError('20003:文件不存在');
  11618. }
  11619. $content = file_get_contents($filePath);
  11620. // 尝试检测并转换编码
  11621. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  11622. if ($encoding && $encoding !== 'UTF-8') {
  11623. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  11624. }
  11625. return trim($content);
  11626. }
  11627. /**
  11628. * 提取 PDF 文件内容
  11629. */
  11630. private function extractPdfContent($filePath) {
  11631. if (!file_exists($filePath)) {
  11632. Utils::throwError('20003:文件不存在');
  11633. }
  11634. try {
  11635. $parser = new PdfParser();
  11636. $pdf = $parser->parseFile($filePath);
  11637. $content = $pdf->getText();
  11638. return trim($content);
  11639. } catch (\Exception $e) {
  11640. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  11641. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  11642. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  11643. }
  11644. }
  11645. /**
  11646. * 提取 Word 文件内容(支持 doc 和 docx)
  11647. */
  11648. private function extractWordContent($filePath) {
  11649. if (!file_exists($filePath)) {
  11650. Utils::throwError('20003:文件不存在');
  11651. }
  11652. try {
  11653. $phpWord = WordIOFactory::load($filePath);
  11654. $content = '';
  11655. foreach ($phpWord->getSections() as $section) {
  11656. foreach ($section->getElements() as $element) {
  11657. $content .= $this->extractWordElementText($element);
  11658. }
  11659. }
  11660. return trim($content);
  11661. } catch (\Exception $e) {
  11662. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  11663. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  11664. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  11665. }
  11666. }
  11667. /**
  11668. * 递归提取 Word 元素中的文本
  11669. */
  11670. private function extractWordElementText($element) {
  11671. $text = '';
  11672. if (method_exists($element, 'getText')) {
  11673. $text .= $element->getText() . "\n";
  11674. } elseif (method_exists($element, 'getElements')) {
  11675. foreach ($element->getElements() as $childElement) {
  11676. $text .= $this->extractWordElementText($childElement);
  11677. }
  11678. }
  11679. return $text;
  11680. }
  11681. /**
  11682. * 提取图片内容(使用火山引擎 OCR)
  11683. */
  11684. private function extractImageContent($filePath) {
  11685. if (!file_exists($filePath)) {
  11686. Utils::throwError('20003:文件不存在');
  11687. }
  11688. try {
  11689. // 读取图片并转换为 base64
  11690. $imageData = file_get_contents($filePath);
  11691. $base64Image = base64_encode($imageData);
  11692. // 调用火山引擎 OCR 服务
  11693. $content = $this->callVolcEngineOCR($base64Image);
  11694. return trim($content);
  11695. } catch (\Exception $e) {
  11696. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  11697. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  11698. Utils::throwError('20003:图片识别失败');
  11699. }
  11700. }
  11701. /**
  11702. * 调用火山引擎 OCR 服务识别图片文字
  11703. *
  11704. * @param string $base64Image base64 编码的图片数据
  11705. * @return string 识别的文字内容
  11706. */
  11707. private function callVolcEngineOCR($base64Image) {
  11708. $method = 'POST';
  11709. $service = 'cv';
  11710. $host = 'visual.volcengineapi.com';
  11711. $region = env('VOLC_REGION', 'cn-north-1');
  11712. $access_key = env('VOLC_AK');
  11713. $secret_key = env('VOLC_SK');
  11714. $action = 'OCRNormal';
  11715. $version = '2020-08-26';
  11716. if (!$access_key || !$secret_key) {
  11717. Utils::throwError('20003:请配置火山引擎 AK/SK');
  11718. }
  11719. // 请求体
  11720. $body = json_encode([
  11721. 'image_base64' => $base64Image
  11722. ]);
  11723. // 生成签名
  11724. $headers = $this->getVolcEngineSignHeaders(
  11725. $method, $service, $host, $region,
  11726. "Action={$action}&Version={$version}",
  11727. $access_key, $secret_key, $body
  11728. );
  11729. $client = new Client(['timeout' => 1800, 'verify' => false]);
  11730. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  11731. 'headers' => $headers,
  11732. 'body' => $body
  11733. ]);
  11734. $response_arr = json_decode($response->getBody()->getContents(), true);
  11735. // 提取识别的文字
  11736. $textLines = [];
  11737. if (isset($response_arr['data']['line_texts'])) {
  11738. $textLines = $response_arr['data']['line_texts'];
  11739. } elseif (isset($response_arr['data']['ocr_infos'])) {
  11740. foreach ($response_arr['data']['ocr_infos'] as $info) {
  11741. if (isset($info['text'])) {
  11742. $textLines[] = $info['text'];
  11743. }
  11744. }
  11745. }
  11746. if (empty($textLines)) {
  11747. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  11748. return '';
  11749. }
  11750. return implode("\n", $textLines);
  11751. }
  11752. /**
  11753. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  11754. */
  11755. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  11756. $contentType = 'application/json';
  11757. $accept = 'application/json';
  11758. // 获取当前UTC时间
  11759. $t = new DateTime('now', new DateTimeZone('UTC'));
  11760. $xDate = $t->format('Ymd\THis\Z');
  11761. $dateStamp = $t->format('Ymd');
  11762. // 计算 body 的 sha256 哈希
  11763. $payloadHash = hash('sha256', $body);
  11764. // 1. 拼接规范请求串
  11765. $canonicalUri = '/';
  11766. $canonicalQueryString = $queryString;
  11767. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  11768. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  11769. $canonicalRequest = implode("\n", [
  11770. $method,
  11771. $canonicalUri,
  11772. $canonicalQueryString,
  11773. $canonicalHeaders,
  11774. $signedHeaders,
  11775. $payloadHash
  11776. ]);
  11777. // 2. 拼接待签名字符串
  11778. $algorithm = 'HMAC-SHA256';
  11779. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  11780. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  11781. $stringToSign = implode("\n", [
  11782. $algorithm,
  11783. $xDate,
  11784. $credentialScope,
  11785. $hashedCanonicalRequest
  11786. ]);
  11787. // 3. 计算签名
  11788. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  11789. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  11790. // 4. 添加签名到请求头
  11791. $authorizationHeader = sprintf(
  11792. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  11793. $algorithm,
  11794. $access_key,
  11795. $credentialScope,
  11796. $signedHeaders,
  11797. $signature
  11798. );
  11799. return [
  11800. 'Accept' => $accept,
  11801. 'Content-Type' => $contentType,
  11802. 'Host' => $host,
  11803. 'X-Date' => $xDate,
  11804. 'X-Content-Sha256'=> $payloadHash,
  11805. 'Authorization' => $authorizationHeader
  11806. ];
  11807. }
  11808. public function generateScriptWords($cid, $model = 'r1') {
  11809. ini_set('max_execution_time', 0);
  11810. if (!$cid) Utils::throwError('20003: 请选择章节!');
  11811. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  11812. // 模型兼容性处理和思考模式设置
  11813. $thinkingMode = 'disabled';
  11814. $reasoningEffort = 'high';
  11815. if ($model == 'r1') {
  11816. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  11817. $thinkingMode = 'enabled';
  11818. } else {
  11819. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  11820. $thinkingMode = 'disabled';
  11821. }
  11822. $messages = [
  11823. [
  11824. 'role' => 'system',
  11825. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  11826. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  11827. 2.非对话部分请全部用旁白角色代替
  11828. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  11829. ],
  11830. [
  11831. 'role' => 'user',
  11832. 'content' => $content
  11833. ]
  11834. ];
  11835. $post_data = [
  11836. 'model' => $model,
  11837. 'messages' => $messages,
  11838. // 'max_tokens' => 8192,
  11839. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  11840. 'frequency_penalty' => 0,
  11841. 'presence_penalty' => 0,
  11842. 'thinking' => ['type' => $thinkingMode],
  11843. 'response_format' => [
  11844. 'type' => 'text'
  11845. ],
  11846. 'stream' => false
  11847. ];
  11848. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  11849. // 根据模型类型选择调用方法
  11850. $fullContent = '';
  11851. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11852. // DeepSeek 官方模型使用 DeepSeek API
  11853. $chatResult = $this->chatOnly($post_data);
  11854. } else if (in_array($model, $this->gpt_text_models)) {
  11855. // GPT-5.4 模型使用 TokenRouter API
  11856. $chatResult = $this->gpt54ChatOnly($post_data);
  11857. } else {
  11858. // 其他模型使用火山引擎API
  11859. $chatResult = $this->volcEngineChatCompletion($post_data);
  11860. }
  11861. if (is_array($chatResult)) {
  11862. $fullContent = $chatResult['fullContent'];
  11863. }
  11864. return $fullContent;
  11865. }
  11866. /**
  11867. * 智能化解析集数信息
  11868. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  11869. *
  11870. * @param string $prompt 用户输入的提示词
  11871. * @return int|null 解析出的集数,如果没有找到则返回null
  11872. */
  11873. private function extractEpisodeNumber($prompt)
  11874. {
  11875. if (empty($prompt)) {
  11876. return null;
  11877. }
  11878. // 定义各种可能的表达模式
  11879. $patterns = [
  11880. // 基本模式:改成N集、调整成N集、修改成N集
  11881. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  11882. // 扩展模式:分成N集、拆分成N集、分割成N集
  11883. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  11884. // 数量模式:N集、共N集、总共N集
  11885. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  11886. // 制作模式:制作N集、生成N集、创建N集
  11887. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  11888. // 计划模式:计划N集、预计N集、打算N集
  11889. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  11890. // 需要模式:需要N集、要N集
  11891. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  11892. // 中文数字模式:改成三集、调整成五集等
  11893. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  11894. // 英文数字模式
  11895. '/(?:change\s+to|adjust\s+to|modify\s+to|set\s+to|make\s+it|split\s+into|divide\s+into)\s*(\d+)\s*(?:episodes?|eps?)/i',
  11896. ];
  11897. // 中文数字转阿拉伯数字的映射
  11898. $chineseNumbers = [
  11899. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  11900. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  11901. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  11902. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  11903. ];
  11904. // 逐个尝试匹配模式
  11905. foreach ($patterns as $pattern) {
  11906. if (preg_match($pattern, $prompt, $matches)) {
  11907. $number = trim($matches[1]);
  11908. // 如果是中文数字,转换为阿拉伯数字
  11909. if (isset($chineseNumbers[$number])) {
  11910. return $chineseNumbers[$number];
  11911. }
  11912. // 如果是阿拉伯数字,直接返回
  11913. if (is_numeric($number)) {
  11914. $episodeNum = intval($number);
  11915. // 合理性检查:集数应该在1-100之间
  11916. if ($episodeNum >= 1 && $episodeNum <= 100) {
  11917. return $episodeNum;
  11918. }
  11919. }
  11920. }
  11921. }
  11922. return null;
  11923. }
  11924. /**
  11925. * 调用火山引擎对话(Chat) API
  11926. *
  11927. * @param array $params 包含以下参数:
  11928. * - model: 模型ID(必填)
  11929. * - messages: 消息列表(必填)
  11930. * - stream: 是否流式输出(可选,默认false)
  11931. * - max_tokens: 最大输出token数(可选)
  11932. * - temperature: 采样温度(可选,默认1)
  11933. * - top_p: 核采样概率(可选,默认0.7)
  11934. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  11935. * - presence_penalty: 存在惩罚系数(可选,默认0)
  11936. * - stop: 停止词(可选)
  11937. * - tools: 工具列表(可选)
  11938. * @return array|Generator 非流式返回数组,流式返回生成器
  11939. */
  11940. public function volcEngineChatCompletion(array $params)
  11941. {
  11942. $apiKey = env('VOLC_AI_API_KEY');
  11943. if (empty($apiKey)) {
  11944. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  11945. }
  11946. // 构建请求参数
  11947. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  11948. $requestData = [
  11949. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  11950. 'messages' => $params['messages'] ?? [],
  11951. ];
  11952. if (!in_array($originalModel, $this->valid_text_models)) {
  11953. Utils::throwError('20003:该模型不支持!');
  11954. }
  11955. // 添加可选参数
  11956. if (isset($params['stream'])) {
  11957. $requestData['stream'] = $params['stream'];
  11958. }
  11959. if (isset($params['stream_options'])) {
  11960. $requestData['stream_options'] = $params['stream_options'];
  11961. }
  11962. if (isset($params['max_tokens'])) {
  11963. $requestData['max_tokens'] = $params['max_tokens'];
  11964. }else if (isset($params['max_completion_tokens'])) {
  11965. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  11966. }else {
  11967. $requestData['max_completion_tokens'] = 100000;
  11968. }
  11969. if (isset($params['temperature'])) {
  11970. $requestData['temperature'] = $params['temperature'];
  11971. }
  11972. if (isset($params['top_p'])) {
  11973. $requestData['top_p'] = $params['top_p'];
  11974. }
  11975. if (isset($params['frequency_penalty'])) {
  11976. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  11977. }
  11978. if (isset($params['presence_penalty'])) {
  11979. $requestData['presence_penalty'] = $params['presence_penalty'];
  11980. }
  11981. if (isset($params['stop'])) {
  11982. $requestData['stop'] = $params['stop'];
  11983. }
  11984. if (isset($params['tools'])) {
  11985. $requestData['tools'] = $params['tools'];
  11986. }
  11987. if (isset($params['tool_choice'])) {
  11988. $requestData['tool_choice'] = $params['tool_choice'];
  11989. }
  11990. if (isset($params['response_format'])) {
  11991. $requestData['response_format'] = $params['response_format'];
  11992. }
  11993. if (isset($params['thinking'])) {
  11994. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  11995. if (is_array($params['thinking'])) {
  11996. $requestData['thinking'] = $params['thinking'];
  11997. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  11998. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11999. }
  12000. } else {
  12001. $requestData['thinking'] = ['type' => $params['thinking']];
  12002. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  12003. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  12004. }
  12005. }
  12006. } else {
  12007. $requestData['thinking'] = ['type' => 'disabled'];
  12008. }
  12009. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  12010. $client = new Client(['verify' => false, 'timeout' => 1800]);
  12011. try {
  12012. // 判断是否为流式输出
  12013. $isStream = isset($params['stream']) && $params['stream'] === true;
  12014. if ($isStream) {
  12015. // 流式输出
  12016. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  12017. } else {
  12018. // 非流式输出
  12019. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  12020. 'headers' => [
  12021. 'Authorization' => 'Bearer ' . $apiKey,
  12022. 'Content-Type' => 'application/json',
  12023. ],
  12024. 'json' => $requestData
  12025. ]);
  12026. $responseData = json_decode($response->getBody(), true);
  12027. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  12028. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  12029. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  12030. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  12031. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  12032. }
  12033. return [
  12034. 'fullContent' => $fullContent,
  12035. 'fullReasoningContent' => $fullReasoningContent,
  12036. 'usage' => $usage
  12037. ];
  12038. }
  12039. } catch (\Exception $e) {
  12040. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  12041. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  12042. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  12043. }
  12044. }
  12045. /**
  12046. * 火山引擎对话API流式输出
  12047. *
  12048. * @param Client $client HTTP客户端
  12049. * @param string $apiKey API密钥
  12050. * @param array $requestData 请求数据
  12051. * @return Generator
  12052. */
  12053. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  12054. {
  12055. try {
  12056. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  12057. 'headers' => [
  12058. 'Authorization' => 'Bearer ' . $apiKey,
  12059. 'Content-Type' => 'application/json',
  12060. ],
  12061. 'json' => $requestData,
  12062. 'stream' => true
  12063. ]);
  12064. $body = $response->getBody();
  12065. $buffer = '';
  12066. $fullContent = '';
  12067. $fullReasoningContent = '';
  12068. $usage = [];
  12069. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  12070. // 逐行读取流式响应
  12071. while (!$body->eof()) {
  12072. $chunk = $body->read(1024);
  12073. $buffer .= $chunk;
  12074. // 按行分割
  12075. $lines = explode("\n", $buffer);
  12076. $buffer = array_pop($lines);
  12077. foreach ($lines as $line) {
  12078. $line = trim($line);
  12079. if (empty($line)) {
  12080. continue;
  12081. }
  12082. // 检查是否是SSE数据行
  12083. if (strpos($line, 'data: ') !== 0) {
  12084. continue;
  12085. }
  12086. $data = substr($line, 6);
  12087. if ($data === '[DONE]') {
  12088. dLog('deepseek')->info('收到结束标记');
  12089. break 2;
  12090. }
  12091. try {
  12092. $json = json_decode($data, true);
  12093. if (json_last_error() !== JSON_ERROR_NONE) {
  12094. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  12095. continue;
  12096. }
  12097. if (isset($json['choices'][0]['delta'])) {
  12098. $delta = $json['choices'][0]['delta'];
  12099. // 处理思维链内容
  12100. if (isset($delta['reasoning_content'])) {
  12101. $fullReasoningContent .= $delta['reasoning_content'];
  12102. yield [
  12103. 'type' => 'reasoning',
  12104. 'content' => $delta['reasoning_content'],
  12105. 'full_reasoning' => $fullReasoningContent
  12106. ];
  12107. }
  12108. // 处理回答内容
  12109. if (isset($delta['content'])) {
  12110. $fullContent .= $delta['content'];
  12111. yield [
  12112. 'type' => 'content',
  12113. 'content' => $delta['content'],
  12114. ];
  12115. }
  12116. }
  12117. // 获取使用统计信息
  12118. if (isset($json['usage'])) {
  12119. $usage = $json['usage'];
  12120. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  12121. }
  12122. } catch (\Exception $e) {
  12123. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  12124. continue;
  12125. }
  12126. }
  12127. }
  12128. dLog('deepseek')->info('流式读取完成', [
  12129. 'content_length' => strlen($fullContent),
  12130. 'reasoning_length' => strlen($fullReasoningContent)
  12131. ]);
  12132. yield [
  12133. 'type' => 'done',
  12134. 'full_content' => $fullContent,
  12135. 'full_reasoning' => $fullReasoningContent,
  12136. 'usage' => $usage
  12137. ];
  12138. } catch (\Exception $e) {
  12139. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  12140. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  12141. throw $e;
  12142. }
  12143. }
  12144. /**
  12145. * 检查并创建图片生成任务
  12146. *
  12147. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  12148. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  12149. * @param string $nameKey 资源名称字段('role' 或 'scene')
  12150. * @param string $art_style 美术风格
  12151. * @return array 更新后的资源列表
  12152. */
  12153. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  12154. {
  12155. // 确保参数为数组
  12156. $merged_items = is_array($merged_items) ? $merged_items : [];
  12157. $global_items = is_array($global_items) ? $global_items : [];
  12158. // 构建全局资源映射表,用于快速查找
  12159. $global_map = [];
  12160. foreach ($global_items as $item) {
  12161. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  12162. if ($itemKey === '') {
  12163. continue;
  12164. }
  12165. $global_map[$itemKey] = $item;
  12166. }
  12167. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  12168. foreach ($merged_items as &$item) {
  12169. $item_name = getProp($item, $nameKey);
  12170. $item_description = getProp($item, 'description');
  12171. // $item_url = getProp($item, 'url');
  12172. // // 如果已有图片URL,跳过
  12173. // if (!empty($item_url)) {
  12174. // continue;
  12175. // }
  12176. // 如果是旁白角色,跳过
  12177. if ($nameKey === 'role' && $item_name === '旁白') {
  12178. continue;
  12179. }
  12180. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  12181. if ($itemKey === '') {
  12182. continue;
  12183. }
  12184. $need_create_task = false;
  12185. // 条件1:在全局资源中找不到匹配的名称
  12186. if (!isset($global_map[$itemKey])) {
  12187. $need_create_task = true;
  12188. } else {
  12189. // 条件2:名称匹配但描述或 pic_prompt 不一致
  12190. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  12191. $current_description = trim((string)$item_description);
  12192. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  12193. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  12194. // 如果 description 或 pic_prompt 有变化,需要重新生成
  12195. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  12196. $need_create_task = true;
  12197. }
  12198. }
  12199. // 如果需要创建任务,调用图片生成服务
  12200. if ($need_create_task) {
  12201. try {
  12202. // 优先使用 pic_prompt,如果没有则使用 description
  12203. $pic_prompt = getProp($item, 'pic_prompt');
  12204. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  12205. // 添加美术风格前缀
  12206. if ($art_style) {
  12207. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  12208. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  12209. $description = "{$prefix}:{$description}";
  12210. }
  12211. $params = [
  12212. 'prompt' => $description,
  12213. 'ref_img_urls' => []
  12214. ];
  12215. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12216. $task_id = $task->id;
  12217. if ($task_id) {
  12218. $item['task_id'] = $task_id;
  12219. $item['task_status'] = 'processing';
  12220. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  12221. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  12222. }
  12223. } catch (\Exception $e) {
  12224. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  12225. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  12226. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  12227. // 不抛出异常,继续处理其他资源
  12228. }
  12229. }
  12230. }
  12231. return $merged_items;
  12232. }
  12233. /**
  12234. * 同步新出现的主体和场景到全局
  12235. *
  12236. * @param int $anime_id 动漫ID
  12237. * @param array $merged_roles 合并后的角色列表
  12238. * @param array $merged_scenes 合并后的场景列表
  12239. * @param array $global_roles 全局角色列表
  12240. * @param array $global_scenes 全局场景列表
  12241. * @return void
  12242. */
  12243. private function syncNewResourcesToGlobal(
  12244. int $anime_id,
  12245. array $merged_roles,
  12246. array $merged_scenes,
  12247. array $global_roles,
  12248. array $global_scenes
  12249. ): void {
  12250. // 构建全局角色映射表
  12251. $global_role_map = [];
  12252. foreach ($global_roles as $role) {
  12253. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  12254. if ($roleKey !== '') {
  12255. $global_role_map[$roleKey] = $role;
  12256. }
  12257. }
  12258. // 构建全局场景映射表
  12259. $global_scene_map = [];
  12260. foreach ($global_scenes as $scene) {
  12261. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  12262. if ($sceneKey !== '') {
  12263. $global_scene_map[$sceneKey] = $scene;
  12264. }
  12265. }
  12266. $need_update = false;
  12267. $new_global_roles = $global_roles;
  12268. $new_global_scenes = $global_scenes;
  12269. // 检查并添加新角色到全局
  12270. foreach ($merged_roles as $role) {
  12271. $role_name = getProp($role, 'role');
  12272. // 跳过旁白
  12273. if ($role_name === '旁白') {
  12274. continue;
  12275. }
  12276. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  12277. if ($roleKey === '') {
  12278. continue;
  12279. }
  12280. // 如果全局中不存在该角色,添加到全局
  12281. if (!isset($global_role_map[$roleKey])) {
  12282. $new_global_roles[] = [
  12283. 'role' => $role_name,
  12284. 'description' => getProp($role, 'description', ''),
  12285. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  12286. 'voice_name' => getProp($role, 'voice_name', ''),
  12287. 'voice_type' => getProp($role, 'voice_type', ''),
  12288. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  12289. 'url' => getProp($role, 'url', ''),
  12290. 'task_id' => getProp($role, 'task_id', ''),
  12291. 'task_status' => getProp($role, 'task_status', ''),
  12292. ];
  12293. $global_role_map[$roleKey] = true; // 标记已添加
  12294. $need_update = true;
  12295. dLog('deepseek')->info("新角色同步到全局", [
  12296. 'anime_id' => $anime_id,
  12297. 'role' => $role_name,
  12298. 'task_id' => getProp($role, 'task_id', ''),
  12299. ]);
  12300. }
  12301. // else {
  12302. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  12303. // $global_role = $global_role_map[$roleKey];
  12304. // if (is_array($global_role)) {
  12305. // $updated = false;
  12306. // $update_fields = [];
  12307. // // 检查描述是否更新
  12308. // $current_description = trim((string)getProp($role, 'description'));
  12309. // $global_description = trim((string)getProp($global_role, 'description'));
  12310. // if ($current_description !== '' && $current_description !== $global_description) {
  12311. // $updated = true;
  12312. // $update_fields[] = 'description';
  12313. // }
  12314. // // 检查pic_prompt是否更新
  12315. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  12316. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  12317. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  12318. // $updated = true;
  12319. // $update_fields[] = 'pic_prompt';
  12320. // }
  12321. // // 检查图片任务信息是否更新
  12322. // $current_task_id = getProp($role, 'task_id');
  12323. // $global_task_id = getProp($global_role, 'task_id');
  12324. // if ($current_task_id && $current_task_id !== $global_task_id) {
  12325. // $updated = true;
  12326. // $update_fields[] = 'task_id';
  12327. // }
  12328. // // 如果有更新,同步到全局
  12329. // if ($updated) {
  12330. // foreach ($new_global_roles as &$global_role_item) {
  12331. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  12332. // if ($global_role_key === $roleKey) {
  12333. // if (in_array('description', $update_fields)) {
  12334. // $global_role_item['description'] = $current_description;
  12335. // }
  12336. // if (in_array('pic_prompt', $update_fields)) {
  12337. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  12338. // }
  12339. // if (in_array('task_id', $update_fields)) {
  12340. // $global_role_item['task_id'] = $current_task_id;
  12341. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  12342. // $global_role_item['url'] = getProp($role, 'url', '');
  12343. // }
  12344. // break;
  12345. // }
  12346. // }
  12347. // $need_update = true;
  12348. // dLog('deepseek')->info("角色信息更新到全局", [
  12349. // 'anime_id' => $anime_id,
  12350. // 'role' => $role_name,
  12351. // 'update_fields' => implode(',', $update_fields),
  12352. // ]);
  12353. // }
  12354. // }
  12355. // }
  12356. }
  12357. // 检查并添加新场景到全局
  12358. foreach ($merged_scenes as $scene) {
  12359. $scene_name = getProp($scene, 'scene');
  12360. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  12361. if ($sceneKey === '') {
  12362. continue;
  12363. }
  12364. // 如果全局中不存在该场景,添加到全局
  12365. if (!isset($global_scene_map[$sceneKey])) {
  12366. $new_global_scenes[] = [
  12367. 'scene' => $scene_name,
  12368. 'description' => getProp($scene, 'description', ''),
  12369. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  12370. 'url' => getProp($scene, 'url', ''),
  12371. 'task_id' => getProp($scene, 'task_id', ''),
  12372. 'task_status' => getProp($scene, 'task_status', ''),
  12373. ];
  12374. $global_scene_map[$sceneKey] = true; // 标记已添加
  12375. $need_update = true;
  12376. dLog('deepseek')->info("新场景同步到全局", [
  12377. 'anime_id' => $anime_id,
  12378. 'scene' => $scene_name,
  12379. 'task_id' => getProp($scene, 'task_id', ''),
  12380. ]);
  12381. }
  12382. // else {
  12383. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  12384. // $global_scene = $global_scene_map[$sceneKey];
  12385. // if (is_array($global_scene)) {
  12386. // $updated = false;
  12387. // $update_fields = [];
  12388. // // 检查描述是否更新
  12389. // $current_description = trim((string)getProp($scene, 'description'));
  12390. // $global_description = trim((string)getProp($global_scene, 'description'));
  12391. // if ($current_description !== '' && $current_description !== $global_description) {
  12392. // $updated = true;
  12393. // $update_fields[] = 'description';
  12394. // }
  12395. // // 检查pic_prompt是否更新
  12396. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  12397. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  12398. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  12399. // $updated = true;
  12400. // $update_fields[] = 'pic_prompt';
  12401. // }
  12402. // // 检查图片任务信息是否更新
  12403. // $current_task_id = getProp($scene, 'task_id');
  12404. // $global_task_id = getProp($global_scene, 'task_id');
  12405. // if ($current_task_id && $current_task_id !== $global_task_id) {
  12406. // $updated = true;
  12407. // $update_fields[] = 'task_id';
  12408. // }
  12409. // // 如果有更新,同步到全局
  12410. // if ($updated) {
  12411. // foreach ($new_global_scenes as &$global_scene_item) {
  12412. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  12413. // if ($global_scene_key === $sceneKey) {
  12414. // if (in_array('description', $update_fields)) {
  12415. // $global_scene_item['description'] = $current_description;
  12416. // }
  12417. // if (in_array('pic_prompt', $update_fields)) {
  12418. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  12419. // }
  12420. // if (in_array('task_id', $update_fields)) {
  12421. // $global_scene_item['task_id'] = $current_task_id;
  12422. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  12423. // $global_scene_item['url'] = getProp($scene, 'url', '');
  12424. // }
  12425. // break;
  12426. // }
  12427. // }
  12428. // $need_update = true;
  12429. // dLog('deepseek')->info("场景信息更新到全局", [
  12430. // 'anime_id' => $anime_id,
  12431. // 'scene' => $scene_name,
  12432. // 'update_fields' => implode(',', $update_fields),
  12433. // ]);
  12434. // }
  12435. // }
  12436. // }
  12437. }
  12438. // 如果有新增或更新,更新数据库
  12439. if ($need_update) {
  12440. $update_data = [
  12441. 'roles' => json_encode($new_global_roles, 256),
  12442. 'scenes' => json_encode($new_global_scenes, 256),
  12443. 'updated_at' => date('Y-m-d H:i:s'),
  12444. ];
  12445. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  12446. if ($result !== false) {
  12447. dLog('deepseek')->info("全局角色和场景更新成功", [
  12448. 'anime_id' => $anime_id,
  12449. 'roles_count' => count($new_global_roles),
  12450. 'scenes_count' => count($new_global_scenes),
  12451. ]);
  12452. } else {
  12453. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  12454. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  12455. }
  12456. }
  12457. }
  12458. }