DeepSeekService.php 724 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031
  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 App\Services\PointsService;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Log;
  14. use Illuminate\Support\Facades\Redis;
  15. use OSS\Core\OssException;
  16. use OSS\OssClient;
  17. use Smalot\PdfParser\Parser as PdfParser;
  18. use TCPDF;
  19. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  20. use Predis\Command\Traits\Get\Get;
  21. class DeepSeekService
  22. {
  23. private $url;
  24. private $api_key;
  25. private $sys_message;
  26. private $headers;
  27. private $valid_text_models;
  28. private $gpt_text_models;
  29. protected $aiImageGenerationService;
  30. protected $pointsService;
  31. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  32. $this->aiImageGenerationService = $aiImageGenerationService;
  33. $this->pointsService = $pointsService;
  34. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  35. $this->api_key = env('DEEPSEEK_API_KEY');
  36. $this->headers = [
  37. 'Authorization' => 'Bearer '.$this->api_key,
  38. 'Content-Type' => 'application/json; charset=UTF-8'
  39. ];
  40. // 火山引擎模型列表
  41. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  42. // GPT文本模型列表
  43. $this->gpt_text_models = BaseConst::GPT_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->valid_text_models)) {
  227. // 火山引擎支持的模型使用火山引擎 API
  228. return $this->volcEngineChatCompletion($post_data);
  229. } else {
  230. Utils::throwError('20003:不支持的模型: ' . $model);
  231. }
  232. }
  233. public function createGenerateText($data) {
  234. $file = getProp($data, 'file');
  235. $uid = Site::getUid();
  236. $cpid = Site::getCpid();
  237. if (!$file) {
  238. Utils::throwError('20003:请上传文件');
  239. }
  240. // 提取文件内容
  241. $content = $this->extractFileContent($file);
  242. if (!$content) {
  243. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  244. }
  245. // 获取原始文件名(不含扩展名)作为script_name
  246. $originalName = $file->getClientOriginalName();
  247. $script_name = pathinfo($originalName, PATHINFO_FILENAME);
  248. if (!$script_name) {
  249. $script_name = '剧本_' . date('YmdHis');
  250. }
  251. // 如果剧本名称已存在,添加时间戳后缀
  252. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('is_deleted', 0)->exists()) {
  253. $script_name .= '_' . date('YmdHis');
  254. }
  255. // 插入数据到mp_scripts表
  256. $script_id = DB::table('mp_scripts')->insertGetId([
  257. 'script_name' => $script_name,
  258. 'user_id' => $uid,
  259. 'cpid' => $cpid,
  260. 'content' => $content,
  261. 'created_at' => date('Y-m-d H:i:s'),
  262. 'updated_at' => date('Y-m-d H:i:s')
  263. ]);
  264. return [
  265. 'script_id' => $script_id,
  266. 'script_name' => $script_name
  267. ];
  268. }
  269. /**
  270. * AI对话调用成功后的积分扣费(返回结果前调用)
  271. *
  272. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  273. *
  274. * @param int $uid
  275. * @param int $tokens
  276. * @param array $chargeInfo
  277. * @return void
  278. */
  279. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo): void
  280. {
  281. $result = $this->pointsService->recordChatCharge(
  282. $uid,
  283. PointsService::CHAT_CHARGE_POINTS,
  284. $tokens,
  285. $chargeInfo
  286. );
  287. if (empty($result['charged'])) {
  288. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  289. }
  290. }
  291. /**
  292. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  293. *
  294. * @param array $data 请求参数
  295. * @return array 返回结果数组
  296. */
  297. public function newGenerateText($data) {
  298. // 获取请求参数
  299. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  300. $messages = getProp($data, 'messages', []);
  301. $systemPrompt = getProp($data, 'system_prompt', '');
  302. $prompt = getProp($data, 'prompt', '');
  303. $images = getProp($data, 'images', []); // 支持多张图片
  304. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  305. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  306. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  307. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  308. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  309. $uid = Site::getUid();
  310. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  311. $originalContent = '';
  312. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  313. if ($script_id > 0) {
  314. $script = DB::table('mp_scripts')
  315. ->where('id', $script_id)
  316. ->where('is_deleted', 0)
  317. ->first();
  318. if (!$script) {
  319. Utils::throwError('20003:剧本不存在或已删除');
  320. }
  321. $originalContent = $script->content ?? '';
  322. if (empty($originalContent)) {
  323. Utils::throwError('20003:剧本内容为空');
  324. }
  325. $hasValidScript = true;
  326. // 将剧本内容添加到提示词前面
  327. if (!empty($originalContent)) {
  328. if (!empty($prompt)) {
  329. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  330. } else {
  331. $prompt = "原文内容:\n" . $originalContent;
  332. }
  333. }
  334. }
  335. // 新增: 如果提供了template_id,从数据库获取template_prompt
  336. if ($templateId > 0) {
  337. $template = DB::table('mp_prompt_templates')
  338. ->where('id', $templateId)
  339. ->where('is_deleted', 0)
  340. ->first();
  341. if (!$template) {
  342. Utils::throwError('20003:模板不存在或已删除');
  343. }
  344. $templatePrompt = $template->template_prompt ?? '';
  345. // 将模板提示词和用户输入的prompt组合
  346. // 模板为准,用户输入作为补充要求
  347. if (!empty($templatePrompt)) {
  348. if (!empty($prompt)) {
  349. $prompt = $templatePrompt . "\n\n" . $prompt;
  350. } else {
  351. $prompt = $templatePrompt;
  352. }
  353. }
  354. }
  355. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  356. if (empty($messages)) {
  357. $messages = [];
  358. // 添加系统提示词
  359. if (!empty($systemPrompt)) {
  360. $messages[] = [
  361. 'role' => 'system',
  362. 'content' => $systemPrompt
  363. ];
  364. }
  365. // 构建用户消息内容(支持文本+图片)
  366. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  367. $userMessage = [
  368. 'role' => 'user',
  369. 'content' => []
  370. ];
  371. // 添加文本内容
  372. if (!empty($prompt)) {
  373. $userMessage['content'][] = [
  374. 'type' => 'text',
  375. 'text' => $prompt
  376. ];
  377. }
  378. // 处理上传的图片文件
  379. if (!empty($images)) {
  380. if (!is_array($images)) {
  381. $images = [$images];
  382. }
  383. foreach ($images as $image) {
  384. $imageBase64 = $this->processImageToBase64($image);
  385. if ($imageBase64) {
  386. $userMessage['content'][] = [
  387. 'type' => 'image_url',
  388. 'image_url' => [
  389. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  390. ]
  391. ];
  392. }
  393. }
  394. }
  395. // 处理图片URL
  396. if (!empty($imageUrls)) {
  397. if (!is_array($imageUrls)) {
  398. $imageUrls = [$imageUrls];
  399. }
  400. foreach ($imageUrls as $url) {
  401. if (!empty($url)) {
  402. $userMessage['content'][] = [
  403. 'type' => 'image_url',
  404. 'image_url' => [
  405. 'url' => $url
  406. ]
  407. ];
  408. }
  409. }
  410. }
  411. // 如果只有文本内容,简化为字符串格式
  412. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  413. $userMessage['content'] = $userMessage['content'][0]['text'];
  414. }
  415. $messages[] = $userMessage;
  416. }
  417. }
  418. // 验证messages不为空
  419. if (empty($messages)) {
  420. Utils::throwError('20003:请提供有效的对话内容');
  421. }
  422. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  423. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  424. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  425. if ($model === 'deepseek-chat') {
  426. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  427. $model = 'deepseek-v4-flash';
  428. $thinkingMode = 'disabled';
  429. } elseif ($model === 'deepseek-reasoner') {
  430. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  431. $model = 'deepseek-v4-flash';
  432. $thinkingMode = 'enabled';
  433. }
  434. // 构建请求参数(非流式)
  435. $post_data = [
  436. 'model' => $model,
  437. 'messages' => $messages,
  438. 'temperature' => getProp($data, 'temperature', 1),
  439. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  440. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  441. 'thinking' => ['type' => $thinkingMode],
  442. 'stream' => false // 非流式输出
  443. ];
  444. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  445. // 添加可选参数
  446. if (isset($data['top_p'])) {
  447. $post_data['top_p'] = $data['top_p'];
  448. }
  449. // 新增: 根据response_format设置响应格式
  450. if ($responseFormat === 'json') {
  451. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  452. $hasJsonKeyword = false;
  453. foreach ($post_data['messages'] as $message) {
  454. if (isset($message['content'])) {
  455. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  456. if (stripos($content, 'json') !== false) {
  457. $hasJsonKeyword = true;
  458. break;
  459. }
  460. }
  461. }
  462. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  463. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  464. if (!$hasJsonKeyword) {
  465. $lastMessageIndex = count($post_data['messages']) - 1;
  466. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  467. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  468. // 如果content是字符串,直接追加
  469. if (is_string($lastContent)) {
  470. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  471. }
  472. // 如果content是数组(包含文本和图片),在文本部分追加
  473. else if (is_array($lastContent)) {
  474. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  475. if ($contentPart['type'] === 'text') {
  476. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  477. break;
  478. }
  479. }
  480. }
  481. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  482. }
  483. }
  484. // 设置response_format参数(所有支持的模型)
  485. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  486. // DeepSeek模型
  487. $post_data['response_format'] = ['type' => 'json_object'];
  488. } else if (in_array($model, $this->gpt_text_models)) {
  489. // GPT模型
  490. $post_data['response_format'] = ['type' => 'json_object'];
  491. } else if (in_array($model, $this->valid_text_models)) {
  492. // 火山引擎模型
  493. $post_data['response_format'] = ['type' => 'json_object'];
  494. }
  495. }
  496. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  497. if ($hasValidScript) {
  498. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  499. }
  500. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  501. $aiResult = null;
  502. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  503. // DeepSeek 官方模型使用现有的 chatOnly 方法
  504. $result = $this->chatOnly($post_data);
  505. // 记录实际使用的模型
  506. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  507. $aiResult = [
  508. 'content' => $result['fullContent'],
  509. 'reasoning_content' => $result['fullReasoningContent'],
  510. 'usage' => $result['usage'],
  511. 'model' => $model,
  512. 'finish_reason' => 'stop'
  513. ];
  514. } else if (in_array($model, $this->gpt_text_models)) {
  515. // GPT 模型使用现有的 gpt54ChatOnly 方法
  516. $result = $this->gpt54ChatOnly($post_data);
  517. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  518. $aiResult = [
  519. 'content' => $result['fullContent'],
  520. 'reasoning_content' => '',
  521. 'usage' => $result['usage'],
  522. 'model' => $model,
  523. 'finish_reason' => 'stop'
  524. ];
  525. } else if (in_array($model, $this->valid_text_models)) {
  526. // 火山引擎支持的模型使用火山引擎 API(非流式)
  527. $post_data['stream'] = false;
  528. $result = $this->volcEngineChatCompletion($post_data);
  529. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  530. 'requested_model' => $model,
  531. 'result_keys' => array_keys($result),
  532. 'has_fullContent' => isset($result['fullContent']),
  533. 'has_content' => isset($result['content'])
  534. ]);
  535. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  536. $aiResult = [
  537. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  538. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  539. 'usage' => $result['usage'] ?? [],
  540. 'model' => $model,
  541. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  542. ];
  543. } else {
  544. Utils::throwError('20003:不支持的模型: ' . $model);
  545. }
  546. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  547. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  548. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  549. 'model' => $model,
  550. 'script_id' => $script_id,
  551. 'sequence' => $sequence,
  552. 'source' => 'newGenerateText',
  553. ]);
  554. }
  555. // 新增: 如果提供了script_id,保存对话记录
  556. if ($script_id > 0 && $aiResult) {
  557. try {
  558. $uid = Site::getUid();
  559. $now = now();
  560. // 获取用户原始的prompt(不包含剧本内容)
  561. $originalPrompt = getProp($data, 'prompt', '');
  562. $recordsToInsert = [
  563. [
  564. 'uid' => $uid,
  565. 'script_id' => $script_id,
  566. 'sequence' => $sequence,
  567. 'role' => 'user',
  568. 'content' => $originalPrompt,
  569. 'created_at' => $now,
  570. 'updated_at' => $now,
  571. ],
  572. [
  573. 'uid' => $uid,
  574. 'script_id' => $script_id,
  575. 'sequence' => $sequence,
  576. 'role' => 'assistant',
  577. 'content' => $aiResult['content'],
  578. 'created_at' => $now,
  579. 'updated_at' => $now,
  580. ]
  581. ];
  582. DB::table('mp_script_records')->insert($recordsToInsert);
  583. // 获取刚插入的记录ID(假设按插入顺序返回)
  584. $insertedRecords = DB::table('mp_script_records')
  585. ->where('uid', $uid)
  586. ->where('script_id', $script_id)
  587. ->where('sequence', $sequence)
  588. ->orderBy('id', 'desc')
  589. ->limit(2)
  590. ->get()
  591. ->map(function ($record) {
  592. return [
  593. 'rid' => $record->id,
  594. 'script_id' => $record->script_id,
  595. 'sequence' => $record->sequence,
  596. 'role' => $record->role,
  597. 'content' => $record->content,
  598. 'created_at' => $record->created_at,
  599. ];
  600. })
  601. ->reverse()
  602. ->values()
  603. ->toArray();
  604. // 将记录信息添加到返回结果中
  605. $aiResult['records'] = $insertedRecords;
  606. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  607. } catch (\Exception $e) {
  608. // 记录错误但不影响主流程
  609. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  610. }
  611. }
  612. return $aiResult;
  613. }
  614. public function saveScriptChatHistory($data) {
  615. $uid = Site::getUid();
  616. $rid = getProp($data, 'rid');
  617. $script_id = getProp($data, 'script_id');
  618. $sequence = getProp($data, 'sequence', 0);
  619. $content = getProp($data, 'content');
  620. if (!$rid) {
  621. Utils::throwError('20003:请选择对话记录ID');
  622. }
  623. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  624. if (!$record) {
  625. Utils::throwError('20003:对话记录不存在');
  626. }
  627. if (!$script_id) {
  628. Utils::throwError('20003:请选择剧本');
  629. }
  630. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  631. if (!$script) {
  632. Utils::throwError('20003:剧本不存在');
  633. }
  634. // 批量插入数据
  635. return DB::table('mp_script_records')->where('id', $rid)->update([
  636. 'content' => $content,
  637. 'updated_at' => date('Y-m-d H:i:s')
  638. ]);
  639. }
  640. /**
  641. * 获取剧本的历史对话记录
  642. *
  643. * @param array $data 请求参数
  644. * @return array 返回历史记录数组
  645. */
  646. public function getScriptChatHistory($data) {
  647. $uid = Site::getUid();
  648. $script_id = getProp($data, 'script_id');
  649. $rid = getProp($data, 'rid');
  650. $sequence = getProp($data, 'sequence', null);
  651. if (!$script_id) {
  652. Utils::throwError('20003:请提供剧本ID');
  653. }
  654. // 验证剧本是否存在
  655. $script = DB::table('mp_scripts')
  656. ->where('id', $script_id)
  657. ->where('is_deleted', 0)
  658. ->first();
  659. if (!$script) {
  660. Utils::throwError('20003:剧本不存在');
  661. }
  662. // 构建查询
  663. $query = DB::table('mp_script_records')
  664. ->where('script_id', $script_id);
  665. // ->where('uid', $uid);
  666. // 如果提供了 sequence,则过滤指定剧集
  667. if ($sequence !== null) {
  668. $query->where('sequence', $sequence);
  669. }
  670. // 记录ID筛选
  671. if ($rid) {
  672. $query->where('id', $rid);
  673. }
  674. // 查询记录并按 id 正序排序
  675. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  676. ->orderBy('created_at', 'asc')
  677. ->orderBy('id', 'asc')
  678. ->get()
  679. ->map(function ($record) {
  680. return [
  681. 'rid' => $record->id,
  682. 'script_id' => $record->script_id,
  683. 'sequence' => $record->sequence,
  684. 'role' => $record->role,
  685. 'content' => $record->content,
  686. 'products' => $record->products ? json_decode($record->products) : [],
  687. 'created_at' => $record->created_at,
  688. ];
  689. })
  690. ->toArray();
  691. return $records;
  692. }
  693. /**
  694. * 处理图片转换为base64
  695. *
  696. * @param mixed $image 图片文件对象或文件路径
  697. * @return string|null base64编码的图片数据
  698. */
  699. private function processImageToBase64($image) {
  700. try {
  701. // 获取文件路径
  702. if (is_string($image)) {
  703. $filePath = $image;
  704. } else {
  705. // Laravel UploadedFile 对象
  706. $filePath = $image->getRealPath();
  707. }
  708. if (!file_exists($filePath)) {
  709. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  710. return null;
  711. }
  712. // 验证是否为图片文件
  713. $imageInfo = @getimagesize($filePath);
  714. if ($imageInfo === false) {
  715. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  716. return null;
  717. }
  718. // 读取图片并转换为base64
  719. $imageData = file_get_contents($filePath);
  720. $base64Image = base64_encode($imageData);
  721. dLog('deepseek')->info('图片转换成功', [
  722. 'size' => strlen($imageData),
  723. 'type' => $imageInfo['mime']
  724. ]);
  725. return $base64Image;
  726. } catch (\Exception $e) {
  727. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  728. return null;
  729. }
  730. }
  731. private function getArtStylePromptMappings($art_style='')
  732. {
  733. $arr = [
  734. '唯美真人风格' => [
  735. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  736. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  737. ],
  738. '真人古风风格' => [
  739. 'aliases' => ['真人古风风格', '真人古风'],
  740. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  741. ],
  742. '日系动漫风格' => [
  743. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  744. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  745. ],
  746. '国漫风格' => [
  747. 'aliases' => ['国漫风格', '国漫'],
  748. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  749. ],
  750. 'Q版卡通风格' => [
  751. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  752. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  753. ],
  754. '简约扁平风格' => [
  755. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  756. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  757. ],
  758. '武侠风格' => [
  759. 'aliases' => ['武侠风格', '武侠'],
  760. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  761. ],
  762. '古风仙侠风格' => [
  763. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  764. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  765. ],
  766. '新中式水墨风格' => [
  767. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  768. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  769. ],
  770. '写实插画风格' => [
  771. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  772. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  773. ],
  774. '3D卡通风格' => [
  775. 'aliases' => ['3D卡通风格', '3D卡通'],
  776. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  777. ],
  778. '条漫风格' => [
  779. 'aliases' => ['条漫风格', '条漫'],
  780. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  781. ],
  782. '赛博朋克风格' => [
  783. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  784. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  785. ],
  786. '暗黑悬疑风格' => [
  787. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  788. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  789. ],
  790. '治愈清新风格' => [
  791. 'aliases' => ['治愈清新风格', '治愈清新'],
  792. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  793. ],
  794. '3D真人风格' => [
  795. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  796. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  797. ],
  798. ];
  799. if($art_style) {
  800. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  801. }
  802. return $arr;
  803. $arr = [
  804. '唯美真人风格' => [
  805. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  806. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  807. 2. 色彩色调
  808. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  809. 3. 画质精度
  810. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  811. 4. 画面观感
  812. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  813. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  814. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  815. ],
  816. '真人古风风格' => [
  817. 'aliases' => ['真人古风风格', '真人古风'],
  818. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  819. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  820. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  821. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  822. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  823. ],
  824. '日系动漫风格' => [
  825. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  826. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  827. 正向提示词(中文)
  828. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  829. 必须遵守规则
  830. • 全程保持日系动漫风格,不混入其他画风
  831. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  832. • 画面适配所选画面比例,构图居中,主体突出
  833. • 线条干净、色彩统一,不杂乱、不突兀
  834. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  835. ],
  836. '国漫风格' => [
  837. 'aliases' => ['国漫风格', '国漫'],
  838. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  839. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  840. 必须遵守规则
  841. • 严格保持国漫画风,不串风格、不混画风
  842. • 角色形象统一,不随意改变五官、身材、服饰
  843. • 画面构图稳定,适合漫剧叙事展示
  844. • 色调统一,不出现脏色、杂色
  845. 禁止/避免词汇
  846. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  847. ],
  848. 'Q版卡通风格' => [
  849. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  850. 'prompt' => "风格说明
  851. 头大身小,造型可爱圆润,简约干净
  852. 正向提示词(中文)
  853. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  854. 必须遵守规则
  855. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  856. • 角色造型统一,表情可爱,不诡异
  857. • 画面简洁清爽,无多余复杂元素
  858. • 色彩明亮柔和,不刺眼
  859. 禁止/避免词汇
  860. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  861. ],
  862. '简约扁平风格' => [
  863. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  864. 'prompt' => "风格说明
  865. 色块简洁、无复杂渐变,现代极简风
  866. 正向提示词(中文)
  867. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  868. 必须遵守规则
  869. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  870. • 构图简洁,主体突出,无多余装饰
  871. • 色彩统一、干净,不杂乱
  872. 禁止/避免词汇
  873. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  874. ],
  875. '武侠风格' => [
  876. 'aliases' => ['武侠风格', '武侠'],
  877. 'prompt' => "风格说明
  878. 江湖气息,线条硬朗,动作感强
  879. 正向提示词(中文)
  880. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  881. 必须遵守规则
  882. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  883. • 角色形象、服饰、身材比例统一
  884. • 画面动作自然,不扭曲、不畸形
  885. 禁止/避免词汇
  886. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  887. ],
  888. '古风仙侠风格' => [
  889. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  890. 'prompt' => "风格说明
  891. 飘逸汉服、云雾仙气、唯美空灵
  892. 正向提示词(中文)
  893. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  894. 必须遵守规则
  895. • 保持古风仙侠统一画风,不混入现代、科幻元素
  896. • 角色服饰、发型、形象前后一致
  897. • 场景仙气飘逸,色调清雅统一
  898. • 画面唯美柔和,不阴暗、不诡异
  899. 禁止/避免词汇
  900. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  901. ],
  902. '新中式水墨风格' => [
  903. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  904. 'prompt' => "风格说明
  905. 淡墨渲染,毛笔笔触,留白意境
  906. 正向提示词(中文)
  907. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  908. 必须遵守规则
  909. • 严格保持水墨质感,不混入厚涂、写实、卡通
  910. • 色调淡雅统一,不浓艳杂乱
  911. • 画面干净有意境,不堆砌元素
  912. 禁止/避免词汇
  913. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  914. ],
  915. '写实插画风格' => [
  916. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  917. 'prompt' => "风格说明
  918. 接近真人比例,光影真实,质感细腻
  919. 正向提示词(中文)
  920. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  921. 必须遵守规则
  922. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  923. • 角色五官、身材、服饰高度统一
  924. • 画面清晰、光影自然、不扭曲
  925. 禁止/避免词汇
  926. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  927. ],
  928. '3D卡通风格' => [
  929. 'aliases' => ['3D卡通风格', '3D卡通'],
  930. 'prompt' => "风格说明
  931. 3D建模质感,柔和渲染,圆润可爱
  932. 正向提示词(中文)
  933. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  934. 必须遵守规则
  935. • 保持3D卡通统一质感,不出现2D杂乱线条
  936. • 角色模型、比例、形象前后一致
  937. • 画面干净,不模糊、不穿模
  938. 禁止/避免词汇
  939. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  940. ],
  941. '条漫风格' => [
  942. 'aliases' => ['条漫风格', '条漫'],
  943. 'prompt' => "风格说明
  944. 纵向分镜,上下滑动阅读,轻量化
  945. 正向提示词(中文)
  946. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  947. 必须遵守规则
  948. • 保持条漫纵向阅读逻辑,构图简洁
  949. • 画风统一,不混写实、3D、水墨
  950. • 画面干净,不杂乱
  951. 禁止/避免词汇
  952. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  953. ],
  954. '赛博朋克风格' => [
  955. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  956. 'prompt' => "风格说明
  957. 霓虹灯光、未来都市、暗色调、科技机械
  958. 正向提示词(中文)
  959. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  960. 必须遵守规则
  961. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  962. • 色调以暗调+霓虹为主,色彩统一
  963. • 画面科技感强,不杂乱
  964. 禁止/避免词汇
  965. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  966. ],
  967. '暗黑悬疑风格' => [
  968. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  969. 'prompt' => "风格说明
  970. 低饱和、冷色调、阴影重、神秘压抑
  971. 正向提示词(中文)
  972. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  973. 必须遵守规则
  974. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  975. • 画面氛围压抑神秘,但不低俗、不血腥
  976. • 角色形象统一,不崩坏
  977. 禁止/避免词汇
  978. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  979. ],
  980. '治愈清新风格' => [
  981. 'aliases' => ['治愈清新风格', '治愈清新'],
  982. 'prompt' => "风格说明
  983. 马卡龙色系、柔光、温暖干净
  984. 正向提示词(中文)
  985. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  986. 必须遵守规则
  987. • 保持治愈清新统一色调,不阴暗、不诡异
  988. • 画面柔和干净,无杂乱元素
  989. • 角色形象柔和可爱,不狰狞
  990. 禁止/避免词汇
  991. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  992. ],
  993. ];
  994. return $arr;
  995. }
  996. public function getArtStylePromptByInput($inputArtStyle): string
  997. {
  998. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  999. if ($normalizedInput === '') {
  1000. return '';
  1001. }
  1002. return $this->getArtStylePromptMappings($normalizedInput);
  1003. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  1004. // foreach ($mapping['aliases'] as $alias) {
  1005. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  1006. // if ($normalizedAlias === '') {
  1007. // continue;
  1008. // }
  1009. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  1010. // return $mapping['prompt'];
  1011. // }
  1012. // }
  1013. // }
  1014. return '';
  1015. }
  1016. public function getArtStyleShortPromptByInput($inputArtStyle) {
  1017. $stylePrefixes = [
  1018. '唯美真人风格' => [
  1019. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  1020. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  1021. ],
  1022. '真人古风风格' => [
  1023. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  1024. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  1025. ],
  1026. '日系动漫风格' => [
  1027. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  1028. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  1029. ],
  1030. '国漫风格' => [
  1031. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  1032. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  1033. ],
  1034. 'Q版卡通风格' => [
  1035. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  1036. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  1037. ],
  1038. '简约扁平风格' => [
  1039. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  1040. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  1041. ],
  1042. '武侠风格' => [
  1043. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  1044. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  1045. ],
  1046. '古风仙侠风格' => [
  1047. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  1048. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  1049. ],
  1050. '新中式水墨风格' => [
  1051. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  1052. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  1053. ],
  1054. '写实插画风格' => [
  1055. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  1056. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  1057. ],
  1058. '3D卡通风格' => [
  1059. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  1060. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  1061. ],
  1062. '条漫风格' => [
  1063. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  1064. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  1065. ],
  1066. '赛博朋克风格' => [
  1067. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  1068. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  1069. ],
  1070. '暗黑悬疑风格' => [
  1071. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  1072. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  1073. ],
  1074. '治愈清新风格' => [
  1075. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  1076. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  1077. ]
  1078. ];
  1079. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  1080. }
  1081. private function normalizeArtStyleInput($value): string
  1082. {
  1083. $value = trim((string)$value);
  1084. if ($value === '') {
  1085. return '';
  1086. }
  1087. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  1088. return mb_strtolower($value, 'UTF-8');
  1089. }
  1090. private function replaceArtStyleSection(string $content, string $artStyle): string
  1091. {
  1092. if ($content === '' || $artStyle === '') {
  1093. return $content;
  1094. }
  1095. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  1096. if (!preg_match($pattern, $content)) {
  1097. return $content;
  1098. }
  1099. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  1100. }
  1101. /**
  1102. * DeepSeek流式输出处理方法
  1103. *
  1104. * @param array $post_data DeepSeek API请求参数
  1105. * @return \Generator 返回生成器,用于流式输出
  1106. */
  1107. private function deepSeekStreamResponse($post_data) {
  1108. // 设置最大输出tokens
  1109. $post_data['max_tokens'] = 300000;
  1110. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  1111. $post_data['stream_options'] = ['include_usage' => true];
  1112. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1113. $response = $client->post($this->url, [
  1114. 'json' => $post_data,
  1115. 'headers' => $this->headers,
  1116. 'stream' => true // 启用流式响应
  1117. ]);
  1118. $body = $response->getBody();
  1119. $fullContent = '';
  1120. $fullReasoningContent = '';
  1121. $usage = [];
  1122. $buffer = '';
  1123. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1124. // 逐行读取流式响应
  1125. while (!$body->eof()) {
  1126. $chunk = $body->read(1024); // 每次读取 1KB
  1127. $buffer .= $chunk;
  1128. // 按行分割
  1129. $lines = explode("\n", $buffer);
  1130. // 保留最后一个不完整的行
  1131. $buffer = array_pop($lines);
  1132. foreach ($lines as $line) {
  1133. $line = trim($line);
  1134. // 跳过空行
  1135. if (empty($line)) {
  1136. continue;
  1137. }
  1138. // 检查是否是 SSE 数据行
  1139. if (strpos($line, 'data: ') !== 0) {
  1140. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1141. continue;
  1142. }
  1143. $data = substr($line, 6); // 移除 "data: " 前缀
  1144. if ($data === '[DONE]') {
  1145. dLog('deepseek')->info('收到结束标记');
  1146. break 2; // 跳出两层循环
  1147. }
  1148. try {
  1149. $json = json_decode($data, true);
  1150. if (json_last_error() !== JSON_ERROR_NONE) {
  1151. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1152. continue;
  1153. }
  1154. if (isset($json['choices'][0]['delta'])) {
  1155. $delta = $json['choices'][0]['delta'];
  1156. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1157. if (isset($delta['reasoning_content'])) {
  1158. $fullReasoningContent .= $delta['reasoning_content'];
  1159. yield [
  1160. 'type' => 'reasoning',
  1161. 'content' => $delta['reasoning_content'],
  1162. 'full_reasoning' => $fullReasoningContent
  1163. ];
  1164. }
  1165. // 处理最终回答内容
  1166. if (isset($delta['content'])) {
  1167. $fullContent .= $delta['content'];
  1168. yield [
  1169. 'type' => 'content',
  1170. 'content' => $delta['content'],
  1171. ];
  1172. }
  1173. }
  1174. // 获取使用统计信息
  1175. if (isset($json['usage'])) {
  1176. $usage = $json['usage'];
  1177. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1178. }
  1179. } catch (\Exception $e) {
  1180. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1181. continue;
  1182. }
  1183. }
  1184. }
  1185. dLog('deepseek')->info('流式读取完成', [
  1186. 'content_length' => strlen($fullContent),
  1187. 'reasoning_length' => strlen($fullReasoningContent)
  1188. ]);
  1189. yield [
  1190. 'type' => 'done',
  1191. 'full_content' => $fullContent,
  1192. 'full_reasoning' => $fullReasoningContent,
  1193. 'usage' => $usage
  1194. ];
  1195. }
  1196. /**
  1197. * GPT 流式输出处理方法
  1198. *
  1199. * @param array $post_data GPT API请求参数
  1200. * @return \Generator 返回生成器,用于流式输出
  1201. */
  1202. private function gpt54StreamResponse($post_data) {
  1203. $apiKey = env('GPT_54_API_KEY');
  1204. if (empty($apiKey)) {
  1205. Utils::throwError('20003:GPT API Key未配置');
  1206. }
  1207. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1208. $headers = [
  1209. 'Authorization' => 'Bearer ' . $apiKey,
  1210. 'Content-Type' => 'application/json'
  1211. ];
  1212. // 移除 thinking 参数,GPT-5.4 不支持
  1213. if (isset($post_data['thinking'])) {
  1214. unset($post_data['thinking']);
  1215. }
  1216. if (isset($post_data['reasoning_effort'])) {
  1217. unset($post_data['reasoning_effort']);
  1218. }
  1219. $post_data['max_completion_tokens'] = 100000;
  1220. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  1221. $post_data['stream_options'] = ['include_usage' => true];
  1222. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  1223. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  1224. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  1225. 'json' => $post_data,
  1226. 'headers' => $headers,
  1227. 'stream' => true // 启用流式响应
  1228. ]);
  1229. $body = $response->getBody();
  1230. $fullContent = '';
  1231. $usage = [];
  1232. $buffer = '';
  1233. dLog('deepseek')->info('开始读取 GPT 流式响应');
  1234. // 逐行读取流式响应
  1235. while (!$body->eof()) {
  1236. $chunk = $body->read(1024); // 每次读取 1KB
  1237. $buffer .= $chunk;
  1238. // 按行分割
  1239. $lines = explode("\n", $buffer);
  1240. // 保留最后一个不完整的行
  1241. $buffer = array_pop($lines);
  1242. foreach ($lines as $line) {
  1243. $line = trim($line);
  1244. // 跳过空行
  1245. if (empty($line)) {
  1246. continue;
  1247. }
  1248. // 检查是否是 SSE 数据行
  1249. if (strpos($line, 'data: ') !== 0) {
  1250. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1251. continue;
  1252. }
  1253. $data = substr($line, 6); // 移除 "data: " 前缀
  1254. if ($data === '[DONE]') {
  1255. dLog('deepseek')->info('收到结束标记');
  1256. break 2; // 跳出两层循环
  1257. }
  1258. try {
  1259. $json = json_decode($data, true);
  1260. if (json_last_error() !== JSON_ERROR_NONE) {
  1261. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1262. continue;
  1263. }
  1264. if (isset($json['choices'][0]['delta'])) {
  1265. $delta = $json['choices'][0]['delta'];
  1266. // 处理回答内容
  1267. if (isset($delta['content'])) {
  1268. $fullContent .= $delta['content'];
  1269. yield [
  1270. 'type' => 'content',
  1271. 'content' => $delta['content'],
  1272. ];
  1273. }
  1274. }
  1275. // 获取使用统计信息
  1276. if (isset($json['usage'])) {
  1277. $usage = $json['usage'];
  1278. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1279. }
  1280. } catch (\Exception $e) {
  1281. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1282. continue;
  1283. }
  1284. }
  1285. }
  1286. dLog('deepseek')->info('流式读取完成', [
  1287. 'content_length' => strlen($fullContent)
  1288. ]);
  1289. yield [
  1290. 'type' => 'done',
  1291. 'full_content' => $fullContent,
  1292. 'full_reasoning' => '',
  1293. 'usage' => $usage
  1294. ];
  1295. }
  1296. // 与推理模型对话
  1297. public function chatWithReasoner($data) {
  1298. $content = getProp($data, 'content');
  1299. $model = getProp($data, 'model', 'r1');
  1300. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1301. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1302. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1303. if ($model == 'r1') {
  1304. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  1305. $thinkingMode = 'disabled';
  1306. } else {
  1307. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  1308. $thinkingMode = 'disabled';
  1309. }
  1310. // 获取可选情感(根据音色可支持情感选)
  1311. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  1312. $emotion_list = [];
  1313. foreach ($timbre_emotion as $emotion) {
  1314. $tmp = explode(',', $emotion);
  1315. $emotion_list = array_merge($emotion_list, $tmp);
  1316. }
  1317. $emotion_list = array_unique($emotion_list);
  1318. $emotion_str = implode('、', $emotion_list);
  1319. // // 获取可选情感
  1320. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  1321. // $emotion_str = implode('、', $emotion_list);
  1322. // 是否启用情感
  1323. $enable_emotion = getProp($data, 'enable_emotion', 0);
  1324. if ($enable_emotion) {
  1325. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  1326. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1327. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  1328. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  1329. }else {
  1330. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  1331. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1332. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  1333. }
  1334. $messages = [
  1335. [
  1336. 'role' => 'system',
  1337. 'content' => $sys_content
  1338. ],
  1339. [
  1340. 'role' => 'user',
  1341. 'content' => $content
  1342. ]
  1343. ];
  1344. $post_data = [
  1345. 'model' => $model,
  1346. 'messages' => $messages,
  1347. // 'max_tokens' => 8192,
  1348. 'temperature' => 1,
  1349. 'frequency_penalty' => 0,
  1350. 'presence_penalty' => 0,
  1351. 'thinking' => ['type' => $thinkingMode],
  1352. 'response_format' => [
  1353. 'type' => 'text'
  1354. ],
  1355. 'stream' => false
  1356. ];
  1357. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1358. // 根据模型类型选择调用方法
  1359. $fullContent = '';
  1360. $usage = [];
  1361. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1362. // DeepSeek 官方模型使用 DeepSeek API
  1363. $chatResult = $this->chatOnly($post_data);
  1364. } else if (in_array($model, $this->gpt_text_models)) {
  1365. // GPT-5.4 模型使用 TokenRouter API
  1366. $chatResult = $this->gpt54ChatOnly($post_data);
  1367. } else {
  1368. // 其他模型使用火山引擎API
  1369. $chatResult = $this->volcEngineChatCompletion($post_data);
  1370. }
  1371. if (is_array($chatResult)) {
  1372. $fullContent = $chatResult['fullContent'];
  1373. $usage = $chatResult['usage'];
  1374. }
  1375. // 处理获取到的剧本数据
  1376. $script_content = handleScriptWords($fullContent, $enable_emotion);
  1377. $result = [
  1378. 'origin_content' => $fullContent,
  1379. 'roles' => getProp($script_content, 'roles'),
  1380. 'words' => getProp($script_content, 'words'),
  1381. ];
  1382. return $result;
  1383. }
  1384. public function resetParagraphAudio($data) {
  1385. $bid = getProp($data, 'bid');
  1386. $cid = getProp($data, 'cid');
  1387. $version_id = getProp($data, 'version_id');
  1388. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  1389. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  1390. 'generate_status' => '待制作',
  1391. 'updated_at' => date('Y-m-d H:i:s')
  1392. ]);
  1393. }
  1394. public function saveParagraphAudio($data) {
  1395. $bid = getProp($data, 'bid');
  1396. $cid = getProp($data, 'cid');
  1397. $version_id = getProp($data, 'version_id');
  1398. $sequence = getProp($data, 'sequence');
  1399. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  1400. // 获取所有情感
  1401. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1402. $emotion_list = array_flip($emotion_list);
  1403. // 获取音色支持情感
  1404. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  1405. $timbre_emotion = explode(',', $timbre_emotion);
  1406. $emotion = getProp($data, 'emotion');
  1407. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  1408. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  1409. $list = [
  1410. 'bid' => $bid,
  1411. 'cid' => $cid,
  1412. 'version_id' => $version_id,
  1413. 'sequence' => $sequence,
  1414. 'role' => getProp($data, 'role'),
  1415. 'gender' => getProp($data, 'gender'),
  1416. 'text' => trim(getProp($data, 'text')),
  1417. 'emotion' => $emotion,
  1418. 'emotion_type' => $emotion_type,
  1419. 'voice_type' => getProp($data, 'voice_type'),
  1420. 'voice_name' => getProp($data, 'voice_name'),
  1421. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  1422. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  1423. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  1424. 'pitch' => getProp($data, 'pitch', 0),
  1425. // 'paragraph_audio_url' => '',
  1426. 'generate_status' => '制作中',
  1427. 'error_msg' => '',
  1428. 'updated_at' => date('Y-m-d H:i:s')
  1429. ];
  1430. $continue = false;
  1431. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  1432. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  1433. $list['generate_status'] = '制作成功';
  1434. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1435. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  1436. $continue = true;
  1437. }
  1438. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  1439. if ($id) {
  1440. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  1441. }else {
  1442. $list['created_at'] = date('Y-m-d H:i:s');
  1443. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  1444. $boolen = $id ? true : false;
  1445. }
  1446. // 如果更新成功则加入查询队列
  1447. if ($boolen) {
  1448. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  1449. Redis::sadd($redis_key, $id);
  1450. }
  1451. if ($boolen && !$continue) {
  1452. $boolen = false;
  1453. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1454. // 根据ID通过API通知合成音频
  1455. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  1456. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  1457. $response = $result->getBody()->getContents();
  1458. $response_arr = json_decode($response, true);
  1459. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1460. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1461. Log::info('通知火山生成段落音频失败: '.$error_msg);
  1462. Utils::throwError('20003:通知火山生成段落音频失败');
  1463. }
  1464. $boolen = true;
  1465. }
  1466. return $boolen;
  1467. }
  1468. public function insertAudioEffect($data) {
  1469. $audio_id = getProp($data, 'audio_id');
  1470. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1471. $bid = getProp($chapter_audio, 'bid');
  1472. $version_id = getProp($chapter_audio, 'version_id');
  1473. $cid = getProp($chapter_audio, 'cid');
  1474. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1475. $audio_effect_json = getProp($data, 'audio_effect_json');
  1476. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  1477. try {
  1478. DB::beginTransaction();
  1479. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1480. if (!$count) {
  1481. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1482. }else {
  1483. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1484. }
  1485. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1486. 'audio_effect_status' => '添加中',
  1487. 'audio_effect_json' => $audio_effect_json,
  1488. 'updated_at' => date('Y-m-d H:i:s')
  1489. ]);
  1490. if (!$boolen1) {
  1491. DB::rollBack();
  1492. Utils::throwError('20003:更新生成数据失败');
  1493. }
  1494. $id = DB::table('mp_audio_tasks')->insertGetId([
  1495. 'audio_id' => $audio_id,
  1496. 'generate_status' => '执行中',
  1497. 'generate_json' => json_encode([], 256),
  1498. 'bid' => $bid,
  1499. 'book_name' => getProp($chapter_audio, 'book_name'),
  1500. 'version_id' => $version_id,
  1501. 'version_name' => getProp($chapter_audio, 'version_name'),
  1502. 'cid' => $cid,
  1503. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1504. 'task_name' => $task_name,
  1505. 'created_at' => date('Y-m-d H:i:s'),
  1506. 'updated_at' => date('Y-m-d H:i:s')
  1507. ]);
  1508. if (!$id) {
  1509. DB::rollBack();
  1510. Utils::throwError('20003:创建任务失败');
  1511. }
  1512. }catch (\Exception $e) {
  1513. DB::rollBack();
  1514. Utils::throwError('20003:'.$e->getMessage());
  1515. }
  1516. DB::commit();
  1517. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1518. // 根据ID通过API通知合成音频
  1519. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1520. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1521. $response = $result->getBody()->getContents();
  1522. $response_arr = json_decode($response, true);
  1523. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1524. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1525. Log::info('通知火山插入音效失败: '.$error_msg);
  1526. Utils::throwError('20003:通知火山插入音效失败');
  1527. }
  1528. return true;
  1529. }
  1530. public function insertBgm($data) {
  1531. $audio_id = getProp($data, 'audio_id');
  1532. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1533. $bid = getProp($chapter_audio, 'bid');
  1534. $version_id = getProp($chapter_audio, 'version_id');
  1535. $cid = getProp($chapter_audio, 'cid');
  1536. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1537. $bgm_json = getProp($data, 'bgm_json');
  1538. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1539. if (!$bgm_json) {
  1540. $bgm_json = getProp($data, 'audio_effect_json');
  1541. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1542. }
  1543. try {
  1544. DB::beginTransaction();
  1545. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1546. if (!$count) {
  1547. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1548. }else {
  1549. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1550. }
  1551. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1552. 'bgm_status' => '添加中',
  1553. 'bgm_json' => $bgm_json,
  1554. 'updated_at' => date('Y-m-d H:i:s')
  1555. ]);
  1556. if (!$boolen1) {
  1557. DB::rollBack();
  1558. Utils::throwError('20003:更新生成数据失败');
  1559. }
  1560. $id = DB::table('mp_audio_tasks')->insertGetId([
  1561. 'audio_id' => $audio_id,
  1562. 'generate_status' => '执行中',
  1563. 'generate_json' => json_encode([], 256),
  1564. 'bid' => $bid,
  1565. 'book_name' => getProp($chapter_audio, 'book_name'),
  1566. 'version_id' => $version_id,
  1567. 'version_name' => getProp($chapter_audio, 'version_name'),
  1568. 'cid' => $cid,
  1569. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1570. 'task_name' => $task_name,
  1571. 'created_at' => date('Y-m-d H:i:s'),
  1572. 'updated_at' => date('Y-m-d H:i:s')
  1573. ]);
  1574. if (!$id) {
  1575. DB::rollBack();
  1576. Utils::throwError('20003:创建任务失败');
  1577. }
  1578. }catch (\Exception $e) {
  1579. DB::rollBack();
  1580. Utils::throwError('20003:'.$e->getMessage());
  1581. }
  1582. DB::commit();
  1583. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1584. // 根据ID通过API通知合成音频
  1585. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1586. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1587. $response = $result->getBody()->getContents();
  1588. $response_arr = json_decode($response, true);
  1589. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1590. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1591. Log::info('通知火山插入bgm失败: '.$error_msg);
  1592. Utils::throwError('20003:通知火山插入bgm失败');
  1593. }
  1594. return true;
  1595. }
  1596. public function getParagraphAudios($data) {
  1597. $bid = getProp($data, 'bid');
  1598. $cid = getProp($data, 'cid');
  1599. $version_id = getProp($data, 'version_id');
  1600. $sequence = getProp($data, 'sequence');
  1601. // 获取已生成的音频
  1602. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  1603. if ($sequence) $query->where('sequence', $sequence);
  1604. $paragraph_audios = $query->orderBy('sequence')->get();
  1605. $result = [];
  1606. foreach($paragraph_audios as $item) {
  1607. $result[] = [
  1608. 'sequence' => getProp($item, 'sequence'),
  1609. 'role' => getProp($item, 'role'),
  1610. 'gender' => getProp($item, 'gender'),
  1611. 'text' => trim(getProp($item, 'text')),
  1612. 'emotion' => getProp($item, 'emotion'),
  1613. 'emotion_type' => getProp($item, 'emotion_type'),
  1614. 'voice_type' => getProp($item, 'voice_type'),
  1615. 'voice_name' => getProp($item, 'voice_name'),
  1616. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1617. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1618. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1619. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1620. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  1621. ];
  1622. }
  1623. return $result;
  1624. }
  1625. // 新增合成任务
  1626. public function addGenerateTask($data) {
  1627. $bid = getProp($data, 'bid');
  1628. $cid = getProp($data, 'cid');
  1629. $version_id = getProp($data, 'version_id');
  1630. $generate_json = getProp($data, 'generate_json');
  1631. // 获取已生成的音频
  1632. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  1633. $paragraph_list = [];
  1634. foreach($paragraph_audios as $item) {
  1635. $paragraph_list[getProp($item, 'sequence')] = [
  1636. 'role' => getProp($item, 'role'),
  1637. 'gender' => getProp($item, 'gender'),
  1638. 'text' => trim(getProp($item, 'text')),
  1639. 'emotion' => getProp($item, 'emotion'),
  1640. 'emotion_type' => getProp($item, 'emotion_type'),
  1641. 'voice_type' => getProp($item, 'voice_type'),
  1642. 'voice_name' => getProp($item, 'voice_name'),
  1643. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1644. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1645. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1646. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1647. ];
  1648. }
  1649. // 更新角色-音色信息
  1650. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  1651. $existed_role_info = json_decode($existed_role_info, true);
  1652. if (!$existed_role_info) $existed_role_info = [];
  1653. // 获取情感信息
  1654. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1655. $emotion_list = array_flip($emotion_list);
  1656. // 获取音色对应情感组
  1657. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  1658. $timbre_emotion_list = [];
  1659. foreach($timbre_emotions as $item) {
  1660. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  1661. }
  1662. // 构造生成音频的json
  1663. $words = json_decode($generate_json, true);
  1664. // 最终合成前的参数组
  1665. $mp_chapter_paragraph_audios = [];
  1666. $sequence = 1;
  1667. $complete_paragraph_sequences = [];
  1668. foreach($words as &$word) {
  1669. 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:参数格式有误');
  1670. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  1671. $role = getProp($word, 'role');
  1672. $word['gender'] = (int)$word['gender'];
  1673. // 判断音色对应情感是否支持,不支持则调整为中性
  1674. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  1675. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  1676. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  1677. if (isset($emotion_list[getProp($word, 'emotion')])) {
  1678. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  1679. }else {
  1680. $word['emotion'] = '中性';
  1681. $word['emotion_type'] = 'neutral';
  1682. }
  1683. $existed_role_info[$role] = [
  1684. 'timbre_type' => $word['voice_type'],
  1685. 'timbre_name' => $word['voice_name'],
  1686. 'emotion' => $word['emotion'],
  1687. 'emotion_type' => $word['emotion_type'],
  1688. 'speed_ratio' => $word['speed_ratio'],
  1689. 'loudness_ratio'=> $word['loudness_ratio'],
  1690. 'emotion_scale' => $word['emotion_scale'],
  1691. 'pitch' => $word['pitch']
  1692. ];
  1693. $word['paragraph_audio_url'] = '';
  1694. // 判断生成参数是否相同,相同则直接使用已生成的音频
  1695. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  1696. // 如果音频存在并且参数都未改变则使用已生成的音频
  1697. if (getProp($paragraph, 'paragraph_audio_url')) {
  1698. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  1699. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  1700. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  1701. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  1702. // {
  1703. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1704. // }
  1705. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1706. }
  1707. $tmp = $word;
  1708. // 组装章节分句音频数据
  1709. // $tmp['sequence'] = getProp($word, 'sequence');
  1710. // $tmp['text'] = getProp($word, 'text');
  1711. // $tmp['emotion'] = getProp($word, 'emotion');
  1712. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  1713. // $tmp['voice_name'] = getProp($word, 'voice_name');
  1714. // $tmp['voice_type'] = getProp($word, 'voice_type');
  1715. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  1716. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  1717. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  1718. $tmp['bid'] = $bid;
  1719. $tmp['version_id'] = $version_id;
  1720. $tmp['cid'] = $cid;
  1721. $tmp['sequence'] = $sequence;
  1722. $tmp['created_at'] = date('Y-m-d H:i:s');
  1723. $tmp['updated_at'] = date('Y-m-d H:i:s');
  1724. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  1725. $mp_chapter_paragraph_audios[] = $tmp;
  1726. $complete_paragraph_sequences[] = $sequence;
  1727. $sequence++;
  1728. }
  1729. $generate_json = json_encode($words, 256);
  1730. // 判断是否有未生成字幕的段落
  1731. $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();
  1732. if ($no_subtitle_sequences) {
  1733. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  1734. }
  1735. try {
  1736. DB::beginTransaction();
  1737. $role_info = json_encode($existed_role_info, 256);
  1738. $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')]);
  1739. if (!$boolen) {
  1740. DB::rollBack();
  1741. Utils::throwError('20003:更新角色信息失败');
  1742. }
  1743. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  1744. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  1745. if (!$count) {
  1746. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1747. }else {
  1748. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1749. }
  1750. $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')]);
  1751. if (!$boolen1) {
  1752. DB::rollBack();
  1753. Utils::throwError('20003:更新生成数据失败');
  1754. }
  1755. $id = DB::table('mp_audio_tasks')->insertGetId([
  1756. 'audio_id' => getProp($chapter_audio, 'id'),
  1757. 'generate_status' => '执行中',
  1758. 'generate_json' => $generate_json,
  1759. 'bid' => $bid,
  1760. 'book_name' => getProp($chapter_audio, 'book_name'),
  1761. 'version_id' => $version_id,
  1762. 'version_name' => getProp($chapter_audio, 'version_name'),
  1763. 'cid' => $cid,
  1764. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1765. 'task_name' => $task_name,
  1766. 'created_at' => date('Y-m-d H:i:s'),
  1767. 'updated_at' => date('Y-m-d H:i:s')
  1768. ]);
  1769. if (!$id) {
  1770. DB::rollBack();
  1771. Utils::throwError('20003:创建任务失败');
  1772. }
  1773. // 删除不在段落序号范围内的其他数据
  1774. if ($complete_paragraph_sequences) {
  1775. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  1776. }
  1777. // // 删除章节分句音频数据并重新插入
  1778. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  1779. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  1780. // if (!$boolen3) {
  1781. // DB::rollBack();
  1782. // Utils::throwError('20003:更新章节分句音频失败');
  1783. // }
  1784. } catch (\Exception $e) {
  1785. DB::rollBack();
  1786. Utils::throwError('20003:'.$e->getMessage());
  1787. }
  1788. DB::commit();
  1789. // 通知火山生成音频
  1790. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1791. // 根据ID通过API通知合成音频
  1792. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  1793. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  1794. $response = $result->getBody()->getContents();
  1795. $response_arr = json_decode($response, true);
  1796. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1797. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1798. Log::info('通知火山生成音频失败: '.$error_msg);
  1799. Utils::throwError('20003:通知火山生成音频失败');
  1800. }
  1801. return true;
  1802. }
  1803. public function timbreList($data) {
  1804. $gender = getProp($data, 'gender');
  1805. $timbre_name = getProp($data, 'voice_name');
  1806. $category_id = getProp($data, 'category_id');
  1807. $age_stage = getProp($data, 'age_stage');
  1808. $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');
  1809. if ($gender) {
  1810. $query->where('gender', $gender);
  1811. }
  1812. if ($timbre_name) {
  1813. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  1814. }
  1815. if ($category_id) {
  1816. $query->where(function ($query) use ($category_id) {
  1817. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  1818. });
  1819. }
  1820. if ($age_stage) {
  1821. $query->where('age_stage', $age_stage);
  1822. }
  1823. $list = $query->get()->map(function ($value) {
  1824. $value = (array)$value;
  1825. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  1826. return $value;
  1827. })->toArray();
  1828. return $list;
  1829. }
  1830. // 生成火山临时token
  1831. public function setStsToken() {
  1832. // ************* 配置参数 *************
  1833. $method = 'GET';
  1834. $service = 'sts';
  1835. $host = 'open.volcengineapi.com';
  1836. $region = env('VOLC_REGION');
  1837. $endpoint = 'https://open.volcengineapi.com';
  1838. // $endpoint = 'https://tos-cn-beijing.volces.com';
  1839. $access_key = env('VOLC_AK');
  1840. $secret_key = env('VOLC_SK');
  1841. // 获取缓存中的token,如果没有则请求接口
  1842. $token = Redis::get('volc_sts_token');
  1843. if (!$token) {
  1844. // 查询参数
  1845. $query_parameters = [
  1846. 'Action' => 'AssumeRole',
  1847. 'RoleSessionName' => 'user@zw',
  1848. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  1849. 'Version' => '2018-01-01'
  1850. ];
  1851. // 生成URL编码的查询字符串
  1852. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  1853. // 获取签名头信息
  1854. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  1855. // 构建完整URL
  1856. $request_url = $endpoint . '?' . $request_parameters;
  1857. $client = new Client(['verify' => false]);
  1858. $response = $client->get($request_url, ['headers' => $headers]);
  1859. $response_arr = json_decode($response->getBody()->getContents(), true);
  1860. $result = [
  1861. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  1862. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  1863. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  1864. 'Region' => env('VOLC_REGION'),
  1865. 'Endpoint' => env('VOLC_END_POINT'),
  1866. 'Bucket' => env('VOLC_BUCKET'),
  1867. ];
  1868. // 缓存token
  1869. Redis::setex('volc_sts_token', 3000, json_encode($result));
  1870. return $result;
  1871. } else {
  1872. return json_decode($token, true);
  1873. }
  1874. // $response = $response['Response'];
  1875. // $access_key = $response['Credentials']['AccessKeyId'];
  1876. // $secret_key = $response['Credentials']['AccessKeySecret'];
  1877. // $security_token = $response['Credentials']['SecurityToken'];
  1878. // $expiration = $response['Credentials']['Expiration'];
  1879. // dd($response_arr);
  1880. }
  1881. public function emotionGroups($data) {
  1882. $id = getProp($data, 'group_id');
  1883. $group_name = getProp($data, 'group_name');
  1884. $voice_type = getProp($data, 'voice_type');
  1885. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  1886. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  1887. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  1888. if ($group_name) {
  1889. $query->where('group_name', 'like', "%{$group_name}%");
  1890. }
  1891. if ($id) {
  1892. $query->where('id', $id);
  1893. }
  1894. if ($voice_type) {
  1895. $query->where('voice_type', $voice_type);
  1896. }
  1897. return $query->orderBy('id')->get()->map(function ($value) {
  1898. return (array)$value;
  1899. })->toArray();
  1900. }
  1901. private function sign($key, $msg) {
  1902. return hash_hmac('sha256', $msg, $key, true);
  1903. }
  1904. // 生成签名密钥
  1905. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  1906. $kDate = $this->sign($key, $dateStamp);
  1907. $kRegion = $this->sign($kDate, $regionName);
  1908. $kService = $this->sign($kRegion, $serviceName);
  1909. $kSigning = $this->sign($kService, 'request');
  1910. return $kSigning;
  1911. }
  1912. // 获取签名头信息
  1913. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  1914. $contenttype = 'application/x-www-form-urlencoded';
  1915. $accept = 'application/json';
  1916. // 获取当前UTC时间
  1917. $t = new DateTime('now', new DateTimeZone('UTC'));
  1918. $xdate = $t->format('Ymd\THis\Z');
  1919. $datestamp = $t->format('Ymd');
  1920. // 1. 拼接规范请求串
  1921. $canonical_uri = '/';
  1922. $canonical_querystring = $request_parameters;
  1923. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  1924. $signed_headers = 'content-type;host;x-date';
  1925. // 空请求体的SHA256哈希
  1926. $payload_hash = hash('sha256', '');
  1927. $canonical_request = implode("\n", [
  1928. $method,
  1929. $canonical_uri,
  1930. $canonical_querystring,
  1931. $canonical_headers,
  1932. $signed_headers,
  1933. $payload_hash
  1934. ]);
  1935. // 2. 拼接待签名字符串
  1936. $algorithm = 'HMAC-SHA256';
  1937. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  1938. $hashed_canonical_request = hash('sha256', $canonical_request);
  1939. $string_to_sign = implode("\n", [
  1940. $algorithm,
  1941. $xdate,
  1942. $credential_scope,
  1943. $hashed_canonical_request
  1944. ]);
  1945. // 3. 计算签名
  1946. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  1947. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  1948. // 4. 添加签名到请求头
  1949. $authorization_header = sprintf(
  1950. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  1951. $algorithm,
  1952. $access_key,
  1953. $credential_scope,
  1954. $signed_headers,
  1955. $signature
  1956. );
  1957. return [
  1958. 'Accept' => $accept,
  1959. 'Content-Type' => $contenttype,
  1960. 'X-Date' => $xdate,
  1961. 'Authorization' => $authorization_header
  1962. ];
  1963. }
  1964. // 文字合成语音(火山引擎)
  1965. public function tts($data) {
  1966. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  1967. $headers = [
  1968. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  1969. 'Content-Type' => 'application/json; charset=UTF-8'
  1970. ];
  1971. $post_data = [
  1972. 'app' => [
  1973. 'appid' => env('VOLC_APPID'),
  1974. 'token' => env('VOLC_TOKEN'),
  1975. 'cluster' => 'volcano_tts'
  1976. ],
  1977. 'user' => [
  1978. 'uid' => 'mp_audio'
  1979. ],
  1980. // 'audio' => [
  1981. // 'voice_type' =>
  1982. // ],
  1983. ];
  1984. }
  1985. public function scriptList($data) {
  1986. $uid = Site::getUid();
  1987. $script_id = getProp($data, 'script_id');
  1988. $script_name = getProp($data, 'script_name');
  1989. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  1990. if ($script_id) {
  1991. $query->where('id', $script_id);
  1992. }
  1993. if ($script_name) {
  1994. $query->where('script_name', 'like', "%{$script_name}%");
  1995. }
  1996. return $query->orderBy('created_at', 'desc')->paginate(12);
  1997. }
  1998. public function scripts($data) {
  1999. $uid = Site::getUid();
  2000. $script_id = getProp($data, 'script_id');
  2001. $script_name = getProp($data, 'script_name');
  2002. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  2003. if ($script_id) {
  2004. $query->where('id', $script_id);
  2005. }
  2006. if ($script_name) {
  2007. $query->where('script_name', 'like', "%{$script_name}%");
  2008. }
  2009. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  2010. return (array)$value;
  2011. })->toArray();
  2012. }
  2013. public function scriptInfo($data) {
  2014. $uid = Site::getUid();
  2015. $script_id = getProp($data, 'script_id');
  2016. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  2017. // ->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();
  2018. ->selectRaw('id as script_id, script_name')->first();
  2019. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2020. $script = (array)$script;
  2021. // 获取分集组信息
  2022. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  2023. ->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')
  2024. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  2025. $value = (array)$value;
  2026. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  2027. return (array)$value;
  2028. })->toArray();
  2029. $script['group'] = $groups;
  2030. return $script;
  2031. }
  2032. public function createScript($data) {
  2033. $script_name = getProp($data, 'script_name');
  2034. $uid = Site::getUid(); // 获取当前用户ID
  2035. $cpid = Site::getCpid(); // 获取当前公司组ID
  2036. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  2037. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  2038. $script_name .= '_'.date('YmdHis');
  2039. }
  2040. return DB::table('mp_scripts')->insertGetId([
  2041. 'script_name' => $script_name,
  2042. 'user_id' => $uid,
  2043. 'cpid' => $cpid,
  2044. 'created_at' => date('Y-m-d H:i:s'),
  2045. 'updated_at' => date('Y-m-d H:i:s')
  2046. ]);
  2047. }
  2048. public function editScript($data) {
  2049. $script_id = getProp($data, 'script_id');
  2050. $script_name = getProp($data, 'script_name');
  2051. $uid = Site::getUid(); // 获取当前用户ID
  2052. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  2053. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  2054. if ($id && (int)$id !== (int)$script_id) {
  2055. $script_name .= '_'.date('YmdHis');
  2056. }
  2057. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2058. 'script_name' => $script_name,
  2059. 'updated_at' => date('Y-m-d H:i:s')
  2060. ]);
  2061. }
  2062. public function delScript($data) {
  2063. $script_id = getProp($data, 'script_id');
  2064. $uid = Site::getUid(); // 获取当前用户ID
  2065. if (!$script_id) Utils::throwError('20003:请选择剧本');
  2066. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2067. 'is_deleted' => 1,
  2068. 'updated_at' => date('Y-m-d H:i:s')
  2069. ]);
  2070. }
  2071. public function createEpisode($data) {
  2072. $script_id = getProp($data, 'script_id');
  2073. $group_name = getProp($data, 'group_name');
  2074. $remark = getProp($data, 'remark');
  2075. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  2076. $uid = Site::getUid(); // 获取当前用户ID
  2077. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  2078. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  2079. $group_name .= '_'.date('YmdHis');
  2080. }
  2081. return DB::table('mp_script_episode_group')->insertGetId([
  2082. 'script_id' => $script_id,
  2083. 'group_name' => $group_name,
  2084. 'user_id' => $uid,
  2085. 'remark' => $remark,
  2086. 'created_at' => date('Y-m-d H:i:s'),
  2087. 'updated_at' => date('Y-m-d H:i:s')
  2088. ]);
  2089. }
  2090. public function editEpisode($data) {
  2091. $group_id = getProp($data, 'group_id');
  2092. $start_episode_number = getProp($data, 'start_episode_number');
  2093. $end_episode_number = getProp($data, 'end_episode_number');
  2094. $group_name = getProp($data, 'group_name');
  2095. $uid = Site::getUid(); // 获取当前用户ID
  2096. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  2097. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  2098. if ($id && (int)$id !== (int)$group_id) {
  2099. $group_name .= '_'.date('YmdHis');
  2100. }
  2101. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2102. 'group_name' => $group_name,
  2103. 'start_episode_number' => $start_episode_number,
  2104. 'end_episode_number' => $end_episode_number,
  2105. 'updated_at' => date('Y-m-d H:i:s')
  2106. ]);
  2107. }
  2108. public function delEpisode($data) {
  2109. $group_id = getProp($data, 'group_id');
  2110. $uid = Site::getUid(); // 获取当前用户ID
  2111. if (!$group_id) Utils::throwError('20003:请选择分集');
  2112. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2113. 'is_deleted' => 1,
  2114. 'updated_at' => date('Y-m-d H:i:s')
  2115. ]);
  2116. }
  2117. /**
  2118. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2119. *
  2120. * @param array $data 包含以下参数:
  2121. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2122. * - question: 用户问题(可选)
  2123. * - model: 使用的模型(r1 或 v3,默认 v3)
  2124. * @return \Generator 返回生成器,用于流式输出
  2125. */
  2126. public function generateEpisodes($data) {
  2127. $script_id = getProp($data, 'script_id');
  2128. $group_id = getProp($data, 'group_id');
  2129. // $file = getProp($data, 'file');
  2130. $file = '';
  2131. $content = getProp($data, 'content', '');
  2132. // $bid = getProp($data, 'bid', 0);
  2133. $bid = 0;
  2134. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2135. if (!$group) {
  2136. Utils::throwError('20003:剧本分集不存在');
  2137. }
  2138. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  2139. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  2140. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  2141. $prompt = getProp($data, 'prompt');
  2142. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  2143. $model = getProp($data, 'model');
  2144. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2145. Utils::throwError('20003:该模型不存在!');
  2146. }
  2147. // 检查是否存在重叠的剧集序号范围
  2148. $exists_groups = DB::table('mp_script_episode_group')
  2149. ->where('script_id', $script_id)
  2150. ->where('id', '<>', $group_id) // 排除当前组
  2151. ->where('is_deleted', 0)
  2152. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2153. // 检查新范围是否与现有范围重叠
  2154. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2155. // 新范围的开始在现有范围内
  2156. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2157. ->where('end_episode_number', '>=', $start_episode_sequence);
  2158. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2159. // 新范围的结束在现有范围内
  2160. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2161. ->where('end_episode_number', '>=', $end_episode_sequence);
  2162. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2163. // 新范围完全包含现有范围
  2164. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2165. ->where('end_episode_number', '<=', $end_episode_sequence);
  2166. });
  2167. })
  2168. ->select('start_episode_number', 'end_episode_number')
  2169. ->get();
  2170. if ($exists_groups->isNotEmpty()) {
  2171. $conflict_ranges = [];
  2172. foreach ($exists_groups as $group) {
  2173. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2174. }
  2175. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2176. }
  2177. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2178. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2179. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2180. if ($model === 'deepseek-chat') {
  2181. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2182. $model = 'deepseek-v4-flash';
  2183. $thinkingMode = 'disabled';
  2184. } elseif ($model === 'deepseek-reasoner') {
  2185. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2186. $model = 'deepseek-v4-flash';
  2187. $thinkingMode = 'enabled';
  2188. }
  2189. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2190. if (!$script) {
  2191. Utils::throwError('20003:剧本不存在');
  2192. }
  2193. $content = getProp($group, 'content');
  2194. if (!$file && !$content && !$bid) {
  2195. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2196. }
  2197. // 提取文件内容
  2198. if ($file) {
  2199. $content = $this->extractFileContent($file);
  2200. if (!$content) {
  2201. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2202. }
  2203. } elseif ($bid) {
  2204. $content = $this->getContentByBid($bid);
  2205. if (!$content) {
  2206. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2207. }
  2208. } elseif ($content) {
  2209. $content = filterContent($content);
  2210. } elseif ($prompt) {
  2211. $content = filterContent($prompt);
  2212. } else {
  2213. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2214. }
  2215. // 构建消息
  2216. $messages = [
  2217. $this->sys_message,
  2218. [
  2219. 'role' => 'user',
  2220. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2221. ]
  2222. ];
  2223. $post_data = [
  2224. 'model' => $model,
  2225. 'messages' => $messages,
  2226. // 'max_tokens' => 8192,
  2227. 'temperature' => 0.7,
  2228. 'frequency_penalty' => 0,
  2229. 'presence_penalty' => 0,
  2230. 'thinking' => ['type' => $thinkingMode],
  2231. 'response_format' => ['type' => 'text'],
  2232. 'stream' => true
  2233. ];
  2234. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2235. // 根据模型类型选择调用方法
  2236. $fullContent = '';
  2237. $fullReasoningContent = '';
  2238. $usage = [];
  2239. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2240. // DeepSeek 官方模型使用 DeepSeek API
  2241. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2242. } else if (in_array($model, $this->gpt_text_models)) {
  2243. // GPT-5.4 模型使用 TokenRouter API
  2244. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2245. } else {
  2246. // 其他模型使用火山引擎API
  2247. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2248. }
  2249. // 处理流式输出
  2250. foreach ($streamGenerator as $chunk) {
  2251. if (isset($chunk['type'])) {
  2252. if ($chunk['type'] === 'done') {
  2253. // 最终结果
  2254. $fullContent = $chunk['full_content'];
  2255. $fullReasoningContent = $chunk['full_reasoning'];
  2256. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2257. } else {
  2258. // 逐块yield数据
  2259. yield $chunk;
  2260. }
  2261. }
  2262. }
  2263. dLog('deepseek')->info('完整内容: '.$fullContent);
  2264. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2265. // 处理完整内容并返回最终结果
  2266. $script_arr = [];
  2267. if ($fullContent) {
  2268. $script_arr = extractScriptContent($fullContent);
  2269. }
  2270. logDB('deepseek', 'info', '解析内容', $script_arr);
  2271. if (!$script_arr['episodes']) {
  2272. Utils::throwError('20003:未生成剧本相关信息');
  2273. // yield [
  2274. // 'type' => 'done',
  2275. // 'script' => $script_arr,
  2276. // 'msg' => '未生成剧本相关信息',
  2277. // 'answer' => $fullContent,
  2278. // 'reasoning' => $fullReasoningContent,
  2279. // 'usage' => $usage
  2280. // ];
  2281. // return ;
  2282. }
  2283. try {
  2284. DB::beginTransaction();
  2285. // // 返回前保存剧本内容
  2286. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2287. // 'content' => $content,
  2288. // 'updated_at' => date('Y-m-d H:i:s')
  2289. // ]);
  2290. // if (!$boolen) {
  2291. // Utils::throwError('20003:保存剧本内容失败');
  2292. // }
  2293. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2294. // 'start_episode_number' => $start_episode_sequence,
  2295. // 'end_episode_number' => $end_episode_sequence,
  2296. // 'updated_at' => date('Y-m-d H:i:s')
  2297. // ]);
  2298. // if (!$boolen1) {
  2299. // Utils::throwError('20003:保存分集失败');
  2300. // }
  2301. $episode_content = '';
  2302. $episodes = [];
  2303. foreach ($script_arr['episodes'] as $item) {
  2304. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  2305. // $episodes[] = [
  2306. // 'script_id' => $script_id,
  2307. // 'episode_number' => $item['episode_number'],
  2308. // 'episode_name' => $item['episode_name'],
  2309. // 'episode_content' => $item['episode_content'],
  2310. // 'created_at' => date('Y-m-d H:i:s'),
  2311. // 'updated_at' => date('Y-m-d H:i:s'),
  2312. // ];
  2313. }
  2314. if ($episode_content) {
  2315. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2316. 'episode_content' => $episode_content,
  2317. 'updated_at' => date('Y-m-d H:i:s')
  2318. ]);
  2319. if (!$boolen2) {
  2320. Utils::throwError('20003:保存分集内容失败');
  2321. }
  2322. }else {
  2323. Utils::throwError('20003:分集剧本解析失败');
  2324. }
  2325. }catch (\Exception $e) {
  2326. DB::rollBack();
  2327. Utils::throwError('20003:'.$e->getMessage());
  2328. }
  2329. DB::commit();
  2330. yield [
  2331. 'type' => 'done',
  2332. 'script' => $script_arr,
  2333. 'episode_content' => $episode_content,
  2334. 'answer' => $fullContent,
  2335. 'reasoning' => $fullReasoningContent,
  2336. 'usage' => $usage
  2337. ];
  2338. }
  2339. public function chatWithFileStream($data) {
  2340. $script_id = getProp($data, 'script_id');
  2341. $group_id = getProp($data, 'group_id');
  2342. $file = getProp($data, 'file');
  2343. $content = getProp($data, 'content', '');
  2344. $bid = getProp($data, 'bid', 0);
  2345. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2346. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2347. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  2348. $prompt = getProp($data, 'prompt');
  2349. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2350. if (!empty($prompt)) {
  2351. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2352. }
  2353. $question = getProp($data, 'question', $baseQuestion);
  2354. $model = getProp($data, 'model');
  2355. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2356. Utils::throwError('20003:该模型不存在!');
  2357. }
  2358. // 检查是否存在重叠的剧集序号范围
  2359. $exists_groups = DB::table('mp_script_episode_group')
  2360. ->where('script_id', $script_id)
  2361. ->where('id', '<>', $group_id)
  2362. ->where('is_deleted', 0)
  2363. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2364. // 检查新范围是否与现有范围重叠
  2365. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2366. // 新范围的开始在现有范围内
  2367. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2368. ->where('end_episode_number', '>=', $start_episode_sequence);
  2369. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2370. // 新范围的结束在现有范围内
  2371. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2372. ->where('end_episode_number', '>=', $end_episode_sequence);
  2373. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2374. // 新范围完全包含现有范围
  2375. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2376. ->where('end_episode_number', '<=', $end_episode_sequence);
  2377. });
  2378. })
  2379. ->select('start_episode_number', 'end_episode_number')
  2380. ->get();
  2381. if ($exists_groups->isNotEmpty()) {
  2382. $conflict_ranges = [];
  2383. foreach ($exists_groups as $group) {
  2384. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2385. }
  2386. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2387. }
  2388. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2389. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2390. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2391. if ($model === 'deepseek-chat') {
  2392. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2393. $model = 'deepseek-v4-flash';
  2394. $thinkingMode = 'disabled';
  2395. } elseif ($model === 'deepseek-reasoner') {
  2396. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2397. $model = 'deepseek-v4-flash';
  2398. $thinkingMode = 'enabled';
  2399. }
  2400. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2401. if (!$script) {
  2402. Utils::throwError('20003:剧本不存在');
  2403. }
  2404. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2405. if (!$group) {
  2406. Utils::throwError('20003:剧本分集不存在');
  2407. }
  2408. if (!$file && !$content && !$bid) {
  2409. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2410. }
  2411. // 提取文件内容
  2412. if ($file) {
  2413. $content = $this->extractFileContent($file);
  2414. if (!$content) {
  2415. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2416. }
  2417. } elseif ($bid) {
  2418. $content = $this->getContentByBid($bid);
  2419. if (!$content) {
  2420. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2421. }
  2422. } elseif ($content) {
  2423. $content = filterContent($content);
  2424. } elseif ($prompt) {
  2425. $content = filterContent($prompt);
  2426. } else {
  2427. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2428. }
  2429. // 构建消息
  2430. $messages = [
  2431. [
  2432. 'role' => 'system',
  2433. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  2434. 强制要求:\n
  2435. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2436. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  2437. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  2438. 普通要求:\n
  2439. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  2440. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  2441. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  2442. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  2443. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  2444. 示例如下:\n
  2445. ###剧本名:西昆仑
  2446. ###故事梗概
  2447. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2448. ###剧本亮点
  2449. 亮点1:绝境奇药,生死一线
  2450. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2451. 亮点2:结拜兄妹,化解尴尬
  2452. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2453. 亮点3:纤发夺命,情愫暗涌
  2454. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2455. ###人物关系
  2456. 阿雪与梁萧之间存在兄妹之情。
  2457. ###核心矛盾
  2458. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2459. ###主体列表
  2460. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2461. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2462. 阴阳球:天地异宝,能化生精气,救人于危难。
  2463. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2464. ###美术风格
  2465. 基础画风风格词:厚涂古风
  2466. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2467. ###场景列表
  2468. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  2469. [
  2470. 'role' => 'user',
  2471. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2472. ]
  2473. ];
  2474. $post_data = [
  2475. 'model' => $model,
  2476. 'messages' => $messages,
  2477. // 'max_tokens' => 8192,
  2478. 'temperature' => 0.7,
  2479. 'frequency_penalty' => 0,
  2480. 'presence_penalty' => 0,
  2481. 'thinking' => ['type' => $thinkingMode],
  2482. 'response_format' => ['type' => 'text'],
  2483. 'stream' => true
  2484. ];
  2485. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2486. // 根据模型类型选择调用方法
  2487. $fullContent = '';
  2488. $fullReasoningContent = '';
  2489. $usage = [];
  2490. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2491. // DeepSeek 官方模型使用 DeepSeek API
  2492. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2493. } else if (in_array($model, $this->gpt_text_models)) {
  2494. // GPT-5.4 模型使用 TokenRouter API
  2495. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2496. } else {
  2497. // 其他模型使用火山引擎API
  2498. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2499. }
  2500. // 处理流式输出
  2501. foreach ($streamGenerator as $chunk) {
  2502. if (isset($chunk['type'])) {
  2503. if ($chunk['type'] === 'done') {
  2504. // 最终结果
  2505. $fullContent = $chunk['full_content'];
  2506. $fullReasoningContent = $chunk['full_reasoning'];
  2507. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2508. } else {
  2509. // 逐块yield数据
  2510. yield $chunk;
  2511. }
  2512. }
  2513. }
  2514. dLog('deepseek')->info('完整内容: '.$fullContent);
  2515. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2516. // 处理完整内容并返回最终结果
  2517. $script_arr = [];
  2518. if ($fullContent) {
  2519. $script_arr = extractScriptContent($fullContent);
  2520. }
  2521. logDB('deepseek', 'info', '解析内容', $script_arr);
  2522. if (!$script_arr['roles']) {
  2523. Utils::throwError('20003:未生成剧本相关信息');
  2524. // yield [
  2525. // 'type' => 'done',
  2526. // 'script' => $script_arr,
  2527. // 'msg' => '未生成剧本相关信息',
  2528. // 'answer' => $fullContent,
  2529. // 'reasoning' => $fullReasoningContent,
  2530. // 'usage' => $usage
  2531. // ];
  2532. }
  2533. try {
  2534. DB::beginTransaction();
  2535. // // 返回前保存剧本内容
  2536. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2537. // 'content' => $content,
  2538. // 'status' => '解析完成',
  2539. // 'updated_at' => date('Y-m-d H:i:s')
  2540. // ]);
  2541. // if (!$boolen) {
  2542. // Utils::throwError('20003:保存剧本内容失败');
  2543. // }
  2544. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2545. 'start_episode_number' => $start_episode_sequence,
  2546. 'end_episode_number' => $end_episode_sequence,
  2547. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2548. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2549. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2550. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2551. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2552. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2553. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2554. 'status' => '解析完成',
  2555. 'content' => $content,
  2556. 'updated_at' => date('Y-m-d H:i:s')
  2557. ]);
  2558. if (!$boolen1) {
  2559. Utils::throwError('20003:保存分集失败');
  2560. }
  2561. // $episodes = [];
  2562. // foreach ($script_arr['episodes'] as $item) {
  2563. // $episodes[] = [
  2564. // 'script_id' => $script_id,
  2565. // 'episode_number' => $item['episode_number'],
  2566. // 'episode_name' => $item['episode_name'],
  2567. // 'episode_content' => $item['episode_content'],
  2568. // 'created_at' => date('Y-m-d H:i:s'),
  2569. // 'updated_at' => date('Y-m-d H:i:s'),
  2570. // ];
  2571. // }
  2572. // if ($episodes) {
  2573. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2574. // if (!$boolen2) {
  2575. // Utils::throwError('20003:保存分集内容失败');
  2576. // }
  2577. // }else {
  2578. // Utils::throwError('20003:分集剧本解析失败');
  2579. // }
  2580. }catch (\Exception $e) {
  2581. DB::rollBack();
  2582. Utils::throwError('20003:'.$e->getMessage());
  2583. }
  2584. DB::commit();
  2585. yield [
  2586. 'type' => 'done',
  2587. 'script' => $script_arr,
  2588. 'answer' => $fullContent,
  2589. 'reasoning' => $fullReasoningContent,
  2590. 'usage' => $usage
  2591. ];
  2592. }
  2593. /**
  2594. * 上传文件识别文字内容并与 DeepSeek 进行对话
  2595. *
  2596. * @param array $data 包含以下参数:
  2597. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2598. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  2599. * - model: 使用的模型(r1 或 v3,默认 v3)
  2600. * @return array
  2601. */
  2602. public function chatWithFile($data) {
  2603. $script_id = getProp($data, 'script_id');
  2604. $file = getProp($data, 'file');
  2605. $content = getProp($data, 'content', '');
  2606. $bid = getProp($data, 'bid', 0);
  2607. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2608. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2609. $prompt = getProp($data, 'prompt');
  2610. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2611. if (!empty($prompt)) {
  2612. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2613. }
  2614. $question = getProp($data, 'question', $baseQuestion);
  2615. // 处理文本模型
  2616. $model = getProp($data, 'model');
  2617. if (!$model) {
  2618. // 用户没有输入,使用默认值
  2619. $model = 'doubao-seed-2-0-mini-260215';
  2620. }
  2621. // 验证模型是否在可用模型表中
  2622. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2623. $model = 'doubao-seed-2-0-mini-260215';
  2624. }
  2625. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2626. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2627. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2628. if ($model === 'deepseek-chat') {
  2629. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2630. $model = 'deepseek-v4-flash';
  2631. $thinkingMode = 'disabled';
  2632. } elseif ($model === 'deepseek-reasoner') {
  2633. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2634. $model = 'deepseek-v4-flash';
  2635. $thinkingMode = 'enabled';
  2636. }
  2637. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2638. if (!$script) {
  2639. Utils::throwError('20003:剧本不存在');
  2640. }
  2641. if (!$file && !$content && !$bid) {
  2642. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2643. }
  2644. // 提取文件内容
  2645. if ($file) {
  2646. $content = $this->extractFileContent($file);
  2647. if (!$content) {
  2648. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2649. }
  2650. } elseif ($bid) {
  2651. $content = $this->getContentByBid($bid);
  2652. if (!$content) {
  2653. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2654. }
  2655. } elseif ($content) {
  2656. $content = filterContent($content);
  2657. } elseif ($prompt) {
  2658. $content = filterContent($prompt);
  2659. } else {
  2660. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2661. }
  2662. // 构建消息
  2663. $messages = [
  2664. $this->sys_message,
  2665. [
  2666. 'role' => 'user',
  2667. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2668. ]
  2669. ];
  2670. $post_data = [
  2671. 'model' => $model,
  2672. 'messages' => $messages,
  2673. // 'max_tokens' => 8192,
  2674. 'temperature' => 0.7,
  2675. 'frequency_penalty' => 0,
  2676. 'presence_penalty' => 0,
  2677. 'thinking' => ['type' => $thinkingMode],
  2678. 'response_format' => ['type' => 'text'],
  2679. 'stream' => false
  2680. ];
  2681. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2682. // 根据模型类型选择调用方法
  2683. $fullContent = '';
  2684. $usage = [];
  2685. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2686. // DeepSeek 官方模型使用 DeepSeek API
  2687. $chatResult = $this->chatOnly($post_data);
  2688. } else if (in_array($model, $this->gpt_text_models)) {
  2689. // GPT-5.4 模型使用 TokenRouter API
  2690. $chatResult = $this->gpt54ChatOnly($post_data);
  2691. } else {
  2692. // 其他模型使用火山引擎API
  2693. $chatResult = $this->volcEngineChatCompletion($post_data);
  2694. }
  2695. if (is_array($chatResult)) {
  2696. $fullContent = $chatResult['fullContent'];
  2697. $usage = $chatResult['usage'];
  2698. }
  2699. $script_arr = [];
  2700. // 处理结果
  2701. if ($fullContent) {
  2702. $script_arr = extractScriptContent($fullContent);
  2703. }
  2704. // 返回前保存剧本内容
  2705. DB::table('mp_scripts')->where('id', $script_id)->update([
  2706. 'content' => $content,
  2707. 'updated_at' => date('Y-m-d H:i:s')
  2708. ]);
  2709. return [
  2710. 'script' => $script_arr,
  2711. 'answer' => $fullContent,
  2712. 'usage' => $usage
  2713. ];
  2714. }
  2715. public function getEpisodeContent($data) {
  2716. $group_id = getProp($data, 'group_id');
  2717. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  2718. }
  2719. public function saveEpisodeContent($data) {
  2720. $script_id = getProp($data, 'script_id');
  2721. $group_id = getProp($data, 'group_id');
  2722. $start_episode_sequence = getProp($data, 'start_episode_number');
  2723. $end_episode_sequence = getProp($data, 'end_episode_number');
  2724. // 检查是否存在重叠的剧集序号范围
  2725. $exists_groups = DB::table('mp_script_episode_group')
  2726. ->where('script_id', $script_id)
  2727. ->where('id', '<>', $group_id) // 排除当前组
  2728. ->where('is_deleted', 0)
  2729. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2730. // 检查新范围是否与现有范围重叠
  2731. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2732. // 新范围的开始在现有范围内
  2733. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2734. ->where('end_episode_number', '>=', $start_episode_sequence);
  2735. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2736. // 新范围的结束在现有范围内
  2737. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2738. ->where('end_episode_number', '>=', $end_episode_sequence);
  2739. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2740. // 新范围完全包含现有范围
  2741. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2742. ->where('end_episode_number', '<=', $end_episode_sequence);
  2743. });
  2744. })
  2745. ->select('start_episode_number', 'end_episode_number')
  2746. ->get();
  2747. if ($exists_groups->isNotEmpty()) {
  2748. $conflict_ranges = [];
  2749. foreach ($exists_groups as $group) {
  2750. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2751. }
  2752. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2753. }
  2754. $episode_content = getProp($data, 'episode_content');
  2755. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  2756. 'content' => $episode_content,
  2757. 'start_episode_number' => $start_episode_sequence,
  2758. 'end_episode_number' => $end_episode_sequence,
  2759. 'updated_at' => date('Y-m-d H:i:s')
  2760. ]);
  2761. $script_arr =getProp($data, 'script', []);
  2762. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  2763. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2764. $script_id = getProp($data, 'script_id');
  2765. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  2766. try {
  2767. DB::beginTransaction();
  2768. $update_data = [
  2769. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2770. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2771. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2772. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2773. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2774. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2775. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2776. 'status' => 3,
  2777. 'start_episode_sequence' => $start_episode_sequence,
  2778. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  2779. 'episode_num' => count($script_arr['episodes']),
  2780. 'updated_at' => date('Y-m-d H:i:s')
  2781. ];
  2782. // 保存剧本内容
  2783. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  2784. if (!$boolen) {
  2785. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  2786. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  2787. Utils::throwError('20003:剧本内容保存失败');
  2788. }
  2789. // 保存分集内容
  2790. // 删除历史分集内容
  2791. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  2792. $episodes = [];
  2793. $sequence = 1;
  2794. foreach ($script_arr['episodes'] as $episode) {
  2795. $segment_number = 1;
  2796. foreach($episode['segments'] as $segment) {
  2797. $episodes[] = [
  2798. 'script_id' => $script_id,
  2799. 'episode_number' => $episode['episode_number'],
  2800. 'title' => $episode['title'],
  2801. // 'content' => $episode['content'],
  2802. 'content' => '',
  2803. 'segment_number' => $segment_number,
  2804. 'segment_content' => $segment['segment_content'],
  2805. 'sequence' => $sequence,
  2806. 'created_at' => date('Y-m-d H:i:s'),
  2807. 'updated_at' => date('Y-m-d H:i:s')
  2808. ];
  2809. $sequence++;
  2810. $segment_number++;
  2811. }
  2812. }
  2813. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2814. if (!$boolen2) {
  2815. dLog('deepseek')->info('分集内容保存失败', $episodes);
  2816. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  2817. Utils::throwError('20003:分集内容保存失败');
  2818. }
  2819. } catch (\Exception $e) {
  2820. DB::rollBack();
  2821. Utils::throwError('20003:'.$e->getMessage());
  2822. }
  2823. DB::commit();
  2824. return true;
  2825. }
  2826. public function getBookContent($data) {
  2827. $bid = getProp($data, 'bid');
  2828. $start_sequence = getProp($data, 'start_sequence');
  2829. $end_sequence = getProp($data, 'end_sequence');
  2830. $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])
  2831. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  2832. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  2833. return $return_content;
  2834. }
  2835. public function exportScript($data) {
  2836. $filename = getProp($data, 'filename');
  2837. $script_id = getProp($data, 'script_id');
  2838. $group_id = getProp($data, 'group_id');
  2839. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  2840. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  2841. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2842. $script = (array)$script;
  2843. // 获取分集组信息
  2844. if ($group_id) {
  2845. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2846. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2847. ->get()->map(function($value) {
  2848. return (array)$value;
  2849. })->toArray();
  2850. }else {
  2851. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2852. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2853. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  2854. return (array)$value;
  2855. })->toArray();
  2856. }
  2857. if (!$groups) Utils::throwError('20003:分集不存在');
  2858. $script['group'] = $groups;
  2859. $export_type = getProp($data, 'export_type', 'txt');
  2860. // 生成文件名
  2861. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  2862. // 根据导出类型生成不同格式的文件
  2863. switch ($export_type) {
  2864. case 'txt':
  2865. return $this->exportScriptAsTxt($script, $filename);
  2866. case 'pdf':
  2867. return $this->exportScriptAsPdf($script, $filename);
  2868. default:
  2869. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  2870. }
  2871. }
  2872. /**
  2873. * 导出剧本为TXT格式
  2874. */
  2875. private function exportScriptAsTxt($script, $filename) {
  2876. // 构建TXT内容
  2877. $content = $this->buildScriptContent($script);
  2878. // 设置响应头,直接下载
  2879. header('Content-Type: text/plain; charset=utf-8');
  2880. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  2881. header('Content-Length: ' . strlen($content));
  2882. // 输出内容并结束
  2883. echo $content;
  2884. exit();
  2885. }
  2886. /**
  2887. * 导出剧本为PDF格式
  2888. */
  2889. private function exportScriptAsPdf($script, $filename) {
  2890. // 使用HTML转PDF的方式来更好地支持中文
  2891. $htmlContent = $this->buildScriptHtmlForPdf($script);
  2892. // 创建PDF实例
  2893. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  2894. // 设置文档信息
  2895. $pdf->SetCreator('剧本导出系统');
  2896. $pdf->SetAuthor('系统');
  2897. $pdf->SetTitle($script['script_name']);
  2898. $pdf->SetSubject('剧本导出');
  2899. // 设置边距
  2900. $pdf->SetMargins(15, 15, 15);
  2901. $pdf->SetAutoPageBreak(TRUE, 15);
  2902. // 添加页面
  2903. $pdf->AddPage();
  2904. // 注册并使用 simsun.ttf 字体
  2905. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  2906. // 使用HTML内容生成PDF
  2907. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  2908. // 直接输出PDF文件供下载
  2909. header('Content-Type: application/pdf');
  2910. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  2911. // 直接输出PDF内容
  2912. $pdf->Output($filename . '.pdf', 'D');
  2913. exit();
  2914. }
  2915. /**
  2916. * 构建用于PDF的HTML内容
  2917. */
  2918. private function buildScriptHtmlForPdf($script) {
  2919. $html = '<style>
  2920. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  2921. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  2922. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  2923. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  2924. .info { margin-bottom: 8px; }
  2925. .group { margin-bottom: 30px; page-break-inside: avoid; }
  2926. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  2927. .segment { margin-bottom: 10px; margin-left: 20px; }
  2928. .episode-content { white-space: pre-wrap; }
  2929. </style>';
  2930. // 标题
  2931. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  2932. // 处理分组数据
  2933. if (!empty($script['group']) && is_array($script['group'])) {
  2934. $groups = (array)$script['group'];
  2935. foreach ($groups as $group) {
  2936. $html .= '<div class="group">';
  2937. // 分组标题
  2938. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  2939. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  2940. // 故事梗概
  2941. if (!empty($group['intro'])) {
  2942. $html .= '<h3>故事梗概</h3>';
  2943. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  2944. }
  2945. // 剧本亮点
  2946. if (!empty($group['highlights'])) {
  2947. $html .= '<h3>剧本亮点</h3>';
  2948. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  2949. }
  2950. // 人物关系
  2951. if (!empty($group['role_relationship'])) {
  2952. $html .= '<h3>人物关系</h3>';
  2953. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  2954. }
  2955. // 核心矛盾
  2956. if (!empty($group['core_contradiction'])) {
  2957. $html .= '<h3>核心矛盾</h3>';
  2958. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  2959. }
  2960. // 主体列表
  2961. if (!empty($group['roles']) && is_array($group['roles'])) {
  2962. $html .= '<h3>主体列表</h3>';
  2963. $html .= '<ul>';
  2964. foreach ($group['roles'] as $role) {
  2965. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  2966. }
  2967. $html .= '</ul>';
  2968. }
  2969. // 美术风格
  2970. if (!empty($group['art_style'])) {
  2971. $html .= '<h3>美术风格</h3>';
  2972. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  2973. }
  2974. // 场景列表
  2975. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  2976. $html .= '<h3>场景列表</h3>';
  2977. $html .= '<ul>';
  2978. foreach ($group['scenes'] as $scene) {
  2979. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  2980. }
  2981. $html .= '</ul>';
  2982. }
  2983. // 分集剧本
  2984. if (!empty($group['episode_content'])) {
  2985. $html .= '<h3>分集剧本</h3>';
  2986. // 去除零宽字符和其他不可见字符
  2987. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  2988. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  2989. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  2990. }
  2991. $html .= '</div>';
  2992. }
  2993. }
  2994. return $html;
  2995. }
  2996. /**
  2997. * 构建PDF内容
  2998. */
  2999. private function buildPdfContent($pdf, $script) {
  3000. // 标题
  3001. $pdf->SetFont('dejavusans', 'B', 18);
  3002. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  3003. $pdf->Ln(5);
  3004. // 基本信息
  3005. $pdf->SetFont('dejavusans', '', 12);
  3006. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  3007. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  3008. $pdf->Ln(5);
  3009. // 剧本简介
  3010. if (!empty($script['intro'])) {
  3011. $pdf->SetFont('dejavusans', 'B', 14);
  3012. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  3013. $pdf->SetFont('dejavusans', '', 12);
  3014. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  3015. $pdf->Ln(3);
  3016. }
  3017. // 亮点
  3018. if (!empty($script['highlights'])) {
  3019. $pdf->SetFont('dejavusans', 'B', 14);
  3020. $pdf->Cell(0, 10, '亮点', 0, 1);
  3021. $pdf->SetFont('dejavusans', '', 12);
  3022. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  3023. $pdf->Ln(3);
  3024. }
  3025. // 核心矛盾
  3026. if (!empty($script['core_contradiction'])) {
  3027. $pdf->SetFont('dejavusans', 'B', 14);
  3028. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  3029. $pdf->SetFont('dejavusans', '', 12);
  3030. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  3031. $pdf->Ln(3);
  3032. }
  3033. // 艺术风格
  3034. if (!empty($script['art_style'])) {
  3035. $pdf->SetFont('dejavusans', 'B', 14);
  3036. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  3037. $pdf->SetFont('dejavusans', '', 12);
  3038. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  3039. $pdf->Ln(3);
  3040. }
  3041. // 备注
  3042. if (!empty($script['remark'])) {
  3043. $pdf->SetFont('dejavusans', 'B', 14);
  3044. $pdf->Cell(0, 10, '备注', 0, 1);
  3045. $pdf->SetFont('dejavusans', '', 12);
  3046. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  3047. $pdf->Ln(3);
  3048. }
  3049. // 角色列表
  3050. if (!empty($script['roles']) && is_array($script['roles'])) {
  3051. $pdf->SetFont('dejavusans', 'B', 14);
  3052. $pdf->Cell(0, 10, '角色列表', 0, 1);
  3053. $pdf->SetFont('dejavusans', '', 12);
  3054. foreach ($script['roles'] as $index => $role) {
  3055. if (is_array($role) || is_object($role)) {
  3056. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  3057. } else {
  3058. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  3059. }
  3060. }
  3061. $pdf->Ln(3);
  3062. }
  3063. // 角色关系
  3064. if (!empty($script['role_relationship'])) {
  3065. $pdf->SetFont('dejavusans', 'B', 14);
  3066. $pdf->Cell(0, 10, '角色关系', 0, 1);
  3067. $pdf->SetFont('dejavusans', '', 12);
  3068. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  3069. $pdf->Ln(3);
  3070. }
  3071. // 场景列表
  3072. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  3073. $pdf->SetFont('dejavusans', 'B', 14);
  3074. $pdf->Cell(0, 10, '场景列表', 0, 1);
  3075. $pdf->SetFont('dejavusans', '', 12);
  3076. foreach ($script['scenes'] as $index => $scene) {
  3077. if (is_array($scene) || is_object($scene)) {
  3078. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  3079. } else {
  3080. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  3081. }
  3082. }
  3083. $pdf->Ln(5);
  3084. }
  3085. // 分集内容
  3086. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  3087. $pdf->SetFont('dejavusans', 'B', 16);
  3088. $pdf->Cell(0, 12, '分集内容', 0, 1);
  3089. $pdf->Ln(3);
  3090. foreach ($script['episodes'] as $episode) {
  3091. // 检查是否需要新页面
  3092. if ($pdf->GetY() > 250) {
  3093. $pdf->AddPage();
  3094. }
  3095. $pdf->SetFont('dejavusans', 'B', 14);
  3096. $episodeTitle = '第' . $episode['episode_number'] . '集';
  3097. if (!empty($episode['title'])) {
  3098. $episodeTitle .= ':' . $episode['title'];
  3099. }
  3100. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  3101. // 处理分段内容
  3102. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  3103. $pdf->SetFont('dejavusans', '', 12);
  3104. foreach ($episode['segments'] as $segment) {
  3105. if (!empty($segment['segment_content'])) {
  3106. // 如果有分段编号,显示分段标题
  3107. if (!empty($segment['segment_number'])) {
  3108. $pdf->SetFont('dejavusans', 'B', 12);
  3109. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  3110. $pdf->SetFont('dejavusans', '', 12);
  3111. }
  3112. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  3113. $pdf->Ln(2);
  3114. }
  3115. }
  3116. }
  3117. $pdf->Ln(5);
  3118. }
  3119. }
  3120. }
  3121. /**
  3122. * 构建剧本文本内容
  3123. */
  3124. private function buildScriptContent($script) {
  3125. $content = '';
  3126. $groups = $script['group'];
  3127. $groups = (array)$groups;
  3128. foreach ($groups as $group) {
  3129. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  3130. // 剧本基本信息
  3131. if (!empty($group['intro'])) {
  3132. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  3133. }
  3134. if (!empty($group['highlights'])) {
  3135. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  3136. }
  3137. if (!empty($group['role_relationship'])) {
  3138. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  3139. }
  3140. if (!empty($group['core_contradiction'])) {
  3141. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  3142. }
  3143. if (!empty($group['roles']) && is_array($group['roles'])) {
  3144. $content .= "###主体列表\n";
  3145. foreach ($group['roles'] as $role) {
  3146. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  3147. }
  3148. $content .= "\n\n";
  3149. }
  3150. if (!empty($group['art_style'])) {
  3151. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  3152. }
  3153. // 场景信息
  3154. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3155. $content .= "###场景列表\n";
  3156. foreach ($group['scenes'] as $scene) {
  3157. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  3158. }
  3159. $content .= "\n\n";
  3160. }
  3161. // 分集内容
  3162. if (!empty($group['episode_content'])) {
  3163. $content .= "###分集剧本\n";
  3164. $content .= $group['episode_content'];
  3165. // foreach ($script['episodes'] as $episode) {
  3166. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  3167. // // if (!empty($episode['episode_name'])) {
  3168. // // $content .= ":" . $episode['episode_name'];
  3169. // // }
  3170. // // $content .= "\n";
  3171. // $content .= $episode['episode_content'] . "\n\n";
  3172. // }
  3173. }
  3174. }
  3175. return $content;
  3176. }
  3177. /**
  3178. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3179. *
  3180. * @param array $data 包含以下参数:
  3181. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3182. * - question: 用户问题(可选)
  3183. * - model: 使用的模型(r1 或 v3,默认 v3)
  3184. * @return \Generator 返回生成器,用于流式输出
  3185. */
  3186. public function addChat($data) {
  3187. $uid = Site::getUid();
  3188. $anime_id = getProp($data, 'anime_id');
  3189. if (!$anime_id) Utils::throwError('20003:请选择对话');
  3190. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3191. if (!$anime) Utils::throwError('20003:对话不存在');
  3192. $file = getProp($data, 'file');
  3193. $content = getProp($data, 'content', '');
  3194. $bid = getProp($data, 'bid', 0);
  3195. $script_id = getProp($data, 'script_id', 0);
  3196. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  3197. $prompt = getProp($data, 'prompt');
  3198. $user_anime_name = getProp($anime, 'anime_name');
  3199. // 处理文本模型
  3200. $model = getProp($data, 'model');
  3201. if (!$model) {
  3202. // 用户没有输入,从anime表获取
  3203. $model = getProp($anime, 'model');
  3204. if (!$model) {
  3205. // anime表也没有,使用默认值
  3206. $model = 'doubao-seed-2-0-mini-260215';
  3207. }
  3208. }
  3209. // 验证模型是否在可用模型表中
  3210. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3211. $model = 'doubao-seed-2-0-mini-260215';
  3212. }
  3213. $is_multi = getProp($anime, 'is_multi');
  3214. $is_single = (int)$is_multi !== 1;
  3215. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3216. if ($prompt) {
  3217. $question .= "本次修改要求如下:\n{$prompt}";
  3218. }
  3219. // if (!$file && !$content && !$bid) {
  3220. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3221. // }
  3222. // 提取文件内容
  3223. if ($file) {
  3224. $content = $this->extractFileContent($file);
  3225. if (!$content) {
  3226. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3227. }
  3228. } elseif ($script_id) {
  3229. $content = $this->getContentByScriptId($script_id);
  3230. if (!$content) {
  3231. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3232. }
  3233. } elseif ($bid) {
  3234. $content = $this->getContentByBid($bid);
  3235. if (!$content) {
  3236. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3237. }
  3238. } elseif ($content) {
  3239. $content = filterContent($content);
  3240. } else {
  3241. $content = getProp($anime, 'content');
  3242. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3243. $need_generate_content = true;
  3244. }
  3245. }
  3246. // 美术风格
  3247. $input_art_style = getProp($data, 'art_style');
  3248. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3249. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3250. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3251. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3252. 中年女:邻居阿姨
  3253. 老年男:幽默大爷
  3254. 老年女:婆婆
  3255. 萌娃:奶气萌娃";
  3256. // 判断是否需要生成原文内容
  3257. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3258. // 如果需要生成原文内容,添加额外的要求
  3259. $content_generation_requirement = $need_generate_content
  3260. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3261. : "";
  3262. // 美术风格
  3263. if (!$mappedArtStyle) {
  3264. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3265. }else {
  3266. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3267. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3268. }else {
  3269. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3270. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3271. }
  3272. }
  3273. $systemPrompt = $is_single
  3274. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3275. 强制要求:
  3276. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3277. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3278. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3279. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3280. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3281. 普通要求:
  3282. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3283. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3284. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  3285. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3286. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3287. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3288. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3289. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3290. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3291. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3292. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3293. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3294. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3295. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3296. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3297. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3298. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3299. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3300. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3301. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3302. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3303. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3304. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3305. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3306. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3307. 5.{$mappedArtStyle_prompt}\n\n
  3308. 示例如下:\n
  3309. ###剧本名:西昆仑
  3310. ###故事梗概
  3311. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3312. ###剧本亮点
  3313. 亮点1:绝境奇药,生死一线
  3314. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3315. 亮点2:结拜兄妹,化解尴尬
  3316. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3317. 亮点3:纤发夺命,情愫暗涌
  3318. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3319. ###人物关系
  3320. 阿雪与梁萧之间存在兄妹之情。
  3321. ###核心矛盾
  3322. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3323. ###主体列表
  3324. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3325. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3326. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3327. 姿态:站立。}{{甜心小美}}
  3328. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3329. 全景,正面拍摄,青年女性,亚洲人。
  3330. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3331. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3332. 姿态:站立。}{{阳光青年}}
  3333. ###美术风格
  3334. 基础画风风格词:厚涂古风
  3335. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3336. ###场景列表
  3337. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3338. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3339. 无人物。}
  3340. ###分镜剧本
  3341. ##第1幕:徐家老旧厨房 白天 室内
  3342. 分镜1
  3343. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3344. 场景:徐家老旧厨房
  3345. 构图设计:全景,低角度仰视
  3346. 运镜调度:手持拍摄
  3347. 配音角色:旁白
  3348. 出镜角色:许芸-校服装、徐母
  3349. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3350. 画面类型:普通画面
  3351. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3352. 分镜2
  3353. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3354. 场景:徐家老旧厨房
  3355. 构图设计:近景,徐母面部特写
  3356. 运镜调度:固定镜头
  3357. 配音角色:徐母
  3358. 出镜角色:徐母
  3359. 台词内容:问我夜不归宿死哪儿去了。
  3360. 画面类型:对口型
  3361. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3362. ##第2幕:徐家简陋客厅 黄昏 室内
  3363. 分镜3
  3364. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3365. 场景:徐家简陋客厅
  3366. 构图设计:全景,景深虚化
  3367. 运镜调度:固定镜头
  3368. 配音角色:旁白
  3369. 出镜角色:无
  3370. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3371. 画面类型:普通画面
  3372. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3373. 分镜4
  3374. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3375. 场景:徐家简陋客厅
  3376. 构图设计:特写,火车票
  3377. 运镜调度:固定镜头
  3378. 配音角色:旁白
  3379. 出镜角色:无
  3380. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3381. 画面类型:普通画面
  3382. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  3383. "
  3384. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3385. 强制要求:\n
  3386. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3387. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3388. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3389. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3390. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3391. 普通要求:\n
  3392. 1.剧本名(必须生成)必须与文档内容高度相关
  3393. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3394. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3395. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3396. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3397. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3398. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3399. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3400. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3401. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3402. 4.{$mappedArtStyle_prompt}\n\n
  3403. 示例如下:\n
  3404. ###剧本名:西昆仑
  3405. ###故事梗概
  3406. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3407. ###剧本亮点
  3408. 亮点1:绝境奇药,生死一线
  3409. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3410. 亮点2:结拜兄妹,化解尴尬
  3411. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3412. 亮点3:纤发夺命,情愫暗涌
  3413. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3414. ###人物关系
  3415. 阿雪与梁萧之间存在兄妹之情。
  3416. ###核心矛盾
  3417. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3418. ###主体列表
  3419. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3420. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3421. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3422. 姿态:站立。}{{甜心小美}}
  3423. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3424. 全景,正面拍摄,青年女性,亚洲人。
  3425. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3426. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3427. 姿态:站立。}{{阳光青年}}
  3428. ###美术风格
  3429. 基础画风风格词:厚涂古风
  3430. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3431. ###场景列表
  3432. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3433. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3434. 无人物。}";
  3435. // 构建消息
  3436. $messages = [
  3437. [
  3438. 'role' => 'system',
  3439. 'content' => $systemPrompt
  3440. ],
  3441. [
  3442. 'role' => 'user',
  3443. 'content' => "以下是文档内容:
  3444. {$content}
  3445. 用户问题:
  3446. {$question}"
  3447. ]
  3448. ];
  3449. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3450. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3451. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3452. if ($model === 'deepseek-chat') {
  3453. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3454. $model = 'deepseek-v4-flash';
  3455. $thinkingMode = 'disabled';
  3456. } elseif ($model === 'deepseek-reasoner') {
  3457. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3458. $model = 'deepseek-v4-flash';
  3459. $thinkingMode = 'enabled';
  3460. }
  3461. $post_data = [
  3462. 'model' => $model,
  3463. 'messages' => $messages,
  3464. // 'max_tokens' => 8192,
  3465. 'temperature' => 0.7,
  3466. 'frequency_penalty' => 0,
  3467. 'presence_penalty' => 0,
  3468. 'response_format' => ['type' => 'text'],
  3469. 'thinking' => ['type'=>$thinkingMode],
  3470. 'stream' => true // 启用流式输出
  3471. ];
  3472. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3473. // 根据模型类型选择调用方法
  3474. $fullContent = '';
  3475. $fullReasoningContent = '';
  3476. $usage = [];
  3477. try {
  3478. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3479. // DeepSeek 官方模型使用 DeepSeek API
  3480. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3481. } else if (in_array($model, $this->gpt_text_models)) {
  3482. // GPT-5.4 模型使用 TokenRouter API
  3483. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3484. } else {
  3485. // 其他模型使用火山引擎API
  3486. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3487. }
  3488. // 验证返回值类型
  3489. if (!is_iterable($streamGenerator)) {
  3490. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  3491. dLog('deepseek')->error('addChat流式生成器无效', [
  3492. 'generator_type' => $errorType,
  3493. 'model' => $model,
  3494. 'anime_id' => $anime_id
  3495. ]);
  3496. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  3497. 'type' => $errorType,
  3498. 'model' => $model
  3499. ]);
  3500. yield [
  3501. 'type' => 'error',
  3502. 'script' => [],
  3503. 'episode' => [],
  3504. 'answer' => '',
  3505. 'reasoning' => '',
  3506. 'usage' => [],
  3507. 'error' => '接口返回数据异常,请重新请求'
  3508. ];
  3509. return;
  3510. }
  3511. // 处理流式输出
  3512. foreach ($streamGenerator as $chunk) {
  3513. if (isset($chunk['type'])) {
  3514. if ($chunk['type'] === 'done') {
  3515. // 最终结果
  3516. $fullContent = $chunk['full_content'];
  3517. $fullReasoningContent = $chunk['full_reasoning'];
  3518. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3519. } else {
  3520. // 逐块yield数据
  3521. yield $chunk;
  3522. }
  3523. }
  3524. }
  3525. } catch (\Exception $e) {
  3526. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  3527. 'model' => $model,
  3528. 'anime_id' => $anime_id,
  3529. 'trace' => $e->getTraceAsString()
  3530. ]);
  3531. logDB('deepseek', 'error', 'addChat流式处理失败', [
  3532. 'error' => $e->getMessage(),
  3533. 'model' => $model
  3534. ]);
  3535. yield [
  3536. 'type' => 'error',
  3537. 'script' => [],
  3538. 'episode' => [],
  3539. 'answer' => '',
  3540. 'reasoning' => '',
  3541. 'usage' => [],
  3542. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  3543. ];
  3544. return;
  3545. }
  3546. dLog('deepseek')->info('完整内容: '.$fullContent);
  3547. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3548. // 处理完整内容并返回最终结果
  3549. $script_arr = [];
  3550. if ($fullContent) {
  3551. $script_arr = handleScriptContent($fullContent);
  3552. dLog('deepseek')->info('解析内容', $script_arr);
  3553. logDB('deepseek', 'info', '解析内容', $script_arr);
  3554. }
  3555. if (empty($script_arr['roles'])) {
  3556. // 未生成剧本相关内容,保存对话记录并返回提示
  3557. dLog('deepseek')->info('未生成剧本相关的内容');
  3558. try {
  3559. DB::beginTransaction();
  3560. $now = date('Y-m-d H:i:s');
  3561. // 保存对话记录
  3562. $records = [
  3563. [
  3564. 'uid' => $uid,
  3565. 'anime_id' => $anime_id,
  3566. 'sequence' => 0,
  3567. 'role' => 'user',
  3568. 'content' => $prompt,
  3569. 'created_at' => $now,
  3570. 'updated_at' => $now
  3571. ],
  3572. [
  3573. 'uid' => $uid,
  3574. 'anime_id' => $anime_id,
  3575. 'sequence' => 0,
  3576. 'role' => 'assistant',
  3577. // 'content' => $fullContent,
  3578. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  3579. 'created_at' => $now,
  3580. 'updated_at' => $now
  3581. ]
  3582. ];
  3583. DB::table('mp_anime_records')->insert($records);
  3584. DB::commit();
  3585. } catch (\Exception $e) {
  3586. DB::rollBack();
  3587. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3588. }
  3589. yield [
  3590. 'type' => 'done',
  3591. 'script' => [],
  3592. 'episode' => [],
  3593. 'answer' => $fullContent,
  3594. 'reasoning' => $fullReasoningContent,
  3595. 'usage' => $usage,
  3596. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  3597. ];
  3598. return;
  3599. }
  3600. // 如果需要生成原文内容,从script_arr中提取
  3601. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  3602. $content = $script_arr['content'];
  3603. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  3604. if (!$content) {
  3605. yield [
  3606. 'type' => 'done',
  3607. 'script' => [],
  3608. 'episode' => [],
  3609. 'answer' => $fullContent,
  3610. 'reasoning' => $fullReasoningContent,
  3611. 'usage' => $usage,
  3612. 'error' => '未生成剧本内容,请调整提示词再试'
  3613. ];
  3614. return;
  3615. }
  3616. }
  3617. // 替换美术风格
  3618. if ($mappedArtStyle !== '') {
  3619. $script_arr['art_style'] = $mappedArtStyle;
  3620. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  3621. }
  3622. // 新建动漫
  3623. if ($user_anime_name == '新剧本策划') {
  3624. $anime_name = getProp($script_arr, 'script_name');
  3625. // if (!$anime_name) {
  3626. // // 未识别到剧本名,保存对话记录并返回提示
  3627. // dLog('deepseek')->info('未能识别到剧本名称');
  3628. // try {
  3629. // DB::beginTransaction();
  3630. // $now = date('Y-m-d H:i:s');
  3631. // // 保存对话记录
  3632. // $records = [
  3633. // [
  3634. // 'uid' => $uid,
  3635. // 'anime_id' => $anime_id,
  3636. // 'sequence' => 0,
  3637. // 'role' => 'user',
  3638. // 'content' => $prompt,
  3639. // 'created_at' => $now,
  3640. // 'updated_at' => $now
  3641. // ],
  3642. // [
  3643. // 'uid' => $uid,
  3644. // 'anime_id' => $anime_id,
  3645. // 'sequence' => 0,
  3646. // 'role' => 'assistant',
  3647. // 'content' => '未能生成剧本名称,请重试',
  3648. // 'created_at' => $now,
  3649. // 'updated_at' => $now
  3650. // ]
  3651. // ];
  3652. // DB::table('mp_anime_records')->insert($records);
  3653. // DB::commit();
  3654. // } catch (\Exception $e) {
  3655. // DB::rollBack();
  3656. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3657. // }
  3658. // yield [
  3659. // 'type' => 'done',
  3660. // 'script' => [],
  3661. // 'episode' => [],
  3662. // 'answer' => $fullContent,
  3663. // 'reasoning' => $fullReasoningContent,
  3664. // 'usage' => $usage,
  3665. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  3666. // ];
  3667. // return;
  3668. // }
  3669. // 确认对话名称唯一性
  3670. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  3671. $anime_name = $anime_name . '_' . date('YmdHis');
  3672. }
  3673. }else {
  3674. $anime_name = $user_anime_name;
  3675. }
  3676. $table_data = [
  3677. 'user_id' => $uid,
  3678. 'anime_name' => $anime_name,
  3679. 'model' => $model,
  3680. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3681. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3682. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3683. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3684. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3685. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3686. 'art_style_type' => $input_art_style,
  3687. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3688. 'status' => '解析完成',
  3689. 'content' => $content,
  3690. 'is_multi' => $is_multi,
  3691. 'ace_mode' => $ace_mode,
  3692. 'generate_status' => '待执行',
  3693. 'updated_at' => date('Y-m-d H:i:s')
  3694. ];
  3695. if ($table_data['content']) {
  3696. $chapters = splitContent($table_data['content']);
  3697. $chapter_count = count($chapters);
  3698. if ($chapter_count > 0) {
  3699. $table_data['start_episode_sequence'] = 1;
  3700. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  3701. }
  3702. }
  3703. // 如果有剧本ID则进行绑定
  3704. if ($script_id) {
  3705. $table_data['script_id'] = $script_id;
  3706. }
  3707. $single_episode = [];
  3708. try {
  3709. DB::beginTransaction();
  3710. $now = date('Y-m-d H:i:s');
  3711. // 更新动漫大纲
  3712. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3713. if (!$boolen) {
  3714. dLog('deepseek')->info('动漫保存失败', $table_data);
  3715. Utils::throwError('20003:动漫保存失败');
  3716. }
  3717. // 保存对话记录
  3718. $records = [
  3719. [
  3720. 'uid' => $uid,
  3721. 'anime_id' => $anime_id,
  3722. 'sequence' => 0,
  3723. 'role' => 'user',
  3724. 'content' => $prompt,
  3725. 'created_at' => date('Y-m-d H:i:s'),
  3726. 'updated_at' => date('Y-m-d H:i:s')
  3727. ],
  3728. [
  3729. 'uid' => $uid,
  3730. 'anime_id' => $anime_id,
  3731. 'sequence' => 0,
  3732. 'role' => 'assistant',
  3733. 'content' => $fullContent,
  3734. 'created_at' => date('Y-m-d H:i:s'),
  3735. 'updated_at' => date('Y-m-d H:i:s')
  3736. ]
  3737. ];
  3738. // 保存对话记录
  3739. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3740. if (!$boolen3) {
  3741. Utils::throwError('20003:对话记录保存失败');
  3742. }
  3743. if ($is_single) {
  3744. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3745. if (empty($episode_arr['acts'])) {
  3746. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3747. }
  3748. $saveResult = $this->saveEpisodeVersionData(
  3749. $anime_id,
  3750. 1,
  3751. $episode_arr,
  3752. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3753. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3754. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  3755. null,
  3756. null,
  3757. false,
  3758. $content,
  3759. $now
  3760. );
  3761. $single_episode = $saveResult['episode'];
  3762. $episode_id = $saveResult['episode_id'];
  3763. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3764. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3765. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3766. 'props' => json_encode($saveResult['merged_props'], 256),
  3767. 'updated_at' => $now
  3768. ]);
  3769. if ($boolen5 === false) {
  3770. Utils::throwError('20003:单剧集主表资源同步失败');
  3771. }
  3772. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3773. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3774. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  3775. $episode_record_content = '确认分镜大纲';
  3776. if ($content !== '') {
  3777. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  3778. }
  3779. $episode_records = [
  3780. [
  3781. 'uid' => $uid,
  3782. 'anime_id' => $anime_id,
  3783. 'role' => 'user',
  3784. 'content' => $episode_record_content,
  3785. 'sequence' => 1,
  3786. 'episode_id' => $episode_id,
  3787. 'created_at' => $now,
  3788. 'updated_at' => $now
  3789. ],
  3790. [
  3791. 'uid' => $uid,
  3792. 'anime_id' => $anime_id,
  3793. 'role' => 'assistant',
  3794. 'content' => $fullContent,
  3795. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3796. 'sequence' => 1,
  3797. 'episode_id' => $episode_id,
  3798. 'created_at' => $now,
  3799. 'updated_at' => $now
  3800. ]
  3801. ];
  3802. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3803. if (!$boolen4) {
  3804. Utils::throwError('20003:单剧集分镜记录保存失败');
  3805. }
  3806. }
  3807. }catch (\Exception $e) {
  3808. DB::rollBack();
  3809. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  3810. yield [
  3811. 'type' => 'done',
  3812. 'answer' => $fullContent,
  3813. 'reasoning' => $fullReasoningContent,
  3814. 'usage' => $usage,
  3815. 'error' => $e->getMessage(),
  3816. ];
  3817. return;
  3818. }
  3819. DB::commit();
  3820. dLog('deepseek')->info('保存完毕');
  3821. if ($is_single && !empty($single_episode)) {
  3822. // $this->batchSetGlobalRoleImg([
  3823. // 'anime_id' => $anime_id,
  3824. // ]);
  3825. // $this->batchSetGlobalSceneImg([
  3826. // 'anime_id' => $anime_id,
  3827. // ]);
  3828. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  3829. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  3830. }
  3831. $table_data['anime_id'] = $anime_id;
  3832. $table_data['roles'] = json_decode($table_data['roles'], true);
  3833. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  3834. // $table_data['episodes'] = $script_arr['episodes'];
  3835. unset($table_data['created_at']);
  3836. unset($table_data['updated_at']);
  3837. unset($table_data['status']);
  3838. dLog('deepseek')->info('开始返回');
  3839. yield [
  3840. 'type' => 'done',
  3841. 'script' => $table_data,
  3842. 'episode' => $single_episode,
  3843. 'answer' => $fullContent,
  3844. 'reasoning' => $fullReasoningContent,
  3845. 'usage' => $usage
  3846. ];
  3847. }
  3848. public function reGenerateAnime($data) {
  3849. $uid = Site::getUid();
  3850. $file = getProp($data, 'file');
  3851. $content = getProp($data, 'content', '');
  3852. $bid = getProp($data, 'bid', 0);
  3853. $script_id = getProp($data, 'script_id', 0);
  3854. $anime_id = getProp($data, 'anime_id');
  3855. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3856. if (!$anime) {
  3857. Utils::throwError('20003:该对话不存在');
  3858. }
  3859. $user_anime_name = getProp($anime, 'anime_name');
  3860. $prompt = getProp($data, 'prompt');
  3861. // 处理文本模型
  3862. $model = getProp($data, 'model');
  3863. if (!$model) {
  3864. // 用户没有输入,从anime表获取
  3865. $model = getProp($anime, 'model');
  3866. if (!$model) {
  3867. // anime表也没有,使用默认值
  3868. $model = 'doubao-seed-2-0-mini-260215';
  3869. }
  3870. }
  3871. // 验证模型是否在可用模型表中
  3872. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3873. $model = 'doubao-seed-2-0-mini-260215';
  3874. }
  3875. $is_multi = getProp($anime, 'is_multi', 1);
  3876. $is_single = (int)$is_multi !== 1;
  3877. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  3878. if ($is_single) {
  3879. $episode_exists = DB::table('mp_anime_episodes')
  3880. ->where('anime_id', $anime_id)
  3881. ->where('sequence', 1)
  3882. ->exists();
  3883. if ($episode_exists) {
  3884. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  3885. }
  3886. }
  3887. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3888. if ($prompt) {
  3889. $question .= "本次修改要求如下:\n{$prompt}";
  3890. }
  3891. // 提取文件内容
  3892. if ($file) {
  3893. $content = $this->extractFileContent($file);
  3894. if (!$content) {
  3895. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3896. }
  3897. } elseif ($script_id) {
  3898. $content = $this->getContentByScriptId($script_id);
  3899. if (!$content) {
  3900. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3901. }
  3902. } elseif ($bid) {
  3903. $content = $this->getContentByBid($bid);
  3904. if (!$content) {
  3905. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3906. }
  3907. } elseif ($content) {
  3908. $content = filterContent($content);
  3909. }else {
  3910. $content = filterContent(getProp($anime, 'content'));
  3911. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3912. $need_generate_content = true;
  3913. }
  3914. }
  3915. // 判断是否需要生成原文内容
  3916. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3917. // 如果需要生成原文内容,添加额外的要求
  3918. $content_generation_requirement = $need_generate_content
  3919. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3920. : "";
  3921. // 美术风格
  3922. $input_art_style = getProp($anime, 'art_style');
  3923. if (!$input_art_style) {
  3924. $input_art_style = getProp($data, 'art_style');
  3925. }
  3926. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3927. // 美术风格
  3928. if (!$mappedArtStyle) {
  3929. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3930. }else {
  3931. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3932. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3933. }else {
  3934. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3935. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3936. }
  3937. }
  3938. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3939. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3940. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3941. 中年女:邻居阿姨
  3942. 老年男:幽默大爷
  3943. 老年女:婆婆
  3944. 萌娃:奶气萌娃";
  3945. $system_message = ['role'=>'system', 'content'=>$is_single
  3946. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3947. 强制要求:
  3948. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3949. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3950. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3951. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3952. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3953. 普通要求:
  3954. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3955. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3956. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3957. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3958. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3959. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3960. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3961. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3962. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3963. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3964. 3.$mappedArtStyle_prompt\n\n
  3965. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3966. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3967. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3968. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3969. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3970. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3971. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3972. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3973. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3974. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3975. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3976. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3977. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3978. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3979. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3980. 示例如下:\n
  3981. ###剧本名:西昆仑
  3982. ###故事梗概
  3983. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3984. ###剧本亮点
  3985. 亮点1:绝境奇药,生死一线
  3986. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3987. 亮点2:结拜兄妹,化解尴尬
  3988. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3989. 亮点3:纤发夺命,情愫暗涌
  3990. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3991. ###人物关系
  3992. 阿雪与梁萧之间存在兄妹之情。
  3993. ###核心矛盾
  3994. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3995. ###主体列表
  3996. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3997. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3998. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3999. 姿态:站立。}{{甜心小美}}
  4000. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4001. 全景,正面拍摄,青年女性,亚洲人。
  4002. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4003. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4004. 姿态:站立。}{{阳光青年}}
  4005. ###美术风格
  4006. 基础画风风格词:厚涂古风
  4007. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4008. ###场景列表
  4009. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4010. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4011. 无人物。}
  4012. ###分镜剧本
  4013. ##第1幕:徐家老旧厨房 白天 室内
  4014. 分镜1
  4015. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4016. 场景:徐家老旧厨房
  4017. 构图设计:全景,低角度仰视
  4018. 运镜调度:手持拍摄
  4019. 配音角色:旁白
  4020. 出镜角色:许芸-校服装、徐母
  4021. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4022. 画面类型:普通画面
  4023. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4024. 分镜2
  4025. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4026. 场景:徐家老旧厨房
  4027. 构图设计:近景,徐母面部特写
  4028. 运镜调度:固定镜头
  4029. 配音角色:徐母
  4030. 出镜角色:徐母
  4031. 台词内容:问我夜不归宿死哪儿去了。
  4032. 画面类型:对口型
  4033. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4034. ##第2幕:徐家简陋客厅 黄昏 室内
  4035. 分镜3
  4036. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4037. 场景:徐家简陋客厅
  4038. 构图设计:全景,景深虚化
  4039. 运镜调度:固定镜头
  4040. 配音角色:旁白
  4041. 出镜角色:无
  4042. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4043. 画面类型:普通画面
  4044. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4045. 分镜4
  4046. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4047. 场景:徐家简陋客厅
  4048. 构图设计:特写,火车票
  4049. 运镜调度:固定镜头
  4050. 配音角色:旁白
  4051. 出镜角色:无
  4052. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4053. 画面类型:普通画面
  4054. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4055. "
  4056. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4057. 强制要求:\n
  4058. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4059. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4060. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4061. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4062. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4063. 普通要求:\n
  4064. 1.剧本名(必须生成)必须与文档内容高度相关
  4065. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4066. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4067. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4068. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4069. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4070. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4071. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4072. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4073. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4074. 4.$mappedArtStyle_prompt\n\n
  4075. 示例如下:\n
  4076. ###剧本名:西昆仑
  4077. ###故事梗概
  4078. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4079. ###剧本亮点
  4080. 亮点1:绝境奇药,生死一线
  4081. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4082. 亮点2:结拜兄妹,化解尴尬
  4083. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4084. 亮点3:纤发夺命,情愫暗涌
  4085. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4086. ###人物关系
  4087. 阿雪与梁萧之间存在兄妹之情。
  4088. ###核心矛盾
  4089. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4090. ###主体列表
  4091. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4092. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4093. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4094. 姿态:站立。}{{甜心小美}}
  4095. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4096. 全景,正面拍摄,青年女性,亚洲人。
  4097. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4098. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4099. 姿态:站立。}{{阳光青年}}
  4100. ###美术风格
  4101. 基础画风风格词:厚涂古风
  4102. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4103. ###场景列表
  4104. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4105. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4106. 无人物。}"];
  4107. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  4108. $episode_count = $this->extractEpisodeNumber($prompt);
  4109. if ((int)getProp($anime, 'is_multi') !== 1) {
  4110. yield [
  4111. 'type' => 'done',
  4112. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  4113. 'reasoning' => '',
  4114. 'usage' => []
  4115. ];
  4116. return;
  4117. }
  4118. if ($episode_count) {
  4119. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  4120. $system_message = [
  4121. 'role' => 'system',
  4122. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4123. 强制要求:\n
  4124. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4125. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4126. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4127. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4128. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4129. 普通要求:\n
  4130. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4131. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4132. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4133. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4134. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4135. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4136. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4137. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4138. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4139. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  4140. 示例如下:\n
  4141. ###剧本名:西昆仑
  4142. ###故事梗概
  4143. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4144. ###剧本亮点
  4145. 亮点1:绝境奇药,生死一线
  4146. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4147. 亮点2:结拜兄妹,化解尴尬
  4148. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4149. 亮点3:纤发夺命,情愫暗涌
  4150. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4151. ###人物关系
  4152. 阿雪与梁萧之间存在兄妹之情。
  4153. ###核心矛盾
  4154. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4155. ###主体列表
  4156. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4157. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4158. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4159. 姿态:站立。}{{甜心小美}}
  4160. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4161. 全景,正面拍摄,青年女性,亚洲人。
  4162. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4163. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4164. 姿态:站立。}{{阳光青年}}
  4165. ###美术风格
  4166. 基础画风风格词:厚涂古风
  4167. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4168. ###场景列表
  4169. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4170. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4171. 无人物。}
  4172. ###分集详细内容
  4173. ##第1章 重生
  4174. 我重生了。
  4175. 源于一个男人偏执的暗恋。
  4176. ##第2章 相救
  4177. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  4178. 我眼睛扫向站在锅炉后的卞大伟。"
  4179. ];
  4180. // 构建消息
  4181. $messages = [
  4182. $system_message,
  4183. [
  4184. 'role' => 'user',
  4185. 'content' => "以下是文档内容:
  4186. {$content}
  4187. 用户问题:
  4188. {$question}"
  4189. ]
  4190. ];
  4191. }else {
  4192. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  4193. // 构建消息
  4194. $messages = [
  4195. $system_message,
  4196. [
  4197. 'role' => 'user',
  4198. 'content' => "以下是文档内容:
  4199. {$content}
  4200. 用户问题:
  4201. {$question}"
  4202. ]
  4203. ];
  4204. }else {
  4205. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  4206. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  4207. return (array)$value;
  4208. })->toArray();
  4209. array_unshift($messages, $system_message);
  4210. $messages[] = [
  4211. 'role' => 'user',
  4212. 'content' => $prompt
  4213. ];
  4214. }
  4215. }
  4216. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4217. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4218. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4219. if ($model === 'deepseek-chat') {
  4220. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4221. $model = 'deepseek-v4-flash';
  4222. $thinkingMode = 'disabled';
  4223. } elseif ($model === 'deepseek-reasoner') {
  4224. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4225. $model = 'deepseek-v4-flash';
  4226. $thinkingMode = 'enabled';
  4227. }
  4228. $post_data = [
  4229. 'model' => $model,
  4230. 'messages' => $messages,
  4231. // 'max_tokens' => 8192,
  4232. 'temperature' => 0.7,
  4233. 'frequency_penalty' => 0,
  4234. 'presence_penalty' => 0,
  4235. 'response_format' => ['type' => 'text'],
  4236. 'thinking' => ['type' => $thinkingMode],
  4237. 'stream' => true // 启用流式输出
  4238. ];
  4239. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4240. // 根据模型类型选择调用方法
  4241. $fullContent = '';
  4242. $fullReasoningContent = '';
  4243. $usage = [];
  4244. // dd($post_data);
  4245. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  4246. try {
  4247. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4248. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4249. } else if (in_array($model, $this->gpt_text_models)) {
  4250. // GPT-5.4 模型使用 TokenRouter API
  4251. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4252. } else {
  4253. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4254. }
  4255. // 验证返回值类型
  4256. if (!is_iterable($streamGenerator)) {
  4257. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4258. dLog('deepseek')->error('方法名流式生成器无效', [
  4259. 'generator_type' => $errorType,
  4260. 'model' => $model,
  4261. // 添加其他上下文信息
  4262. ]);
  4263. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  4264. 'type' => $errorType,
  4265. 'model' => $model
  4266. ]);
  4267. yield [
  4268. 'type' => 'error',
  4269. // 根据方法返回相应的空数据结构
  4270. 'answer' => '',
  4271. 'reasoning' => '',
  4272. 'usage' => [],
  4273. 'error' => '接口返回数据异常,请重新请求'
  4274. ];
  4275. return;
  4276. }
  4277. // 处理流式输出
  4278. foreach ($streamGenerator as $chunk) {
  4279. if (isset($chunk['type'])) {
  4280. if ($chunk['type'] === 'done') {
  4281. $fullContent = $chunk['full_content'];
  4282. $fullReasoningContent = $chunk['full_reasoning'];
  4283. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4284. } else {
  4285. yield $chunk;
  4286. }
  4287. }
  4288. }
  4289. } catch (\Exception $e) {
  4290. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  4291. 'model' => $model,
  4292. 'trace' => $e->getTraceAsString()
  4293. ]);
  4294. logDB('deepseek', 'error', '方法名流式处理失败', [
  4295. 'error' => $e->getMessage(),
  4296. 'model' => $model
  4297. ]);
  4298. yield [
  4299. 'type' => 'error',
  4300. // 根据方法返回相应的空数据结构
  4301. 'answer' => '',
  4302. 'reasoning' => '',
  4303. 'usage' => [],
  4304. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4305. ];
  4306. return;
  4307. }
  4308. dLog('deepseek')->info('完整内容: '.$fullContent);
  4309. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4310. // 处理完整内容并返回最终结果
  4311. $script_arr = [];
  4312. if ($fullContent) {
  4313. $script_arr = handleScriptContent($fullContent);
  4314. dLog('deepseek')->info('解析内容', $script_arr);
  4315. logDB('deepseek', 'info', '解析内容', $script_arr);
  4316. }
  4317. if (empty($script_arr['roles'])) {
  4318. // 未生成剧本相关内容,保存对话记录并返回提示
  4319. dLog('deepseek')->info('未生成剧本相关的内容');
  4320. try {
  4321. $now = date('Y-m-d H:i:s');
  4322. // 保存对话记录
  4323. $records = [
  4324. [
  4325. 'uid' => $uid,
  4326. 'anime_id' => $anime_id,
  4327. 'sequence' => 0,
  4328. 'role' => 'user',
  4329. 'content' => $prompt,
  4330. 'created_at' => $now,
  4331. 'updated_at' => $now
  4332. ],
  4333. [
  4334. 'uid' => $uid,
  4335. 'anime_id' => $anime_id,
  4336. 'sequence' => 0,
  4337. 'role' => 'assistant',
  4338. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  4339. 'created_at' => $now,
  4340. 'updated_at' => $now
  4341. ]
  4342. ];
  4343. DB::table('mp_anime_records')->insert($records);
  4344. } catch (\Exception $e) {
  4345. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4346. }
  4347. yield [
  4348. 'type' => 'done',
  4349. 'script' => [],
  4350. 'episode' => [],
  4351. 'answer' => $fullContent,
  4352. 'reasoning' => $fullReasoningContent,
  4353. 'usage' => $usage,
  4354. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4355. ];
  4356. return;
  4357. }
  4358. // 替换美术风格
  4359. if ($mappedArtStyle !== '') {
  4360. $script_arr['art_style'] = $mappedArtStyle;
  4361. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4362. }
  4363. if ($user_anime_name != '新剧本策划') {
  4364. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  4365. // 确认对话名称唯一性
  4366. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4367. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  4368. }
  4369. }else {
  4370. $anime_name = $user_anime_name;
  4371. }
  4372. $table_data = [
  4373. 'user_id' => $uid,
  4374. 'model' => $model,
  4375. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4376. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4377. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4378. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4379. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4380. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4381. 'art_style_type' => $input_art_style,
  4382. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4383. 'status' => '解析完成',
  4384. 'generate_status' => '待执行',
  4385. 'updated_at' => date('Y-m-d H:i:s')
  4386. ];
  4387. if ($anime_name) $table_data['anime_name'] = $anime_name;
  4388. // 如果是修改集数,则将content内容更新(会改变原文)
  4389. if (isset($episode_count) && $episode_count > 0) {
  4390. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  4391. $table_data['start_episode_sequence'] = 1;
  4392. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  4393. }else {
  4394. // 如果需要生成原文内容,从script_arr中提取
  4395. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4396. $table_data['content'] = $script_arr['content'];
  4397. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  4398. if (!$table_data['content']) {
  4399. yield [
  4400. 'type' => 'done',
  4401. 'script' => [],
  4402. 'episode' => [],
  4403. 'answer' => $fullContent,
  4404. 'reasoning' => $fullReasoningContent,
  4405. 'usage' => $usage,
  4406. 'error' => '未生成剧本内容,请调整提示词再试'
  4407. ];
  4408. return;
  4409. }
  4410. }
  4411. if (isset($table_data['content']) && $table_data['content']) {
  4412. $chapters = splitContent($table_data['content']);
  4413. $chapter_count = count($chapters);
  4414. if ($chapter_count > 0) {
  4415. $table_data['start_episode_sequence'] = 1;
  4416. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4417. }
  4418. }
  4419. }
  4420. $single_episode = [];
  4421. try {
  4422. DB::beginTransaction();
  4423. $now = date('Y-m-d H:i:s');
  4424. // 更新动漫大纲
  4425. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4426. if (!$boolen) {
  4427. dLog('deepseek')->info('对话修改失败', $table_data);
  4428. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  4429. Utils::throwError('20003:对话修改失败');
  4430. }
  4431. // 保存对话记录
  4432. $records = [
  4433. [
  4434. 'uid' => $uid,
  4435. 'anime_id' => $anime_id,
  4436. 'sequence' => 0,
  4437. 'role' => 'user',
  4438. 'content' => $prompt,
  4439. 'created_at' => $now,
  4440. 'updated_at' => $now
  4441. ],
  4442. [
  4443. 'uid' => $uid,
  4444. 'anime_id' => $anime_id,
  4445. 'sequence' => 0,
  4446. 'role' => 'assistant',
  4447. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4448. 'content' => $fullContent,
  4449. 'created_at' => $now,
  4450. 'updated_at' => $now
  4451. ]
  4452. ];
  4453. // 保存对话记录
  4454. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4455. if (!$boolen3) {
  4456. Utils::throwError('20003:对话记录保存失败');
  4457. }
  4458. // 单剧集模式:生成并保存剧集信息
  4459. if ($is_single) {
  4460. $anime_name = getProp($anime, 'anime_name', '未命名');
  4461. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4462. if (empty($episode_arr['acts'])) {
  4463. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4464. }
  4465. $saveResult = $this->saveEpisodeVersionData(
  4466. $anime_id,
  4467. 1,
  4468. $episode_arr,
  4469. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4470. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4471. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  4472. null,
  4473. null,
  4474. false,
  4475. $content,
  4476. $now
  4477. );
  4478. $single_episode = $saveResult['episode'];
  4479. $episode_id = $saveResult['episode_id'];
  4480. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4481. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4482. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4483. 'props' => json_encode($saveResult['merged_props'], 256),
  4484. 'updated_at' => $now
  4485. ]);
  4486. if ($boolen5 === false) {
  4487. Utils::throwError('20003:单剧集主表资源同步失败');
  4488. }
  4489. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4490. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4491. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  4492. $episode_record_content = '确认分镜大纲';
  4493. if ($content !== '') {
  4494. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4495. }
  4496. $episode_records = [
  4497. [
  4498. 'uid' => $uid,
  4499. 'anime_id' => $anime_id,
  4500. 'role' => 'user',
  4501. 'content' => $episode_record_content,
  4502. 'sequence' => 1,
  4503. 'episode_id' => $episode_id,
  4504. 'created_at' => $now,
  4505. 'updated_at' => $now
  4506. ],
  4507. [
  4508. 'uid' => $uid,
  4509. 'anime_id' => $anime_id,
  4510. 'role' => 'assistant',
  4511. 'content' => $fullContent,
  4512. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4513. 'sequence' => 1,
  4514. 'episode_id' => $episode_id,
  4515. 'created_at' => $now,
  4516. 'updated_at' => $now
  4517. ]
  4518. ];
  4519. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4520. if (!$boolen4) {
  4521. Utils::throwError('20003:单剧集分镜记录保存失败');
  4522. }
  4523. }
  4524. }catch (\Exception $e) {
  4525. DB::rollBack();
  4526. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  4527. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  4528. yield [
  4529. 'type' => 'done',
  4530. 'answer' => $fullContent,
  4531. 'reasoning' => $fullReasoningContent,
  4532. 'usage' => $usage,
  4533. 'error' => $e->getMessage(),
  4534. ];
  4535. return;
  4536. }
  4537. DB::commit();
  4538. dLog('deepseek')->info('保存完毕');
  4539. if ($is_single && !empty($single_episode)) {
  4540. // $this->batchSetGlobalRoleImg([
  4541. // 'anime_id' => $anime_id,
  4542. // ]);
  4543. // $this->batchSetGlobalSceneImg([
  4544. // 'anime_id' => $anime_id,
  4545. // ]);
  4546. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4547. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4548. }
  4549. $table_data['anime_id'] = $anime_id;
  4550. $table_data['roles'] = json_decode($table_data['roles'], true);
  4551. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4552. unset($table_data['updated_at']);
  4553. unset($table_data['status']);
  4554. yield [
  4555. 'type' => 'done',
  4556. 'script' => $table_data,
  4557. 'episode' => $single_episode,
  4558. 'answer' => $fullContent,
  4559. 'reasoning' => $fullReasoningContent,
  4560. 'usage' => $usage
  4561. ];
  4562. }
  4563. public function chat($data) {
  4564. $uid = Site::getUid();
  4565. $anime_id = getProp($data, 'anime_id');
  4566. $file = getProp($data, 'file');
  4567. $content = getProp($data, 'content', '');
  4568. $bid = getProp($data, 'bid', 0);
  4569. $script_id = getProp($data, 'script_id', 0);
  4570. $episode_number = getProp($data, 'episode_number', 1);
  4571. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4572. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4573. if (!$anime) Utils::throwError('20003:该对话不存在!');
  4574. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  4575. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  4576. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  4577. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  4578. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  4579. $roles = is_array($roles) ? $roles : [];
  4580. $scenes = is_array($scenes) ? $scenes : [];
  4581. // 获取最后一集序号
  4582. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  4583. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  4584. // 转换主体列表和场景列表的格式
  4585. // 获取参考主体或场景
  4586. if ((int)$episode_number === 1) {
  4587. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  4588. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  4589. }else {
  4590. $prev_episode_number = $episode_number - 1;
  4591. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  4592. }
  4593. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  4594. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  4595. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  4596. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  4597. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4598. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4599. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4600. 中年女:邻居阿姨
  4601. 老年男:幽默大爷
  4602. 老年女:婆婆
  4603. 萌娃:奶气萌娃";
  4604. if ($roles_content) {
  4605. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  4606. 主体范围:\n {$roles_content}\n
  4607. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  4608. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4609. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4610. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4611. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4612. }else {
  4613. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4614. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4615. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4616. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4617. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4618. }
  4619. if ($scenes_content) {
  4620. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  4621. 场景范围:\n {$scenes_content}\n
  4622. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  4623. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4624. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4625. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4626. }else {
  4627. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4628. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4629. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4630. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4631. }
  4632. // 提取文件内容
  4633. if ($file) {
  4634. $uploaded_content = $this->extractFileContent($file);
  4635. if (!$uploaded_content) {
  4636. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4637. }
  4638. } elseif ($script_id) {
  4639. $uploaded_content = $this->getContentByScriptId($script_id);
  4640. if (!$uploaded_content) {
  4641. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4642. }
  4643. } elseif ($bid) {
  4644. $uploaded_content = $this->getContentByBid($bid);
  4645. if (!$uploaded_content) {
  4646. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4647. }
  4648. } elseif ($content) {
  4649. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  4650. }
  4651. // elseif ($prompt) {
  4652. // $uploaded_content = filterContent($prompt);
  4653. // }
  4654. else {
  4655. $uploaded_content = '';
  4656. }
  4657. $input_art_style = getProp($anime, 'art_style');
  4658. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4659. // 美术风格
  4660. if (!$mappedArtStyle) {
  4661. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4662. }else {
  4663. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4664. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4665. }else {
  4666. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4667. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4668. }
  4669. }
  4670. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4671. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4672. // 强制要求:
  4673. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4674. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4675. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4676. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4677. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  4678. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  4679. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  4680. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  4681. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  4682. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  4683. // - 分镜要和场景列表、人物主体保持一致\n
  4684. // 普通要求:
  4685. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4686. // {$role_demo}
  4687. // {$scene_demo}
  4688. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4689. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4690. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4691. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4692. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4693. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4694. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4695. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4696. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4697. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4698. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4699. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4700. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4701. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4702. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4703. // 5.$mappedArtStyle_prompt\n\n
  4704. // 示例格式:\n
  4705. // 第1集:隐形的守护者
  4706. // ###故事梗概
  4707. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4708. // ###美术风格
  4709. // 基础画风风格词:韩漫二次元
  4710. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4711. // ###主体列表
  4712. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4713. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4714. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4715. // ###场景列表
  4716. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4717. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4718. // 无人物。}
  4719. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4720. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4721. // 无人物。}
  4722. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4723. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4724. // 无人物。}
  4725. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4726. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4727. // 无人物。}
  4728. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4729. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4730. // 无人物。}
  4731. // ###分镜剧本
  4732. // ##第1幕:徐家老旧厨房 白天 室内
  4733. // 分镜1
  4734. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4735. // 场景:徐家老旧厨房
  4736. // 构图设计:全景,低角度仰视
  4737. // 运镜调度:手持拍摄
  4738. // 配音角色:旁白
  4739. // 出镜角色:许芸-校服装、徐母
  4740. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4741. // 画面类型:普通画面
  4742. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4743. // 分镜2
  4744. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4745. // 场景:徐家老旧厨房
  4746. // 构图设计:近景,徐母面部特写
  4747. // 运镜调度:固定镜头
  4748. // 配音角色:徐母
  4749. // 出镜角色:徐母
  4750. // 台词内容:问我夜不归宿死哪儿去了。
  4751. // 画面类型:对口型
  4752. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4753. // ##第2幕:徐家简陋客厅 黄昏 室内
  4754. // 分镜3
  4755. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4756. // 场景:徐家简陋客厅
  4757. // 构图设计:全景,景深虚化
  4758. // 运镜调度:固定镜头
  4759. // 配音角色:旁白
  4760. // 出镜角色:无
  4761. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4762. // 画面类型:普通画面
  4763. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4764. // 分镜4
  4765. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4766. // 场景:徐家简陋客厅
  4767. // 构图设计:特写,火车票
  4768. // 运镜调度:固定镜头
  4769. // 配音角色:旁白
  4770. // 出镜角色:无
  4771. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4772. // 画面类型:普通画面
  4773. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4774. // \n\n";
  4775. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  4776. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  4777. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  4778. 普通要求:
  4779. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4780. {$role_demo}
  4781. {$scene_demo}
  4782. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4783. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4784. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4785. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  4786. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4787. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4788. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4789. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4790. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4791. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4792. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4793. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4794. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4795. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4796. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4797. 5.$mappedArtStyle_prompt
  4798. 6.《情绪-视听语言映射表》:
  4799. 6.1 场景空间与时间心理学 (Scene & Temporality)
  4800. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4801. -----|---------|------------|----------------
  4802. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  4803. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  4804. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  4805. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  4806. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  4807. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4808. -----|---------|------------|----------------
  4809. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  4810. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  4811. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  4812. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  4813. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  4814. --------|---------|--------------|-------------
  4815. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  4816. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  4817. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  4818. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  4819. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  4820. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  4821. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  4822. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  4823. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  4824. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  4825. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  4826. -----|---------|------------|------------
  4827. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  4828. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  4829. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  4830. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  4831. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  4832. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  4833. --------|---------|--------------|----------
  4834. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  4835. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  4836. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  4837. 6.6 声音设计与潜意识影响 (Soundscape)
  4838. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  4839. -----|---------|------------|------------------
  4840. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  4841. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  4842. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  4843. 理论基石:
  4844. - The Five C's of Cinematography by Joseph V. Mascelli
  4845. - Film Art: An Introduction by David Bordwell
  4846. - Sight, Sound, Motion by Herbert Zettl
  4847. - Notes on the Cinematograph by Robert Bresson
  4848. \n\n
  4849. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  4850. 示例格式:\n
  4851. 第1集:隐形的守护者
  4852. ###故事梗概
  4853. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4854. ###美术风格
  4855. 基础画风风格词:韩漫二次元
  4856. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4857. ###主体列表
  4858. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4859. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4860. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4861. ###场景列表
  4862. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4863. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4864. 无人物。}
  4865. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4866. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4867. 无人物。}
  4868. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4869. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4870. 无人物。}
  4871. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4872. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4873. 无人物。}
  4874. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4875. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4876. 无人物。}
  4877. ###分镜剧本
  4878. ##第1幕:徐家老旧厨房 白天 室内
  4879. 分镜1
  4880. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4881. 场景:徐家老旧厨房
  4882. 构图设计:全景,低角度仰视
  4883. 运镜调度:手持拍摄
  4884. 配音角色:旁白
  4885. 出镜角色:许芸-校服装、徐母
  4886. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4887. 画面类型:普通画面
  4888. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4889. 分镜2
  4890. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4891. 场景:徐家老旧厨房
  4892. 构图设计:近景,徐母面部特写
  4893. 运镜调度:固定镜头
  4894. 配音角色:徐母
  4895. 出镜角色:徐母
  4896. 台词内容:问我夜不归宿死哪儿去了。
  4897. 画面类型:对口型
  4898. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4899. ##第2幕:徐家简陋客厅 黄昏 室内
  4900. 分镜3
  4901. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4902. 场景:徐家简陋客厅
  4903. 构图设计:全景,景深虚化
  4904. 运镜调度:固定镜头
  4905. 配音角色:旁白
  4906. 出镜角色:无
  4907. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4908. 画面类型:普通画面
  4909. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4910. 分镜4
  4911. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4912. 场景:徐家简陋客厅
  4913. 构图设计:特写,火车票
  4914. 运镜调度:固定镜头
  4915. 配音角色:旁白
  4916. 出镜角色:无
  4917. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4918. 画面类型:普通画面
  4919. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4920. \n\n";
  4921. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4922. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  4923. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  4924. $prompt = $origin_prompt;
  4925. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  4926. // 获取章节内容
  4927. $full_content = getProp($anime, 'content');
  4928. if ($uploaded_content) {
  4929. $full_content = $uploaded_content;
  4930. }
  4931. // 根据章节内容拆分章节
  4932. $chapters = splitContent($full_content);
  4933. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  4934. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  4935. $messages = [];
  4936. if ($prompt == '确认分镜大纲') {
  4937. // 暂时保留
  4938. $content = $chapter_content;
  4939. if ($is_single) $content = $full_content; // 单剧集使用全文
  4940. if (!$content) {
  4941. Utils::throwError('20003:章节内容无法获取,请确认');
  4942. }
  4943. $question = $is_single
  4944. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  4945. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  4946. // 构建消息
  4947. $messages[] =
  4948. [
  4949. 'role' => 'user',
  4950. 'content' => $question
  4951. ];
  4952. }else if ($prompt == '继续策划下一集') {
  4953. if ($is_single) {
  4954. Utils::throwError('20003:单剧集不支持继续策划下一集');
  4955. }
  4956. $content = $chapter_content;
  4957. if (!$content) {
  4958. Utils::throwError('20003:章节内容无法获取,请确认');
  4959. }
  4960. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  4961. // 获取上一集最后记录
  4962. $prev_sequence = $episode_number - 1;
  4963. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  4964. // 构建消息
  4965. $messages[] =
  4966. [
  4967. 'role' => 'user',
  4968. 'content' => $question
  4969. ];
  4970. }else {
  4971. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  4972. if (!$content) {
  4973. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  4974. }
  4975. if (!$content) {
  4976. Utils::throwError('20003:章节内容无法获取,请确认');
  4977. }
  4978. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  4979. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  4980. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  4981. if ($origin_prompt) {
  4982. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  4983. }
  4984. $messages[] =
  4985. [
  4986. 'role' => 'user',
  4987. 'content' => $question
  4988. ];
  4989. }
  4990. // 处理文本模型
  4991. $model = getProp($data, 'model');
  4992. if (!$model) {
  4993. // 用户没有输入,从anime表获取
  4994. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4995. $model = getProp($anime, 'model');
  4996. if (!$model) {
  4997. // anime表也没有,使用默认值
  4998. $model = 'doubao-seed-2-0-mini-260215';
  4999. }
  5000. }
  5001. // 验证模型是否在可用模型表中
  5002. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5003. $model = 'doubao-seed-2-0-mini-260215';
  5004. }
  5005. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5006. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5007. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5008. if ($model === 'deepseek-chat') {
  5009. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5010. $model = 'deepseek-v4-flash';
  5011. $thinkingMode = 'disabled';
  5012. } elseif ($model === 'deepseek-reasoner') {
  5013. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5014. $model = 'deepseek-v4-flash';
  5015. $thinkingMode = 'enabled';
  5016. }
  5017. $post_data = [
  5018. 'model' => $model,
  5019. 'messages' => $messages,
  5020. // 'max_tokens' => 8192,
  5021. 'temperature' => 0.2,
  5022. 'frequency_penalty' => 0,
  5023. 'presence_penalty' => 0,
  5024. 'response_format' => ['type' => 'text'],
  5025. 'thinking' => ['type' => $thinkingMode],
  5026. 'stream' => true // 启用流式输出
  5027. ];
  5028. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5029. // 根据模型类型选择调用方法
  5030. $fullContent = '';
  5031. $fullReasoningContent = '';
  5032. $usage = [];
  5033. try {
  5034. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5035. // DeepSeek 官方模型使用 DeepSeek API
  5036. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5037. } else if (in_array($model, $this->gpt_text_models)) {
  5038. // GPT-5.4 模型使用 TokenRouter API
  5039. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5040. } else {
  5041. // 其他模型使用火山引擎API
  5042. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5043. }
  5044. // 验证返回值类型
  5045. if (!is_iterable($streamGenerator)) {
  5046. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5047. dLog('deepseek')->error('chat流式生成器无效', [
  5048. 'generator_type' => $errorType,
  5049. 'model' => $model,
  5050. 'anime_id' => $anime_id,
  5051. 'episode_number' => $episode_number
  5052. ]);
  5053. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  5054. 'type' => $errorType,
  5055. 'model' => $model
  5056. ]);
  5057. yield [
  5058. 'type' => 'error',
  5059. 'episode' => [],
  5060. 'answer' => '',
  5061. 'reasoning' => '',
  5062. 'usage' => [],
  5063. 'error' => '接口返回数据异常,请重新请求'
  5064. ];
  5065. return;
  5066. }
  5067. // 处理流式输出
  5068. foreach ($streamGenerator as $chunk) {
  5069. if (isset($chunk['type'])) {
  5070. if ($chunk['type'] === 'done') {
  5071. // 最终结果
  5072. $fullContent = $chunk['full_content'];
  5073. $fullReasoningContent = $chunk['full_reasoning'];
  5074. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5075. } else {
  5076. // 逐块yield数据
  5077. yield $chunk;
  5078. }
  5079. }
  5080. }
  5081. } catch (\Exception $e) {
  5082. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  5083. 'model' => $model,
  5084. 'anime_id' => $anime_id,
  5085. 'episode_number' => $episode_number,
  5086. 'trace' => $e->getTraceAsString()
  5087. ]);
  5088. logDB('deepseek', 'error', 'chat流式处理失败', [
  5089. 'error' => $e->getMessage(),
  5090. 'model' => $model
  5091. ]);
  5092. yield [
  5093. 'type' => 'error',
  5094. 'episode' => [],
  5095. 'answer' => '',
  5096. 'reasoning' => '',
  5097. 'usage' => [],
  5098. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5099. ];
  5100. return;
  5101. }
  5102. dLog('deepseek')->info('完整内容: '.$fullContent);
  5103. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5104. // 处理完整内容并返回最终结果
  5105. $episode_arr = handleEpisodeContent($fullContent);
  5106. logDB('deepseek', 'info', '解析内容', $episode_arr);
  5107. if (empty($episode_arr['acts'])) {
  5108. // 未生成剧本相关内容,保存对话记录并返回提示
  5109. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  5110. try {
  5111. $now = date('Y-m-d H:i:s');
  5112. // 保存对话记录
  5113. $records = [
  5114. [
  5115. 'uid' => $uid,
  5116. 'anime_id' => $anime_id,
  5117. 'sequence' => $episode_number,
  5118. 'role' => 'user',
  5119. 'content' => $prompt,
  5120. 'created_at' => $now,
  5121. 'updated_at' => $now
  5122. ],
  5123. [
  5124. 'uid' => $uid,
  5125. 'anime_id' => $anime_id,
  5126. 'sequence' => $episode_number,
  5127. 'role' => 'assistant',
  5128. 'content' => $fullContent,
  5129. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5130. 'created_at' => $now,
  5131. 'updated_at' => $now
  5132. ]
  5133. ];
  5134. DB::table('mp_anime_records')->insert($records);
  5135. } catch (\Exception $e) {
  5136. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5137. }
  5138. yield [
  5139. 'type' => 'done',
  5140. 'episode' => [],
  5141. 'answer' => $fullContent,
  5142. 'reasoning' => $fullReasoningContent,
  5143. 'usage' => $usage,
  5144. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  5145. ];
  5146. return;
  5147. }
  5148. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  5149. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  5150. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  5151. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  5152. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  5153. $existing_props = is_array($existing_props) ? $existing_props : [];
  5154. $now = date('Y-m-d H:i:s');
  5155. try {
  5156. DB::beginTransaction();
  5157. $saveResult = $this->saveEpisodeVersionData(
  5158. $anime_id,
  5159. $episode_number,
  5160. $episode_arr,
  5161. $existing_roles,
  5162. $existing_scenes,
  5163. $existing_props,
  5164. $current_episode,
  5165. $base_episode,
  5166. $is_regenerate_version,
  5167. $content,
  5168. $now
  5169. );
  5170. $episode = $saveResult['episode'];
  5171. $episode_id = $saveResult['episode_id'];
  5172. $merged_roles = $saveResult['merged_roles'];
  5173. $merged_scenes = $saveResult['merged_scenes'];
  5174. $merged_props = $saveResult['merged_props'];
  5175. $record_content = $origin_prompt;
  5176. if ($uploaded_content !== '') {
  5177. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  5178. }
  5179. $records = [
  5180. [
  5181. 'uid' => $uid,
  5182. 'anime_id' => $anime_id,
  5183. 'role' => 'user',
  5184. 'content' => $record_content,
  5185. 'sequence' => $episode_number,
  5186. 'episode_id' => $episode_id,
  5187. 'created_at' => $now,
  5188. 'updated_at' => $now
  5189. ],
  5190. [
  5191. 'uid' => $uid,
  5192. 'anime_id' => $anime_id,
  5193. 'role' => 'assistant',
  5194. 'content' => $fullContent,
  5195. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5196. 'sequence' => $episode_number,
  5197. 'episode_id' => $episode_id,
  5198. 'created_at' => $now,
  5199. 'updated_at' => $now
  5200. ]
  5201. ];
  5202. $boolen4 = DB::table('mp_anime_records')->insert($records);
  5203. if (!$boolen4) {
  5204. Utils::throwError('20003:对话记录保存失败');
  5205. }
  5206. // 保存模型和内容到anime表
  5207. $update_anime_data = [
  5208. 'model' => $model,
  5209. 'updated_at' => $now
  5210. ];
  5211. if ($uploaded_content) {
  5212. $update_anime_data['content'] = $uploaded_content;
  5213. }
  5214. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  5215. }catch (\Exception $e) {
  5216. DB::rollBack();
  5217. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5218. yield [
  5219. 'type' => 'done',
  5220. 'answer' => $fullContent,
  5221. 'reasoning' => $fullReasoningContent,
  5222. 'usage' => $usage,
  5223. 'error' => $e->getMessage(),
  5224. ];
  5225. return;
  5226. }
  5227. DB::commit();
  5228. if ($is_global_generate_pics) {
  5229. // // 批量生成全局角色图片
  5230. // $this->batchSetGlobalRoleImg([
  5231. // 'anime_id' => $anime_id,
  5232. // ], true);
  5233. // // 批量生成全局场景图片
  5234. // $this->batchSetGlobalSceneImg([
  5235. // 'anime_id' => $anime_id,
  5236. // ], true);
  5237. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5238. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5239. }
  5240. $episode['episode_id'] = $episode_id;
  5241. $episode['roles'] = $merged_roles;
  5242. $episode['scenes'] = $merged_scenes;
  5243. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  5244. yield [
  5245. 'type' => 'done',
  5246. 'episode' => $episode,
  5247. 'answer' => $fullContent,
  5248. 'reasoning' => $fullReasoningContent,
  5249. 'usage' => $usage
  5250. ];
  5251. }
  5252. public function addChatForAce($data) {
  5253. $uid = Site::getUid();
  5254. $anime_id = getProp($data, 'anime_id');
  5255. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5256. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5257. if (!$anime) Utils::throwError('20003:对话不存在');
  5258. $file = getProp($data, 'file');
  5259. $content = getProp($data, 'content', '');
  5260. $bid = getProp($data, 'bid', 0);
  5261. $script_id = getProp($data, 'script_id', 0);
  5262. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5263. $prompt = getProp($data, 'prompt');
  5264. $is_multi = getProp($anime, 'is_multi');
  5265. $is_single = (int)$is_multi !== 1;
  5266. // 积分余额预检(仅单剧集模式收费)
  5267. if ($is_single) {
  5268. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  5269. }
  5270. $extra_products = getProp($data, 'products', []);
  5271. if (!$extra_products) {
  5272. $extra_products = getProp($anime, 'extra_products');
  5273. if ($extra_products) {
  5274. $extra_products = json_decode($extra_products, true);
  5275. }else {
  5276. $extra_products = [];
  5277. }
  5278. }else {
  5279. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  5280. }
  5281. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  5282. $anime_script_id = getProp($anime, 'script_id');
  5283. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  5284. $cpid = Site::getCpid();
  5285. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  5286. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  5287. ->where('mapping.script_id', $anime_script_id)
  5288. ->where('product.cpid', $cpid)
  5289. ->where('product.is_deleted', 0);
  5290. $mappings = $script_products_mappings->select(
  5291. 'mapping.product_id',
  5292. 'mapping.episode_number',
  5293. 'product.product_name',
  5294. 'product.type',
  5295. 'product.product',
  5296. 'product.pic_prompt',
  5297. 'product.url',
  5298. 'product.pic_task_id',
  5299. 'product.pic_task_status',
  5300. 'product.three_view_image_url'
  5301. )
  5302. ->get();
  5303. // 按 product_id 分组,合并 episode_number
  5304. $productMap = [];
  5305. foreach ($mappings as $item) {
  5306. $product_id = $item->product_id;
  5307. $product_name = $item->product_name;
  5308. // 处理product_name两边的符号
  5309. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5310. if (!isset($productMap[$product_id])) {
  5311. $productMap[$product_id] = [
  5312. 'product_id' => $product_id,
  5313. 'product_name' => $product_name,
  5314. 'type' => (int)$item->type,
  5315. 'product' => (int)$item->product,
  5316. 'pic_prompt' => $item->pic_prompt,
  5317. 'url' => $item->url,
  5318. 'pic_task_id' => $item->pic_task_id,
  5319. 'pic_task_status' => $item->pic_task_status,
  5320. 'episode_numbers' => [],
  5321. ];
  5322. }
  5323. // 添加 episode_number(去重)
  5324. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  5325. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  5326. }
  5327. }
  5328. // 将查询到的剧本资产合并到extra_products中
  5329. // 先构建extra_products的索引(以product_id为key,用于去重)
  5330. $extraProductsMap = [];
  5331. foreach ($extra_products as $item) {
  5332. $key = getProp($item, 'product_id');
  5333. if ($key) {
  5334. $extraProductsMap[$key] = $item;
  5335. }
  5336. }
  5337. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  5338. foreach ($productMap as $product) {
  5339. $product_id = $product['product_id'];
  5340. // 如果不存在则添加(不带episode_number信息)
  5341. if (!isset($extraProductsMap[$product_id])) {
  5342. $extraProductsMap[$product_id] = [
  5343. 'product_id' => $product['product_id'],
  5344. 'product_name' => $product['product_name'],
  5345. 'type' => $product['type'],
  5346. 'product' => $product['product'],
  5347. 'pic_prompt' => $product['pic_prompt'],
  5348. 'url' => $product['url'],
  5349. 'pic_task_id' => $product['pic_task_id'],
  5350. 'pic_task_status' => $product['pic_task_status'],
  5351. ];
  5352. }
  5353. }
  5354. // 重新赋值给extra_products
  5355. $extra_products = array_values($extraProductsMap);
  5356. }
  5357. $user_anime_name = getProp($anime, 'anime_name');
  5358. // 处理提示词
  5359. if ($prompt && $extra_products) {
  5360. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  5361. foreach($extra_products as $item) {
  5362. $product_name = getProp($item, 'product_name');
  5363. if ($product_name) {
  5364. // 替换 {product_name} 为 product_name
  5365. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  5366. }
  5367. }
  5368. }
  5369. // 处理文本模型
  5370. $model = getProp($data, 'model');
  5371. if (!$model) {
  5372. // 用户没有输入,从anime表获取
  5373. $model = getProp($anime, 'model');
  5374. if (!$model) {
  5375. // anime表也没有,使用默认值
  5376. $model = 'deepseek-v4-pro';
  5377. }
  5378. }
  5379. // 验证模型是否在可用模型表中
  5380. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5381. $model = 'deepseek-v4-pro';
  5382. }
  5383. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  5384. if ($prompt) {
  5385. $question .= "本次修改要求如下:\n{$prompt}";
  5386. }
  5387. // if (!$file && !$content && !$bid) {
  5388. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5389. // }
  5390. // 提取文件内容
  5391. if ($file) {
  5392. $content = $this->extractFileContent($file);
  5393. if (!$content) {
  5394. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5395. }
  5396. } elseif ($script_id) {
  5397. $content = $this->getContentByScriptId($script_id);
  5398. if (!$content) {
  5399. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5400. }
  5401. } elseif ($bid) {
  5402. $content = $this->getContentByBid($bid);
  5403. if (!$content) {
  5404. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5405. }
  5406. } elseif ($content) {
  5407. $content = filterContent($content);
  5408. } else {
  5409. $content = getProp($anime, 'content');
  5410. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5411. $need_generate_content = true;
  5412. }
  5413. }
  5414. // 美术风格
  5415. $input_art_style = getProp($data, 'art_style');
  5416. if (!$input_art_style) {
  5417. $mappedArtStyle = getProp($anime, 'art_style');
  5418. }else {
  5419. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5420. }
  5421. // 判断是否需要生成原文内容
  5422. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5423. // 如果需要生成原文内容,添加额外的要求
  5424. $content_generation_requirement = $need_generate_content
  5425. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5426. : "";
  5427. // 美术风格
  5428. if (!$mappedArtStyle) {
  5429. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5430. }else {
  5431. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5432. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5433. }else {
  5434. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5435. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5436. }
  5437. }
  5438. // 构建主体、场景和道具提示词
  5439. $extra_role_prompt = "\n";
  5440. $extra_scene_prompt = "\n";
  5441. $extra_prop_prompt = "\n";
  5442. $ref_products = []; // 参考资产
  5443. if ($extra_products) {
  5444. foreach($extra_products as $item) {
  5445. $product = getProp($item, 'product');
  5446. $product_name = getProp($item, 'product_name');
  5447. if ($product_name == '旁白') continue;
  5448. $ref_products[$product_name] = $item;
  5449. $pic_prompt = getProp($item, 'pic_prompt');
  5450. if ((int)$product === 1) {
  5451. // 拼接角色信息
  5452. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5453. } elseif ((int)$product === 2) {
  5454. // 拼接场景信息
  5455. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5456. } elseif ((int)$product === 3) {
  5457. // 拼接道具信息
  5458. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5459. }
  5460. }
  5461. // 优化提示词,融入剧本
  5462. if (!empty(trim($extra_role_prompt))) {
  5463. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  5464. }
  5465. if (!empty(trim($extra_scene_prompt))) {
  5466. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  5467. }
  5468. if (!empty(trim($extra_prop_prompt))) {
  5469. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  5470. }
  5471. }
  5472. if ($anime_script_id && $is_single) {
  5473. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  5474. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  5475. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  5476. }else {
  5477. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5478. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5479. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5480. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5481. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5482. {$extra_role_prompt}";
  5483. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5484. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5485. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5486. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5487. {$extra_scene_prompt}";
  5488. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5489. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5490. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5491. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5492. {$extra_prop_prompt}";
  5493. }
  5494. $systemPrompt = $is_single
  5495. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5496. 强制要求:
  5497. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5498. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5499. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5500. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5501. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5502. 普通要求:
  5503. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5504. $role_demo
  5505. $scene_demo
  5506. $prop_demo
  5507. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  5508. 5.1片段分割逻辑(优先级从高到低):
  5509. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  5510. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  5511. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  5512. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  5513. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  5514. - 片段数量格式为: 片段数量:8
  5515. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5516. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  5517. 5.3分镜结构:每个分镜包含以下字段:
  5518. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  5519. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5520. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5521. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5522. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  5523. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5524. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5525. - 运镜:场景+画面描述+运镜
  5526. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  5527. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  5528. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  5529. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  5530. 6.{$mappedArtStyle_prompt}\n\n
  5531. 示例如下:\n
  5532. ###剧本名:西昆仑
  5533. ###故事梗概
  5534. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5535. ###剧本亮点
  5536. 亮点1:绝境奇药,生死一线
  5537. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5538. 亮点2:结拜兄妹,化解尴尬
  5539. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5540. 亮点3:纤发夺命,情愫暗涌
  5541. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5542. ###人物关系
  5543. 阿雪与梁萧之间存在兄妹之情。
  5544. ###核心矛盾
  5545. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5546. ###主体列表
  5547. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5548. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5549. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5550. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5551. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5552. 全景,正面拍摄,青年女性,亚洲人。
  5553. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5554. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5555. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5556. ###美术风格
  5557. 基础画风风格词:厚涂古风
  5558. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5559. ###场景列表
  5560. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5561. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5562. 无人物。}
  5563. ###分段剧本
  5564. 片段数量:8
  5565. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  5566. ##片段1
  5567. 时长:12s
  5568. 分镜1
  5569. 出场角色:刀疤脸
  5570. 场景:边境小镇街道
  5571. 出场道具:酒杯-高脚杯
  5572. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  5573. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  5574. 配音台词:
  5575. 背景音效:
  5576. 分镜2
  5577. 出场角色:刀疤脸
  5578. 场景:悦来酒馆
  5579. 出场道具:酒杯-高脚杯
  5580. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  5581. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  5582. 配音台词:
  5583. 背景音效:
  5584. 分镜3
  5585. 出场角色:刀疤脸
  5586. 场景:悦来酒馆
  5587. 出场道具:酒杯-高脚杯
  5588. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  5589. 运镜:从中景推向令牌特写。
  5590. 配音台词:
  5591. 背景音效:
  5592. 分镜4
  5593. 出场角色:刀疤脸
  5594. 场景:悦来酒馆
  5595. 出场道具:酒杯-高脚杯
  5596. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  5597. 运镜:极速推向酒水溅起的瞬间。
  5598. 配音台词:
  5599. 背景音效:
  5600. 分镜5
  5601. 出场角色:刀疤脸
  5602. 场景:悦来酒馆
  5603. 出场道具:酒杯-高脚杯
  5604. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  5605. 运镜:固定机位,利用倾斜构图制造压迫感。
  5606. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  5607. 背景音效:
  5608. \n\n"
  5609. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5610. 强制要求:\n
  5611. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5612. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5613. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5614. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5615. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5616. 普通要求:\n
  5617. 1.剧本名(必须生成)必须与文档内容高度相关
  5618. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5619. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5620. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5621. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5622. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5623. {$extra_role_prompt}
  5624. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5625. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5626. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5627. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5628. {$extra_scene_prompt}
  5629. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5630. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5631. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5632. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5633. {$extra_prop_prompt}
  5634. 5.{$mappedArtStyle_prompt}\n\n
  5635. 示例如下:\n
  5636. ###剧本名:西昆仑
  5637. ###故事梗概
  5638. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5639. ###剧本亮点
  5640. 亮点1:绝境奇药,生死一线
  5641. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5642. 亮点2:结拜兄妹,化解尴尬
  5643. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5644. 亮点3:纤发夺命,情愫暗涌
  5645. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5646. ###人物关系
  5647. 阿雪与梁萧之间存在兄妹之情。
  5648. ###核心矛盾
  5649. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5650. ###主体列表
  5651. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5652. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5653. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5654. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5655. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5656. 全景,正面拍摄,青年女性,亚洲人。
  5657. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5658. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5659. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5660. ###美术风格
  5661. 基础画风风格词:厚涂古风
  5662. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5663. ###场景列表
  5664. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5665. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5666. 无人物。}
  5667. ###道具列表
  5668. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  5669. // 构建消息
  5670. $messages = [
  5671. [
  5672. 'role' => 'system',
  5673. 'content' => $systemPrompt
  5674. ],
  5675. [
  5676. 'role' => 'user',
  5677. 'content' => "以下是文档内容:
  5678. {$content}
  5679. 用户问题:
  5680. {$question}"
  5681. ]
  5682. ];
  5683. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5684. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5685. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5686. if ($model === 'deepseek-chat') {
  5687. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5688. $model = 'deepseek-v4-flash';
  5689. $thinkingMode = 'disabled';
  5690. } elseif ($model === 'deepseek-reasoner') {
  5691. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5692. $model = 'deepseek-v4-flash';
  5693. $thinkingMode = 'enabled';
  5694. }
  5695. $post_data = [
  5696. 'model' => $model,
  5697. 'messages' => $messages,
  5698. // 'max_tokens' => 8192,
  5699. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  5700. 'frequency_penalty' => 0,
  5701. 'presence_penalty' => 0,
  5702. 'response_format' => ['type' => 'text'],
  5703. 'thinking' => ['type'=>$thinkingMode],
  5704. 'stream' => true // 启用流式输出
  5705. ];
  5706. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5707. // 根据模型类型选择调用方法
  5708. $fullContent = '';
  5709. $fullReasoningContent = '';
  5710. $usage = [];
  5711. try {
  5712. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5713. // DeepSeek 官方模型使用 DeepSeek API
  5714. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5715. } else if (in_array($model, $this->gpt_text_models)) {
  5716. // GPT-5.4 模型使用 TokenRouter API
  5717. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5718. } else {
  5719. // 其他模型使用火山引擎API
  5720. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5721. }
  5722. // 验证返回值类型
  5723. if (!is_iterable($streamGenerator)) {
  5724. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5725. dLog('deepseek')->error('addChat流式生成器无效', [
  5726. 'generator_type' => $errorType,
  5727. 'model' => $model,
  5728. 'anime_id' => $anime_id
  5729. ]);
  5730. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5731. 'type' => $errorType,
  5732. 'model' => $model
  5733. ]);
  5734. yield [
  5735. 'type' => 'error',
  5736. 'script' => [],
  5737. 'episode' => [],
  5738. 'answer' => '',
  5739. 'reasoning' => '',
  5740. 'usage' => [],
  5741. 'error' => '接口返回数据异常,请重新请求'
  5742. ];
  5743. return;
  5744. }
  5745. // 处理流式输出
  5746. foreach ($streamGenerator as $chunk) {
  5747. if (isset($chunk['type'])) {
  5748. if ($chunk['type'] === 'done') {
  5749. // 最终结果
  5750. $fullContent = $chunk['full_content'];
  5751. $fullReasoningContent = $chunk['full_reasoning'];
  5752. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5753. } else {
  5754. // 逐块yield数据
  5755. yield $chunk;
  5756. }
  5757. }
  5758. }
  5759. } catch (\Exception $e) {
  5760. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5761. 'model' => $model,
  5762. 'anime_id' => $anime_id,
  5763. 'trace' => $e->getTraceAsString()
  5764. ]);
  5765. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5766. 'error' => $e->getMessage(),
  5767. 'model' => $model
  5768. ]);
  5769. yield [
  5770. 'type' => 'error',
  5771. 'script' => [],
  5772. 'episode' => [],
  5773. 'answer' => '',
  5774. 'reasoning' => '',
  5775. 'usage' => [],
  5776. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5777. ];
  5778. return;
  5779. }
  5780. dLog('deepseek')->info('完整内容: '.$fullContent);
  5781. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5782. // 处理完整内容并返回最终结果
  5783. $script_arr = [];
  5784. if ($fullContent) {
  5785. $script_arr = handleScriptContentForAce($fullContent);
  5786. dLog('deepseek')->info('解析内容', $script_arr);
  5787. logDB('deepseek', 'info', '解析内容', $script_arr);
  5788. }
  5789. if (empty($script_arr['roles'])) {
  5790. // 未生成剧本相关内容,保存对话记录并返回提示
  5791. dLog('deepseek')->info('未生成剧本相关的内容');
  5792. try {
  5793. DB::beginTransaction();
  5794. $now = date('Y-m-d H:i:s');
  5795. // 保存对话记录
  5796. $records = [
  5797. [
  5798. 'uid' => $uid,
  5799. 'anime_id' => $anime_id,
  5800. 'sequence' => 0,
  5801. 'role' => 'user',
  5802. 'content' => $prompt,
  5803. 'created_at' => $now,
  5804. 'updated_at' => $now
  5805. ],
  5806. [
  5807. 'uid' => $uid,
  5808. 'anime_id' => $anime_id,
  5809. 'sequence' => 0,
  5810. 'role' => 'assistant',
  5811. // 'content' => $fullContent,
  5812. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5813. 'created_at' => $now,
  5814. 'updated_at' => $now
  5815. ]
  5816. ];
  5817. DB::table('mp_anime_records')->insert($records);
  5818. DB::commit();
  5819. } catch (\Exception $e) {
  5820. DB::rollBack();
  5821. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5822. }
  5823. yield [
  5824. 'type' => 'done',
  5825. 'script' => [],
  5826. 'episode' => [],
  5827. 'answer' => $fullContent,
  5828. 'reasoning' => $fullReasoningContent,
  5829. 'usage' => $usage,
  5830. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5831. ];
  5832. return;
  5833. }
  5834. // 如果需要生成原文内容,从script_arr中提取
  5835. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5836. $content = $script_arr['content'];
  5837. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5838. if (!$content) {
  5839. yield [
  5840. 'type' => 'done',
  5841. 'script' => [],
  5842. 'episode' => [],
  5843. 'answer' => $fullContent,
  5844. 'reasoning' => $fullReasoningContent,
  5845. 'usage' => $usage,
  5846. 'error' => '未生成剧本内容,请调整提示词再试'
  5847. ];
  5848. return;
  5849. }
  5850. }
  5851. // 替换美术风格
  5852. if ($mappedArtStyle !== '') {
  5853. $script_arr['art_style'] = $mappedArtStyle;
  5854. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5855. }
  5856. // 新建动漫
  5857. if ($user_anime_name == '新剧本策划') {
  5858. $anime_name = getProp($script_arr, 'script_name');
  5859. // if (!$anime_name) {
  5860. // // 未识别到剧本名,保存对话记录并返回提示
  5861. // dLog('deepseek')->info('未能识别到剧本名称');
  5862. // try {
  5863. // DB::beginTransaction();
  5864. // $now = date('Y-m-d H:i:s');
  5865. // // 保存对话记录
  5866. // $records = [
  5867. // [
  5868. // 'uid' => $uid,
  5869. // 'anime_id' => $anime_id,
  5870. // 'sequence' => 0,
  5871. // 'role' => 'user',
  5872. // 'content' => $prompt,
  5873. // 'created_at' => $now,
  5874. // 'updated_at' => $now
  5875. // ],
  5876. // [
  5877. // 'uid' => $uid,
  5878. // 'anime_id' => $anime_id,
  5879. // 'sequence' => 0,
  5880. // 'role' => 'assistant',
  5881. // 'content' => '未能生成剧本名称,请重试',
  5882. // 'created_at' => $now,
  5883. // 'updated_at' => $now
  5884. // ]
  5885. // ];
  5886. // DB::table('mp_anime_records')->insert($records);
  5887. // DB::commit();
  5888. // } catch (\Exception $e) {
  5889. // DB::rollBack();
  5890. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5891. // }
  5892. // yield [
  5893. // 'type' => 'done',
  5894. // 'script' => [],
  5895. // 'episode' => [],
  5896. // 'answer' => $fullContent,
  5897. // 'reasoning' => $fullReasoningContent,
  5898. // 'usage' => $usage,
  5899. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  5900. // ];
  5901. // return;
  5902. // }
  5903. // 确认对话名称唯一性
  5904. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5905. $anime_name = $anime_name . '_' . date('YmdHis');
  5906. }
  5907. }else {
  5908. $anime_name = $user_anime_name;
  5909. }
  5910. $table_data = [
  5911. 'user_id' => $uid,
  5912. 'anime_name' => $anime_name,
  5913. 'model' => $model,
  5914. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5915. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5916. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5917. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5918. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5919. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5920. 'art_style_type' => $input_art_style,
  5921. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5922. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  5923. 'status' => '解析完成',
  5924. 'content' => $content,
  5925. 'is_multi' => $is_multi,
  5926. 'ace_mode' => $ace_mode,
  5927. 'generate_status' => '待执行',
  5928. 'updated_at' => date('Y-m-d H:i:s')
  5929. ];
  5930. if ($table_data['content']) {
  5931. $chapters = splitContent($table_data['content']);
  5932. $chapter_count = count($chapters);
  5933. if ($chapter_count > 0) {
  5934. $table_data['start_episode_sequence'] = 1;
  5935. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5936. }
  5937. }
  5938. if ($extra_products) {
  5939. $table_data['extra_products'] = json_encode($extra_products, 256);
  5940. }
  5941. // 如果有剧本ID则进行绑定
  5942. if ($script_id) {
  5943. $table_data['script_id'] = $script_id;
  5944. }
  5945. $single_episode = [];
  5946. try {
  5947. DB::beginTransaction();
  5948. $now = date('Y-m-d H:i:s');
  5949. // 更新动漫大纲
  5950. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5951. if (!$boolen) {
  5952. dLog('deepseek')->info('动漫保存失败', $table_data);
  5953. Utils::throwError('20003:动漫保存失败');
  5954. }
  5955. // 保存对话记录
  5956. $records = [
  5957. [
  5958. 'uid' => $uid,
  5959. 'anime_id' => $anime_id,
  5960. 'sequence' => 0,
  5961. 'role' => 'user',
  5962. 'content' => $prompt,
  5963. 'created_at' => date('Y-m-d H:i:s'),
  5964. 'updated_at' => date('Y-m-d H:i:s')
  5965. ],
  5966. [
  5967. 'uid' => $uid,
  5968. 'anime_id' => $anime_id,
  5969. 'sequence' => 0,
  5970. 'role' => 'assistant',
  5971. 'content' => $fullContent,
  5972. 'created_at' => date('Y-m-d H:i:s'),
  5973. 'updated_at' => date('Y-m-d H:i:s')
  5974. ]
  5975. ];
  5976. // 保存对话记录
  5977. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5978. if (!$boolen3) {
  5979. Utils::throwError('20003:对话记录保存失败');
  5980. }
  5981. if ($is_single) {
  5982. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5983. if (empty($episode_arr['acts'])) {
  5984. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5985. }
  5986. $saveResult = $this->saveEpisodeVersionData(
  5987. $anime_id,
  5988. 1,
  5989. $episode_arr,
  5990. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5991. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5992. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5993. null,
  5994. null,
  5995. false,
  5996. $content,
  5997. $now,
  5998. $ref_products
  5999. );
  6000. $single_episode = $saveResult['episode'];
  6001. $episode_id = $saveResult['episode_id'];
  6002. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6003. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6004. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6005. 'props' => json_encode($saveResult['merged_props'], 256),
  6006. 'updated_at' => $now
  6007. ]);
  6008. if ($boolen5 === false) {
  6009. Utils::throwError('20003:单剧集主表资源同步失败');
  6010. }
  6011. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6012. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6013. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6014. $episode_record_content = '确认分镜大纲';
  6015. if ($content !== '') {
  6016. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6017. }
  6018. $episode_records = [
  6019. [
  6020. 'uid' => $uid,
  6021. 'anime_id' => $anime_id,
  6022. 'role' => 'user',
  6023. 'content' => $episode_record_content,
  6024. 'sequence' => 1,
  6025. 'episode_id' => $episode_id,
  6026. 'created_at' => $now,
  6027. 'updated_at' => $now
  6028. ],
  6029. [
  6030. 'uid' => $uid,
  6031. 'anime_id' => $anime_id,
  6032. 'role' => 'assistant',
  6033. 'content' => $fullContent,
  6034. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6035. 'sequence' => 1,
  6036. 'episode_id' => $episode_id,
  6037. 'created_at' => $now,
  6038. 'updated_at' => $now
  6039. ]
  6040. ];
  6041. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6042. if (!$boolen4) {
  6043. Utils::throwError('20003:单剧集分镜记录保存失败');
  6044. }
  6045. }
  6046. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6047. if ($is_single && !empty($single_episode)) {
  6048. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6049. 'anime_id' => $anime_id,
  6050. 'episode_id' => $episode_id ?? 0,
  6051. ]);
  6052. }
  6053. }catch (\Exception $e) {
  6054. DB::rollBack();
  6055. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6056. yield [
  6057. 'type' => 'done',
  6058. 'answer' => $fullContent,
  6059. 'reasoning' => $fullReasoningContent,
  6060. 'usage' => $usage,
  6061. 'error' => $e->getMessage(),
  6062. ];
  6063. return;
  6064. }
  6065. DB::commit();
  6066. dLog('deepseek')->info('保存完毕');
  6067. if ($is_single && !empty($single_episode)) {
  6068. // $this->batchSetGlobalRoleImg([
  6069. // 'anime_id' => $anime_id,
  6070. // ]);
  6071. // $this->batchSetGlobalSceneImg([
  6072. // 'anime_id' => $anime_id,
  6073. // ]);
  6074. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6075. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6076. }
  6077. $table_data['anime_id'] = $anime_id;
  6078. $table_data['roles'] = json_decode($table_data['roles'], true);
  6079. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6080. // $table_data['episodes'] = $script_arr['episodes'];
  6081. unset($table_data['created_at']);
  6082. unset($table_data['updated_at']);
  6083. unset($table_data['status']);
  6084. dLog('deepseek')->info('开始返回');
  6085. yield [
  6086. 'type' => 'done',
  6087. 'script' => $table_data,
  6088. 'episode' => $single_episode,
  6089. 'answer' => $fullContent,
  6090. 'reasoning' => $fullReasoningContent,
  6091. 'usage' => $usage
  6092. ];
  6093. }
  6094. public function reGenerateAnimeForAce($data) {
  6095. $uid = Site::getUid();
  6096. $file = getProp($data, 'file');
  6097. $content = getProp($data, 'content', '');
  6098. $bid = getProp($data, 'bid', 0);
  6099. $script_id = getProp($data, 'script_id', 0);
  6100. $anime_id = getProp($data, 'anime_id');
  6101. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6102. if (!$anime) {
  6103. Utils::throwError('20003:该对话不存在');
  6104. }
  6105. $is_multi = getProp($anime, 'is_multi', 1);
  6106. $is_single = (int)$is_multi !== 1;
  6107. // 积分余额预检(仅单剧集模式收费)
  6108. if ($is_single) {
  6109. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  6110. }
  6111. $extra_products = getProp($data, 'products', []);
  6112. if (!$extra_products) {
  6113. $extra_products = getProp($anime, 'extra_products');
  6114. if ($extra_products) {
  6115. $extra_products = json_decode($extra_products, true);
  6116. }else {
  6117. $extra_products = [];
  6118. }
  6119. }else {
  6120. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6121. }
  6122. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6123. $anime_script_id = getProp($anime, 'script_id');
  6124. if ($anime_script_id && $is_single) {
  6125. $cpid = Site::getCpid();
  6126. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6127. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6128. ->where('mapping.script_id', $anime_script_id)
  6129. ->where('product.cpid', $cpid)
  6130. ->where('product.is_deleted', 0);
  6131. $mappings = $script_products_mappings->select(
  6132. 'mapping.product_id',
  6133. 'mapping.episode_number',
  6134. 'product.product_name',
  6135. 'product.type',
  6136. 'product.product',
  6137. 'product.pic_prompt',
  6138. 'product.url',
  6139. 'product.pic_task_id',
  6140. 'product.pic_task_status',
  6141. 'product.three_view_image_url'
  6142. )
  6143. ->get();
  6144. // 按 product_id 分组,合并 episode_number
  6145. $productMap = [];
  6146. foreach ($mappings as $item) {
  6147. $product_id = $item->product_id;
  6148. $product_name = $item->product_name;
  6149. // 处理product_name两边的符号
  6150. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6151. if (!isset($productMap[$product_id])) {
  6152. $productMap[$product_id] = [
  6153. 'product_id' => $product_id,
  6154. 'product_name' => $product_name,
  6155. 'type' => (int)$item->type,
  6156. 'product' => (int)$item->product,
  6157. 'pic_prompt' => $item->pic_prompt,
  6158. 'url' => $item->url,
  6159. 'pic_task_id' => $item->pic_task_id,
  6160. 'pic_task_status' => $item->pic_task_status,
  6161. 'episode_numbers' => [],
  6162. ];
  6163. }
  6164. // 添加 episode_number(去重)
  6165. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6166. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6167. }
  6168. }
  6169. // 将查询到的剧本资产合并到extra_products中
  6170. // 先构建extra_products的索引(以product_id为key,用于去重)
  6171. $extraProductsMap = [];
  6172. foreach ($extra_products as $item) {
  6173. $key = getProp($item, 'product_id');
  6174. if ($key) {
  6175. $extraProductsMap[$key] = $item;
  6176. }
  6177. }
  6178. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6179. foreach ($productMap as $product) {
  6180. $product_id = $product['product_id'];
  6181. // 如果不存在则添加(不带episode_number信息)
  6182. if (!isset($extraProductsMap[$product_id])) {
  6183. $extraProductsMap[$product_id] = [
  6184. 'product_id' => $product['product_id'],
  6185. 'product_name' => $product['product_name'],
  6186. 'type' => $product['type'],
  6187. 'product' => $product['product'],
  6188. 'pic_prompt' => $product['pic_prompt'],
  6189. 'url' => $product['url'],
  6190. 'pic_task_id' => $product['pic_task_id'],
  6191. 'pic_task_status' => $product['pic_task_status'],
  6192. ];
  6193. }
  6194. }
  6195. // 重新赋值给extra_products
  6196. $extra_products = array_values($extraProductsMap);
  6197. }
  6198. $user_anime_name = getProp($anime, 'anime_name');
  6199. $prompt = getProp($data, 'prompt');
  6200. // 处理提示词
  6201. if ($prompt && $extra_products) {
  6202. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6203. foreach($extra_products as $item) {
  6204. $product_name = getProp($item, 'product_name');
  6205. if ($product_name) {
  6206. // 替换 {product_name} 为 product_name
  6207. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6208. }
  6209. }
  6210. }
  6211. // 处理文本模型
  6212. $model = getProp($data, 'model');
  6213. if (!$model) {
  6214. // 用户没有输入,从anime表获取
  6215. $model = getProp($anime, 'model');
  6216. if (!$model) {
  6217. // anime表也没有,使用默认值
  6218. $model = 'deepseek-v4-pro';
  6219. }
  6220. }
  6221. // 验证模型是否在可用模型表中
  6222. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6223. $model = 'deepseek-v4-pro';
  6224. }
  6225. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  6226. if ($is_single) {
  6227. $episode_exists = DB::table('mp_anime_episodes')
  6228. ->where('anime_id', $anime_id)
  6229. ->where('sequence', 1)
  6230. ->exists();
  6231. if ($episode_exists) {
  6232. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  6233. }
  6234. }
  6235. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6236. if ($prompt) {
  6237. $question .= "本次修改要求如下:\n{$prompt}";
  6238. }
  6239. // 提取文件内容
  6240. if ($file) {
  6241. $content = $this->extractFileContent($file);
  6242. if (!$content) {
  6243. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6244. }
  6245. } elseif ($script_id) {
  6246. $content = $this->getContentByScriptId($script_id);
  6247. if (!$content) {
  6248. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6249. }
  6250. } elseif ($bid) {
  6251. $content = $this->getContentByBid($bid);
  6252. if (!$content) {
  6253. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6254. }
  6255. } elseif ($content) {
  6256. $content = filterContent($content);
  6257. }else {
  6258. $content = filterContent(getProp($anime, 'content'));
  6259. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6260. $need_generate_content = true;
  6261. }
  6262. }
  6263. // 判断是否需要生成原文内容
  6264. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6265. // 如果需要生成原文内容,添加额外的要求
  6266. $content_generation_requirement = $need_generate_content
  6267. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6268. : "";
  6269. // 美术风格
  6270. $input_art_style = getProp($data, 'art_style');
  6271. if (!$input_art_style) {
  6272. $mappedArtStyle = getProp($anime, 'art_style');
  6273. }else {
  6274. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6275. }
  6276. if (!$mappedArtStyle) {
  6277. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6278. }else {
  6279. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6280. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6281. }else {
  6282. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6283. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6284. }
  6285. }
  6286. // 构建主体、场景和道具提示词
  6287. $extra_role_prompt = "\n";
  6288. $extra_scene_prompt = "\n";
  6289. $extra_prop_prompt = "\n";
  6290. $ref_products = []; // 参考资产
  6291. if ($extra_products) {
  6292. foreach($extra_products as $item) {
  6293. $product = getProp($item, 'product');
  6294. $product_name = getProp($item, 'product_name');
  6295. if ($product_name == '旁白') continue;
  6296. $ref_products[$product_name] = $item;
  6297. $pic_prompt = getProp($item, 'pic_prompt');
  6298. if ((int)$product === 1) {
  6299. // 拼接角色信息
  6300. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6301. } elseif ((int)$product === 2) {
  6302. // 拼接场景信息
  6303. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6304. } elseif ((int)$product === 3) {
  6305. // 拼接道具信息
  6306. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6307. }
  6308. }
  6309. // 优化提示词,融入剧本
  6310. if (!empty(trim($extra_role_prompt))) {
  6311. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6312. }
  6313. if (!empty(trim($extra_scene_prompt))) {
  6314. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6315. }
  6316. if (!empty(trim($extra_prop_prompt))) {
  6317. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6318. }
  6319. }
  6320. if ($anime_script_id && $is_single) {
  6321. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6322. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6323. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6324. }else {
  6325. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6326. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6327. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6328. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6329. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6330. {$extra_role_prompt}";
  6331. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6332. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6333. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6334. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6335. {$extra_scene_prompt}";
  6336. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6337. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6338. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6339. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6340. {$extra_prop_prompt}";
  6341. }
  6342. $system_message = ['role'=>'system', 'content'=>$is_single
  6343. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6344. 强制要求:
  6345. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6346. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6347. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6348. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6349. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6350. 普通要求:
  6351. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6352. $role_demo
  6353. $scene_demo
  6354. $prop_demo
  6355. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6356. 5.1片段分割逻辑(优先级从高到低):
  6357. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6358. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6359. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6360. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6361. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6362. - 片段数量格式为: 片段数量:8
  6363. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6364. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6365. 5.3分镜结构:每个分镜包含以下字段:
  6366. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6367. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6368. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6369. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6370. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6371. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6372. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6373. - 运镜:场景+画面描述+运镜
  6374. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  6375. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  6376. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6377. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6378. 6.{$mappedArtStyle_prompt}\n\n
  6379. 示例如下:\n
  6380. ###剧本名:西昆仑
  6381. ###故事梗概
  6382. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6383. ###剧本亮点
  6384. 亮点1:绝境奇药,生死一线
  6385. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6386. 亮点2:结拜兄妹,化解尴尬
  6387. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6388. 亮点3:纤发夺命,情愫暗涌
  6389. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6390. ###人物关系
  6391. 阿雪与梁萧之间存在兄妹之情。
  6392. ###核心矛盾
  6393. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6394. ###主体列表
  6395. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6396. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6397. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6398. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6399. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6400. 全景,正面拍摄,青年女性,亚洲人。
  6401. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6402. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6403. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6404. ###美术风格
  6405. 基础画风风格词:厚涂古风
  6406. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6407. ###场景列表
  6408. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6409. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6410. 无人物。}
  6411. ###分段剧本
  6412. 片段数量:8
  6413. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6414. ##片段1
  6415. 时长:12s
  6416. 分镜1
  6417. 出场角色:刀疤脸
  6418. 场景:边境小镇街道
  6419. 出场道具:酒杯-高脚杯
  6420. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6421. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6422. 配音台词:
  6423. 背景音效:
  6424. 分镜2
  6425. 出场角色:刀疤脸
  6426. 场景:悦来酒馆
  6427. 出场道具:酒杯-高脚杯
  6428. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6429. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6430. 配音台词:
  6431. 背景音效:
  6432. 分镜3
  6433. 出场角色:刀疤脸
  6434. 场景:悦来酒馆
  6435. 出场道具:酒杯-高脚杯
  6436. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6437. 运镜:从中景推向令牌特写。
  6438. 配音台词:
  6439. 背景音效:
  6440. 分镜4
  6441. 出场角色:刀疤脸
  6442. 场景:悦来酒馆
  6443. 出场道具:酒杯-高脚杯
  6444. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6445. 运镜:极速推向酒水溅起的瞬间。
  6446. 配音台词:
  6447. 背景音效:
  6448. 分镜5
  6449. 出场角色:刀疤脸
  6450. 场景:悦来酒馆
  6451. 出场道具:酒杯-高脚杯
  6452. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6453. 运镜:固定机位,利用倾斜构图制造压迫感。
  6454. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6455. 背景音效:
  6456. \n\n"
  6457. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6458. 强制要求:\n
  6459. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6460. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6461. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6462. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6463. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6464. 普通要求:\n
  6465. 1.剧本名(必须生成)必须与文档内容高度相关
  6466. $role_demo
  6467. $scene_demo
  6468. $prop_demo
  6469. 5.{$mappedArtStyle_prompt}\n\n
  6470. 示例如下:\n
  6471. ###剧本名:西昆仑
  6472. ###故事梗概
  6473. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6474. ###剧本亮点
  6475. 亮点1:绝境奇药,生死一线
  6476. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6477. 亮点2:结拜兄妹,化解尴尬
  6478. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6479. 亮点3:纤发夺命,情愫暗涌
  6480. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6481. ###人物关系
  6482. 阿雪与梁萧之间存在兄妹之情。
  6483. ###核心矛盾
  6484. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6485. ###主体列表
  6486. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6487. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6488. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6489. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6490. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6491. 全景,正面拍摄,青年女性,亚洲人。
  6492. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6493. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6494. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6495. ###美术风格
  6496. 基础画风风格词:厚涂古风
  6497. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6498. ###场景列表
  6499. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6500. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6501. 无人物。}
  6502. ###道具列表
  6503. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  6504. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6505. $episode_count = $this->extractEpisodeNumber($prompt);
  6506. if ((int)getProp($anime, 'is_multi') !== 1) {
  6507. yield [
  6508. 'type' => 'done',
  6509. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6510. 'reasoning' => '',
  6511. 'usage' => []
  6512. ];
  6513. return;
  6514. }
  6515. if ($episode_count) {
  6516. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6517. $system_message = [
  6518. 'role' => 'system',
  6519. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6520. 强制要求:\n
  6521. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6522. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6523. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6524. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6525. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6526. 普通要求:\n
  6527. 1.<故事梗概>控制在200-300字左右
  6528. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6529. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6530. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6531. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6532. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6533. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6534. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6535. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6536. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6537. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6538. 示例如下:\n
  6539. ###剧本名:西昆仑
  6540. ###故事梗概
  6541. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6542. ###剧本亮点
  6543. 亮点1:绝境奇药,生死一线
  6544. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6545. 亮点2:结拜兄妹,化解尴尬
  6546. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6547. 亮点3:纤发夺命,情愫暗涌
  6548. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6549. ###人物关系
  6550. 阿雪与梁萧之间存在兄妹之情。
  6551. ###核心矛盾
  6552. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6553. ###主体列表
  6554. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6555. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6556. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6557. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6558. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6559. 全景,正面拍摄,青年女性,亚洲人。
  6560. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6561. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6562. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6563. ###美术风格
  6564. 基础画风风格词:厚涂古风
  6565. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6566. ###场景列表
  6567. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6568. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6569. 无人物。}
  6570. ###分集详细内容
  6571. ##第1章 重生
  6572. 我重生了。
  6573. 源于一个男人偏执的暗恋。
  6574. ##第2章 相救
  6575. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6576. 我眼睛扫向站在锅炉后的卞大伟。"
  6577. ];
  6578. // 构建消息
  6579. $messages = [
  6580. $system_message,
  6581. [
  6582. 'role' => 'user',
  6583. 'content' => "以下是文档内容:
  6584. {$content}
  6585. 用户问题:
  6586. {$question}"
  6587. ]
  6588. ];
  6589. }else {
  6590. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6591. // 构建消息
  6592. $messages = [
  6593. $system_message,
  6594. [
  6595. 'role' => 'user',
  6596. 'content' => "以下是文档内容:
  6597. {$content}
  6598. 用户问题:
  6599. {$question}"
  6600. ]
  6601. ];
  6602. }else {
  6603. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6604. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6605. return (array)$value;
  6606. })->toArray();
  6607. array_unshift($messages, $system_message);
  6608. $messages[] = [
  6609. 'role' => 'user',
  6610. 'content' => $prompt
  6611. ];
  6612. }
  6613. }
  6614. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6615. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6616. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6617. if ($model === 'deepseek-chat') {
  6618. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6619. $model = 'deepseek-v4-flash';
  6620. $thinkingMode = 'disabled';
  6621. } elseif ($model === 'deepseek-reasoner') {
  6622. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6623. $model = 'deepseek-v4-flash';
  6624. $thinkingMode = 'enabled';
  6625. }
  6626. $post_data = [
  6627. 'model' => $model,
  6628. 'messages' => $messages,
  6629. // 'max_tokens' => 8192,
  6630. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  6631. 'frequency_penalty' => 0,
  6632. 'presence_penalty' => 0,
  6633. 'response_format' => ['type' => 'text'],
  6634. 'thinking' => ['type' => $thinkingMode],
  6635. 'stream' => true // 启用流式输出
  6636. ];
  6637. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6638. // 根据模型类型选择调用方法
  6639. $fullContent = '';
  6640. $fullReasoningContent = '';
  6641. $usage = [];
  6642. // dd($post_data);
  6643. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6644. try {
  6645. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6646. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6647. } else if (in_array($model, $this->gpt_text_models)) {
  6648. // GPT-5.4 模型使用 TokenRouter API
  6649. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6650. } else {
  6651. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6652. }
  6653. // 验证返回值类型
  6654. if (!is_iterable($streamGenerator)) {
  6655. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6656. dLog('deepseek')->error('方法名流式生成器无效', [
  6657. 'generator_type' => $errorType,
  6658. 'model' => $model,
  6659. // 添加其他上下文信息
  6660. ]);
  6661. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6662. 'type' => $errorType,
  6663. 'model' => $model
  6664. ]);
  6665. yield [
  6666. 'type' => 'error',
  6667. // 根据方法返回相应的空数据结构
  6668. 'answer' => '',
  6669. 'reasoning' => '',
  6670. 'usage' => [],
  6671. 'error' => '接口返回数据异常,请重新请求'
  6672. ];
  6673. return;
  6674. }
  6675. // 处理流式输出
  6676. foreach ($streamGenerator as $chunk) {
  6677. if (isset($chunk['type'])) {
  6678. if ($chunk['type'] === 'done') {
  6679. $fullContent = $chunk['full_content'];
  6680. $fullReasoningContent = $chunk['full_reasoning'];
  6681. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6682. } else {
  6683. yield $chunk;
  6684. }
  6685. }
  6686. }
  6687. } catch (\Exception $e) {
  6688. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6689. 'model' => $model,
  6690. 'trace' => $e->getTraceAsString()
  6691. ]);
  6692. logDB('deepseek', 'error', '方法名流式处理失败', [
  6693. 'error' => $e->getMessage(),
  6694. 'model' => $model
  6695. ]);
  6696. yield [
  6697. 'type' => 'error',
  6698. // 根据方法返回相应的空数据结构
  6699. 'answer' => '',
  6700. 'reasoning' => '',
  6701. 'usage' => [],
  6702. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6703. ];
  6704. return;
  6705. }
  6706. dLog('deepseek')->info('完整内容: '.$fullContent);
  6707. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6708. // 处理完整内容并返回最终结果
  6709. $script_arr = [];
  6710. if ($fullContent) {
  6711. $script_arr = handleScriptContentForAce($fullContent);
  6712. dLog('deepseek')->info('解析内容', $script_arr);
  6713. logDB('deepseek', 'info', '解析内容', $script_arr);
  6714. }
  6715. if (empty($script_arr['roles'])) {
  6716. // 未生成剧本相关内容,保存对话记录并返回提示
  6717. dLog('deepseek')->info('未生成剧本相关的内容');
  6718. try {
  6719. $now = date('Y-m-d H:i:s');
  6720. // 保存对话记录
  6721. $records = [
  6722. [
  6723. 'uid' => $uid,
  6724. 'anime_id' => $anime_id,
  6725. 'sequence' => 0,
  6726. 'role' => 'user',
  6727. 'content' => $prompt,
  6728. 'created_at' => $now,
  6729. 'updated_at' => $now
  6730. ],
  6731. [
  6732. 'uid' => $uid,
  6733. 'anime_id' => $anime_id,
  6734. 'sequence' => 0,
  6735. 'role' => 'assistant',
  6736. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6737. 'created_at' => $now,
  6738. 'updated_at' => $now
  6739. ]
  6740. ];
  6741. DB::table('mp_anime_records')->insert($records);
  6742. } catch (\Exception $e) {
  6743. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6744. }
  6745. yield [
  6746. 'type' => 'done',
  6747. 'script' => [],
  6748. 'episode' => [],
  6749. 'answer' => $fullContent,
  6750. 'reasoning' => $fullReasoningContent,
  6751. 'usage' => $usage,
  6752. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6753. ];
  6754. return;
  6755. }
  6756. // 替换美术风格
  6757. if ($mappedArtStyle !== '') {
  6758. $script_arr['art_style'] = $mappedArtStyle;
  6759. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6760. }
  6761. if ($user_anime_name != '新剧本策划') {
  6762. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  6763. // 确认对话名称唯一性
  6764. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6765. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6766. }
  6767. }else {
  6768. $anime_name = $user_anime_name;
  6769. }
  6770. $table_data = [
  6771. 'user_id' => $uid,
  6772. 'model' => $model,
  6773. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6774. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6775. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6776. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6777. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6778. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6779. 'art_style_type' => $input_art_style,
  6780. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6781. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6782. 'status' => '解析完成',
  6783. 'generate_status' => '待执行',
  6784. 'updated_at' => date('Y-m-d H:i:s')
  6785. ];
  6786. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6787. // 如果是修改集数,则将content内容更新(会改变原文)
  6788. if (isset($episode_count) && $episode_count > 0) {
  6789. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6790. $table_data['start_episode_sequence'] = 1;
  6791. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6792. }else {
  6793. // 如果需要生成原文内容,从script_arr中提取
  6794. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6795. $table_data['content'] = $script_arr['content'];
  6796. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6797. if (!$table_data['content']) {
  6798. yield [
  6799. 'type' => 'done',
  6800. 'script' => [],
  6801. 'episode' => [],
  6802. 'answer' => $fullContent,
  6803. 'reasoning' => $fullReasoningContent,
  6804. 'usage' => $usage,
  6805. 'error' => '未生成剧本内容,请调整提示词再试'
  6806. ];
  6807. return;
  6808. }
  6809. }
  6810. if (isset($table_data['content']) && $table_data['content']) {
  6811. $chapters = splitContent($table_data['content']);
  6812. $chapter_count = count($chapters);
  6813. if ($chapter_count > 0) {
  6814. $table_data['start_episode_sequence'] = 1;
  6815. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6816. }
  6817. }
  6818. }
  6819. if ($extra_products) {
  6820. $table_data['extra_products'] = json_encode($extra_products, 256);
  6821. }
  6822. $single_episode = [];
  6823. try {
  6824. DB::beginTransaction();
  6825. $now = date('Y-m-d H:i:s');
  6826. // 更新动漫大纲
  6827. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6828. if (!$boolen) {
  6829. dLog('deepseek')->info('对话修改失败', $table_data);
  6830. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6831. Utils::throwError('20003:对话修改失败');
  6832. }
  6833. // 保存对话记录
  6834. $records = [
  6835. [
  6836. 'uid' => $uid,
  6837. 'anime_id' => $anime_id,
  6838. 'sequence' => 0,
  6839. 'role' => 'user',
  6840. 'content' => $prompt,
  6841. 'created_at' => $now,
  6842. 'updated_at' => $now
  6843. ],
  6844. [
  6845. 'uid' => $uid,
  6846. 'anime_id' => $anime_id,
  6847. 'sequence' => 0,
  6848. 'role' => 'assistant',
  6849. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6850. 'content' => $fullContent,
  6851. 'created_at' => $now,
  6852. 'updated_at' => $now
  6853. ]
  6854. ];
  6855. // 保存对话记录
  6856. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6857. if (!$boolen3) {
  6858. Utils::throwError('20003:对话记录保存失败');
  6859. }
  6860. // 单剧集模式:生成并保存剧集信息
  6861. if ($is_single) {
  6862. $anime_name = getProp($anime, 'anime_name', '未命名');
  6863. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6864. if (empty($episode_arr['acts'])) {
  6865. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6866. }
  6867. $saveResult = $this->saveEpisodeVersionData(
  6868. $anime_id,
  6869. 1,
  6870. $episode_arr,
  6871. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6872. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6873. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6874. null,
  6875. null,
  6876. false,
  6877. $content,
  6878. $now,
  6879. $ref_products
  6880. );
  6881. $single_episode = $saveResult['episode'];
  6882. $episode_id = $saveResult['episode_id'];
  6883. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6884. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6885. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6886. 'props' => json_encode($saveResult['merged_props'], 256),
  6887. 'updated_at' => $now
  6888. ]);
  6889. if ($boolen5 === false) {
  6890. Utils::throwError('20003:单剧集主表资源同步失败');
  6891. }
  6892. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6893. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6894. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6895. $episode_record_content = '确认分镜大纲';
  6896. if ($content !== '') {
  6897. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6898. }
  6899. $episode_records = [
  6900. [
  6901. 'uid' => $uid,
  6902. 'anime_id' => $anime_id,
  6903. 'role' => 'user',
  6904. 'content' => $episode_record_content,
  6905. 'sequence' => 1,
  6906. 'episode_id' => $episode_id,
  6907. 'created_at' => $now,
  6908. 'updated_at' => $now
  6909. ],
  6910. [
  6911. 'uid' => $uid,
  6912. 'anime_id' => $anime_id,
  6913. 'role' => 'assistant',
  6914. 'content' => $fullContent,
  6915. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6916. 'sequence' => 1,
  6917. 'episode_id' => $episode_id,
  6918. 'created_at' => $now,
  6919. 'updated_at' => $now
  6920. ]
  6921. ];
  6922. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6923. if (!$boolen4) {
  6924. Utils::throwError('20003:单剧集分镜记录保存失败');
  6925. }
  6926. }
  6927. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6928. if ($is_single && !empty($single_episode)) {
  6929. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6930. 'anime_id' => $anime_id,
  6931. 'episode_id' => $episode_id ?? 0,
  6932. ]);
  6933. }
  6934. }catch (\Exception $e) {
  6935. DB::rollBack();
  6936. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  6937. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  6938. yield [
  6939. 'type' => 'done',
  6940. 'answer' => $fullContent,
  6941. 'reasoning' => $fullReasoningContent,
  6942. 'usage' => $usage,
  6943. 'error' => $e->getMessage(),
  6944. ];
  6945. return;
  6946. }
  6947. DB::commit();
  6948. dLog('deepseek')->info('保存完毕');
  6949. if ($is_single && !empty($single_episode)) {
  6950. // $this->batchSetGlobalRoleImg([
  6951. // 'anime_id' => $anime_id,
  6952. // ]);
  6953. // $this->batchSetGlobalSceneImg([
  6954. // 'anime_id' => $anime_id,
  6955. // ]);
  6956. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6957. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6958. }
  6959. $table_data['anime_id'] = $anime_id;
  6960. $table_data['roles'] = json_decode($table_data['roles'], true);
  6961. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6962. $table_data['props'] = json_decode($table_data['props'], true);
  6963. unset($table_data['updated_at']);
  6964. unset($table_data['status']);
  6965. yield [
  6966. 'type' => 'done',
  6967. 'script' => $table_data,
  6968. 'episode' => $single_episode,
  6969. 'answer' => $fullContent,
  6970. 'reasoning' => $fullReasoningContent,
  6971. 'usage' => $usage
  6972. ];
  6973. }
  6974. public function chatForAce($data) {
  6975. $uid = Site::getUid();
  6976. // 积分余额预检(不足直接报错)
  6977. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  6978. $anime_id = getProp($data, 'anime_id');
  6979. $file = getProp($data, 'file');
  6980. $content = getProp($data, 'content', '');
  6981. $bid = getProp($data, 'bid', 0);
  6982. $script_id = getProp($data, 'script_id', 0);
  6983. $episode_number = getProp($data, 'episode_number', 1);
  6984. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6985. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6986. if (!$anime) Utils::throwError('20003:该对话不存在!');
  6987. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  6988. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  6989. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  6990. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  6991. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  6992. $roles = is_array($roles) ? $roles : [];
  6993. $scenes = is_array($scenes) ? $scenes : [];
  6994. $extra_products = getProp($data, 'products', []);
  6995. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6996. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6997. $anime_script_id = getProp($anime, 'script_id');
  6998. if ($anime_script_id) {
  6999. $cpid = Site::getCpid();
  7000. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7001. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7002. ->where('mapping.script_id', $anime_script_id)
  7003. ->where('product.cpid', $cpid)
  7004. ->where('product.is_deleted', 0);
  7005. // 如果提供了 episode_number,则过滤指定集数
  7006. if ($episode_number !== null && $episode_number !== '') {
  7007. $script_products_mappings->where('mapping.episode_number', $episode_number);
  7008. }
  7009. $mappings = $script_products_mappings->select(
  7010. 'mapping.product_id',
  7011. 'mapping.episode_number',
  7012. 'product.product_name',
  7013. 'product.type',
  7014. 'product.product',
  7015. 'product.pic_prompt',
  7016. 'product.url',
  7017. 'product.pic_task_id',
  7018. 'product.pic_task_status',
  7019. 'product.three_view_image_url'
  7020. )
  7021. ->get();
  7022. // 按 product_id 分组,合并 episode_number
  7023. $productMap = [];
  7024. foreach ($mappings as $item) {
  7025. $product_id = $item->product_id;
  7026. $product_name = $item->product_name;
  7027. // 处理product_name两边的符号
  7028. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7029. if (!isset($productMap[$product_id])) {
  7030. $productMap[$product_id] = [
  7031. 'product_id' => $product_id,
  7032. 'product_name' => $product_name,
  7033. 'type' => (int)$item->type,
  7034. 'product' => (int)$item->product,
  7035. 'pic_prompt' => $item->pic_prompt,
  7036. 'url' => $item->url,
  7037. 'pic_task_id' => $item->pic_task_id,
  7038. 'pic_task_status' => $item->pic_task_status,
  7039. 'episode_numbers' => [],
  7040. ];
  7041. }
  7042. // 添加 episode_number(去重)
  7043. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7044. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7045. }
  7046. }
  7047. // 将查询到的剧本资产合并到extra_products中
  7048. // 先构建extra_products的索引(以product_id+episode_number为key)
  7049. $extraProductsMap = [];
  7050. foreach ($extra_products as $item) {
  7051. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  7052. $extraProductsMap[$key] = $item;
  7053. }
  7054. // 合并剧本资产(去重:product_id+episode_number)
  7055. foreach ($productMap as $product) {
  7056. foreach ($product['episode_numbers'] as $ep_num) {
  7057. $key = $product['product_id'] . '_' . $ep_num;
  7058. // 如果不存在则添加
  7059. if (!isset($extraProductsMap[$key])) {
  7060. $extraProductsMap[$key] = [
  7061. 'product_id' => $product['product_id'],
  7062. 'product_name' => $product['product_name'],
  7063. 'type' => $product['type'],
  7064. 'product' => $product['product'],
  7065. 'pic_prompt' => $product['pic_prompt'],
  7066. 'url' => $product['url'],
  7067. 'pic_task_id' => $product['pic_task_id'],
  7068. 'pic_task_status' => $product['pic_task_status'],
  7069. 'episode_number' => $ep_num,
  7070. ];
  7071. }
  7072. }
  7073. }
  7074. // 重新赋值给extra_products
  7075. $extra_products = array_values($extraProductsMap);
  7076. }
  7077. // 处理提示词
  7078. if ($prompt && $extra_products) {
  7079. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7080. foreach($extra_products as $item) {
  7081. $product_name = getProp($item, 'product_name');
  7082. if ($product_name) {
  7083. // 替换 {product_name} 为 product_name
  7084. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7085. }
  7086. }
  7087. }
  7088. // 获取最后一集序号
  7089. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  7090. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  7091. // 转换主体列表和场景列表的格式
  7092. // 获取参考主体或场景
  7093. if ((int)$episode_number === 1) {
  7094. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  7095. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  7096. }else {
  7097. $prev_episode_number = $episode_number - 1;
  7098. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  7099. }
  7100. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  7101. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  7102. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  7103. // 合并anime_products和extra_products(extra_products优先,去重)
  7104. $anime_products = getProp($anime, 'extra_products');
  7105. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  7106. $ref_products = [];
  7107. foreach($anime_products as $item) {
  7108. $product_name = getProp($item, 'product_name');
  7109. $ref_products[$product_name] = $item;
  7110. }
  7111. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  7112. $extra_roles = []; // 从extra_products中提取的角色
  7113. $extra_scenes = []; // 从extra_products中提取的场景
  7114. $extra_props = []; // 从extra_products中提取的道具
  7115. if ($extra_products && is_array($extra_products)) {
  7116. foreach($extra_products as $item) {
  7117. $product = (int)getProp($item, 'product');
  7118. $product_name = getProp($item, 'product_name');
  7119. if ($product_name == '旁白') continue;
  7120. $pic_prompt = getProp($item, 'pic_prompt');
  7121. $ref_products[$product_name] = $item;
  7122. if ($product === 1) {
  7123. // 角色
  7124. $extra_roles[$product_name] = [
  7125. 'role' => $product_name,
  7126. 'pic_prompt' => $pic_prompt,
  7127. 'url' => getProp($item, 'url', ''),
  7128. ];
  7129. } elseif ($product === 2) {
  7130. // 场景
  7131. $extra_scenes[$product_name] = [
  7132. 'scene' => $product_name,
  7133. 'pic_prompt' => $pic_prompt,
  7134. 'url' => getProp($item, 'url', ''),
  7135. ];
  7136. } elseif ($product === 3) {
  7137. // 道具
  7138. $extra_props[$product_name] = [
  7139. 'prop' => $product_name,
  7140. 'pic_prompt' => $pic_prompt,
  7141. 'url' => getProp($item, 'url', ''),
  7142. ];
  7143. }
  7144. }
  7145. }
  7146. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  7147. $merged_roles = [];
  7148. foreach($ref_roles as $role) {
  7149. $role_name = getProp($role, 'role');
  7150. if (!isset($extra_roles[$role_name])) {
  7151. $merged_roles[$role_name] = $role;
  7152. }
  7153. }
  7154. // 添加extra_roles
  7155. foreach($extra_roles as $role_name => $role) {
  7156. $merged_roles[$role_name] = $role;
  7157. }
  7158. $ref_roles = array_values($merged_roles);
  7159. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  7160. $merged_scenes = [];
  7161. foreach($ref_scenes as $scene) {
  7162. $scene_name = getProp($scene, 'scene');
  7163. if (!isset($extra_scenes[$scene_name])) {
  7164. $merged_scenes[$scene_name] = $scene;
  7165. }
  7166. }
  7167. // 添加extra_scenes
  7168. foreach($extra_scenes as $scene_name => $scene) {
  7169. $merged_scenes[$scene_name] = $scene;
  7170. }
  7171. $ref_scenes = array_values($merged_scenes);
  7172. // 合并ref_props和extra_props(extra_props优先,去重)
  7173. $merged_props = [];
  7174. foreach($ref_props as $prop) {
  7175. $prop_name = getProp($prop, 'prop');
  7176. if (!isset($extra_props[$prop_name])) {
  7177. $merged_props[$prop_name] = $prop;
  7178. }
  7179. }
  7180. // 添加extra_props
  7181. foreach($extra_props as $prop_name => $prop) {
  7182. $merged_props[$prop_name] = $prop;
  7183. }
  7184. $ref_props = array_values($merged_props);
  7185. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  7186. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  7187. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  7188. // 构建强制主体、场景和道具提示词
  7189. $forced_roles_prompt = "";
  7190. $forced_scenes_prompt = "";
  7191. $forced_props_prompt = "";
  7192. if (!empty($extra_roles)) {
  7193. $forced_roles_list = "";
  7194. foreach($extra_roles as $role_name => $role) {
  7195. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  7196. }
  7197. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7198. }
  7199. if (!empty($extra_scenes)) {
  7200. $forced_scenes_list = "";
  7201. foreach($extra_scenes as $scene_name => $scene) {
  7202. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  7203. }
  7204. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7205. }
  7206. if (!empty($extra_props)) {
  7207. $forced_props_list = "";
  7208. foreach($extra_props as $prop_name => $prop) {
  7209. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  7210. }
  7211. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7212. }
  7213. if ($anime_script_id) {
  7214. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  7215. }else if ($roles_content) {
  7216. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  7217. 主体范围:\n {$roles_content}\n
  7218. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  7219. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7220. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7221. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7222. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7223. }else {
  7224. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7225. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7226. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7227. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7228. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7229. }
  7230. if ($anime_script_id) {
  7231. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  7232. }else if ($scenes_content) {
  7233. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7234. 场景范围:\n {$scenes_content}\n
  7235. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  7236. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  7237. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7238. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7239. }else {
  7240. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7241. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7242. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7243. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7244. }
  7245. if ($anime_script_id) {
  7246. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  7247. }else if ($props_content) {
  7248. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7249. 道具范围:\n {$props_content}\n
  7250. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  7251. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  7252. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7253. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7254. }else {
  7255. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7256. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  7257. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7258. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7259. }
  7260. // 提取文件内容
  7261. if ($file) {
  7262. $uploaded_content = $this->extractFileContent($file);
  7263. if (!$uploaded_content) {
  7264. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7265. }
  7266. } elseif ($script_id) {
  7267. $uploaded_content = $this->getContentByScriptId($script_id);
  7268. if (!$uploaded_content) {
  7269. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7270. }
  7271. } elseif ($bid) {
  7272. $uploaded_content = $this->getContentByBid($bid);
  7273. if (!$uploaded_content) {
  7274. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7275. }
  7276. } elseif ($content) {
  7277. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  7278. }
  7279. // elseif ($prompt) {
  7280. // $uploaded_content = filterContent($prompt);
  7281. // }
  7282. else {
  7283. $uploaded_content = '';
  7284. }
  7285. // 美术风格
  7286. $input_art_style = getProp($data, 'art_style');
  7287. if (!$input_art_style) {
  7288. $mappedArtStyle = getProp($anime, 'art_style');
  7289. }else {
  7290. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7291. }
  7292. if (!$mappedArtStyle) {
  7293. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7294. }else {
  7295. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7296. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7297. }else {
  7298. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7299. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7300. }
  7301. }
  7302. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7303. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7304. // 强制要求:
  7305. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7306. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7307. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7308. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  7309. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  7310. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  7311. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  7312. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  7313. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  7314. // 10.分镜要和场景列表、人物主体保持一致\n
  7315. // 普通要求:
  7316. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7317. // {$role_demo}
  7318. // {$scene_demo}
  7319. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7320. // 4.1片段分割逻辑(优先级从高到低):
  7321. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7322. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7323. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7324. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7325. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7326. // - 片段数量格式为: 片段数量:8
  7327. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7328. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7329. // 4.3分镜结构:每个分镜包含以下字段:
  7330. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  7331. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  7332. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7333. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  7334. // - 运镜:场景+画面描述+运镜
  7335. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  7336. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7337. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7338. // 5.$mappedArtStyle_prompt\n\n
  7339. // 示例格式:\n
  7340. // 第1集:隐形的守护者
  7341. // ###故事梗概
  7342. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7343. // ###美术风格
  7344. // 基础画风风格词:胡金铨武侠
  7345. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7346. // ###主体列表
  7347. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7348. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7349. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7350. // ###场景列表
  7351. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7352. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7353. // ###分段剧本
  7354. // 片段数量:8
  7355. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7356. // ##片段1
  7357. // 时长:12s
  7358. // 分镜1
  7359. // 场景:边境小镇街道
  7360. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7361. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7362. // 配音台词:
  7363. // 背景音效:
  7364. // 分镜2
  7365. // 场景:悦来酒馆
  7366. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7367. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7368. // 配音台词:
  7369. // 背景音效:
  7370. // 分镜3
  7371. // 场景:悦来酒馆
  7372. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7373. // 运镜:从中景推向令牌特写。
  7374. // 配音台词:
  7375. // 背景音效:
  7376. // 分镜4
  7377. // 场景:悦来酒馆
  7378. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7379. // 运镜:极速推向酒水溅起的瞬间。
  7380. // 配音台词:
  7381. // 背景音效:
  7382. // 分镜5
  7383. // 镜头描述
  7384. // 场景:悦来酒馆
  7385. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7386. // 运镜:固定机位,利用倾斜构图制造压迫感。
  7387. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7388. // 背景音效:
  7389. // \n\n";
  7390. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7391. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7392. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  7393. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  7394. 普通要求:
  7395. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7396. {$role_demo}
  7397. {$scene_demo}
  7398. {$prop_demo}
  7399. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7400. 5.1片段分割逻辑(优先级从高到低):
  7401. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7402. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7403. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7404. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7405. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7406. - 片段数量格式为: 片段数量:8
  7407. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7408. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7409. 5.3分镜结构:每个分镜包含以下字段:
  7410. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7411. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7412. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7413. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7414. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7415. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7416. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7417. - 运镜:场景+画面描述+运镜
  7418. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7419. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7420. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7421. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7422. 6.《情绪-视听语言映射表》:
  7423. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7424. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7425. -----|---------|------------|----------------
  7426. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7427. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7428. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7429. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7430. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7431. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7432. -----|---------|------------|----------------
  7433. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7434. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7435. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7436. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7437. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7438. --------|---------|--------------|-------------
  7439. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7440. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7441. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7442. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7443. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7444. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7445. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7446. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7447. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7448. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7449. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7450. -----|---------|------------|------------
  7451. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7452. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7453. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7454. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7455. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7456. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7457. --------|---------|--------------|----------
  7458. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7459. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7460. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7461. 6.6 声音设计与潜意识影响 (Soundscape)
  7462. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7463. -----|---------|------------|------------------
  7464. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7465. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7466. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7467. 理论基石:
  7468. - The Five C's of Cinematography by Joseph V. Mascelli
  7469. - Film Art: An Introduction by David Bordwell
  7470. - Sight, Sound, Motion by Herbert Zettl
  7471. - Notes on the Cinematograph by Robert Bresson
  7472. \n\n
  7473. 7.{$mappedArtStyle_prompt}
  7474. 示例格式:\n
  7475. 第1集:隐形的守护者
  7476. ###故事梗概
  7477. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7478. ###美术风格
  7479. 基础画风风格词:胡金铨武侠
  7480. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7481. ###主体列表
  7482. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7483. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7484. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7485. ###场景列表
  7486. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7487. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7488. ###道具列表
  7489. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  7490. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  7491. ###分段剧本
  7492. 片段数量:8
  7493. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7494. ##片段1
  7495. 时长:12s
  7496. 分镜1
  7497. 出场角色:刀疤脸
  7498. 场景:边境小镇街道
  7499. 出场道具:酒杯-高脚杯
  7500. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7501. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7502. 配音台词:
  7503. 背景音效:
  7504. 分镜2
  7505. 出场角色:刀疤脸
  7506. 场景:悦来酒馆
  7507. 出场道具:酒杯-高脚杯
  7508. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7509. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7510. 配音台词:
  7511. 背景音效:
  7512. 分镜3
  7513. 出场角色:刀疤脸
  7514. 场景:悦来酒馆
  7515. 出场道具:酒杯-高脚杯
  7516. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7517. 运镜:从中景推向令牌特写。
  7518. 配音台词:
  7519. 背景音效:
  7520. 分镜4
  7521. 出场角色:刀疤脸
  7522. 场景:悦来酒馆
  7523. 出场道具:酒杯-高脚杯
  7524. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7525. 运镜:极速推向酒水溅起的瞬间。
  7526. 配音台词:
  7527. 背景音效:
  7528. 分镜5
  7529. 出场角色:刀疤脸
  7530. 场景:悦来酒馆
  7531. 出场道具:酒杯-高脚杯
  7532. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7533. 运镜:固定机位,利用倾斜构图制造压迫感。
  7534. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7535. 背景音效:
  7536. \n\n";
  7537. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7538. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  7539. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7540. $prompt = $origin_prompt;
  7541. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7542. // 获取章节内容
  7543. $full_content = getProp($anime, 'content');
  7544. if ($uploaded_content) {
  7545. $full_content = $uploaded_content;
  7546. }
  7547. // 根据章节内容拆分章节
  7548. $chapters = splitContent($full_content);
  7549. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7550. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7551. $messages = [];
  7552. if ($prompt == '确认分镜大纲') {
  7553. // 暂时保留
  7554. $content = $chapter_content;
  7555. if ($is_single) $content = $full_content; // 单剧集使用全文
  7556. if (!$content) {
  7557. Utils::throwError('20003:章节内容无法获取,请确认');
  7558. }
  7559. $question = $is_single
  7560. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7561. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7562. // 构建消息
  7563. $messages[] =
  7564. [
  7565. 'role' => 'user',
  7566. 'content' => $question
  7567. ];
  7568. }else if ($prompt == '继续策划下一集') {
  7569. if ($is_single) {
  7570. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7571. }
  7572. $content = $chapter_content;
  7573. if (!$content) {
  7574. Utils::throwError('20003:章节内容无法获取,请确认');
  7575. }
  7576. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7577. // 获取上一集最后记录
  7578. $prev_sequence = $episode_number - 1;
  7579. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7580. // 构建消息
  7581. $messages[] =
  7582. [
  7583. 'role' => 'user',
  7584. 'content' => $question
  7585. ];
  7586. // dd($messages);
  7587. }else {
  7588. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7589. if (!$content) {
  7590. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7591. }
  7592. if (!$content) {
  7593. Utils::throwError('20003:章节内容无法获取,请确认');
  7594. }
  7595. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7596. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7597. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7598. if ($origin_prompt) {
  7599. $question .= "本次修改要求如下:\n{$origin_prompt}";
  7600. }
  7601. $messages[] =
  7602. [
  7603. 'role' => 'user',
  7604. 'content' => $question
  7605. ];
  7606. }
  7607. // 处理文本模型
  7608. $model = getProp($data, 'model');
  7609. if (!$model) {
  7610. // 用户没有输入,从anime表获取
  7611. $model = getProp($anime, 'model');
  7612. if (!$model) {
  7613. // anime表也没有,使用默认值
  7614. $model = 'deepseek-v4-pro';
  7615. }
  7616. }
  7617. // 验证模型是否在可用模型表中
  7618. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7619. $model = 'deepseek-v4-pro';
  7620. }
  7621. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7622. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7623. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7624. if ($model === 'deepseek-chat') {
  7625. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7626. $model = 'deepseek-v4-flash';
  7627. $thinkingMode = 'disabled';
  7628. } elseif ($model === 'deepseek-reasoner') {
  7629. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7630. $model = 'deepseek-v4-flash';
  7631. $thinkingMode = 'enabled';
  7632. }
  7633. $post_data = [
  7634. 'model' => $model,
  7635. 'messages' => $messages,
  7636. // 'max_tokens' => 8192,
  7637. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7638. 'frequency_penalty' => 0,
  7639. 'presence_penalty' => 0,
  7640. 'response_format' => ['type' => 'text'],
  7641. 'thinking' => ['type' => $thinkingMode],
  7642. 'stream' => true // 启用流式输出
  7643. ];
  7644. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7645. // 根据模型类型选择调用方法
  7646. $fullContent = '';
  7647. $fullReasoningContent = '';
  7648. $usage = [];
  7649. try {
  7650. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7651. // DeepSeek 官方模型使用 DeepSeek API
  7652. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7653. } else if (in_array($model, $this->gpt_text_models)) {
  7654. // GPT-5.4 模型使用 TokenRouter API
  7655. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7656. } else {
  7657. // 其他模型使用火山引擎API
  7658. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7659. }
  7660. // 验证返回值类型
  7661. if (!is_iterable($streamGenerator)) {
  7662. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7663. dLog('deepseek')->error('chat流式生成器无效', [
  7664. 'generator_type' => $errorType,
  7665. 'model' => $model,
  7666. 'anime_id' => $anime_id,
  7667. 'episode_number' => $episode_number
  7668. ]);
  7669. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7670. 'type' => $errorType,
  7671. 'model' => $model
  7672. ]);
  7673. yield [
  7674. 'type' => 'error',
  7675. 'episode' => [],
  7676. 'answer' => '',
  7677. 'reasoning' => '',
  7678. 'usage' => [],
  7679. 'error' => '接口返回数据异常,请重新请求'
  7680. ];
  7681. return;
  7682. }
  7683. // 处理流式输出
  7684. foreach ($streamGenerator as $chunk) {
  7685. if (isset($chunk['type'])) {
  7686. if ($chunk['type'] === 'done') {
  7687. // 最终结果
  7688. $fullContent = $chunk['full_content'];
  7689. $fullReasoningContent = $chunk['full_reasoning'];
  7690. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7691. } else {
  7692. // 逐块yield数据
  7693. yield $chunk;
  7694. }
  7695. }
  7696. }
  7697. } catch (\Exception $e) {
  7698. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7699. 'model' => $model,
  7700. 'anime_id' => $anime_id,
  7701. 'episode_number' => $episode_number,
  7702. 'trace' => $e->getTraceAsString()
  7703. ]);
  7704. logDB('deepseek', 'error', 'chat流式处理失败', [
  7705. 'error' => $e->getMessage(),
  7706. 'model' => $model
  7707. ]);
  7708. yield [
  7709. 'type' => 'error',
  7710. 'episode' => [],
  7711. 'answer' => '',
  7712. 'reasoning' => '',
  7713. 'usage' => [],
  7714. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7715. ];
  7716. return;
  7717. }
  7718. dLog('deepseek')->info('完整内容: '.$fullContent);
  7719. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7720. // 处理完整内容并返回最终结果
  7721. $episode_arr = handleEpisodeContentForAce($fullContent);
  7722. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7723. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  7724. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7725. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7726. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  7727. // }
  7728. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  7729. $max_retries = 3;
  7730. $retry_count = 0;
  7731. $validation_failed = false;
  7732. $validation_error_msg = '';
  7733. // 验证生成的内容
  7734. if ($anime_script_id) {
  7735. // 检查是否有acts数据
  7736. if (empty($episode_arr['acts'])) {
  7737. $validation_failed = true;
  7738. $validation_error_msg = '未生成分镜剧本相关的内容';
  7739. } else {
  7740. // 检查主体列表是否匹配 - 只验证生成的主体名是否都在预期列表中
  7741. $generated_roles = array_column($episode_arr['roles'], 'role');
  7742. // 过滤掉"旁白"角色
  7743. $generated_roles = array_filter($generated_roles, function($role) {
  7744. return $role !== '旁白';
  7745. });
  7746. $expected_roles = array_keys($extra_roles);
  7747. // 找出生成的主体中不在预期列表中的主体
  7748. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7749. if (!empty($invalid_roles)) {
  7750. $validation_failed = true;
  7751. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7752. }
  7753. // 检查场景列表是否匹配 - 只验证生成的场景名是否都在预期列表中
  7754. if (!$validation_failed) {
  7755. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7756. $expected_scenes = array_keys($extra_scenes);
  7757. // 找出生成的场景中不在预期列表中的场景
  7758. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7759. if (!empty($invalid_scenes)) {
  7760. $validation_failed = true;
  7761. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7762. }
  7763. }
  7764. }
  7765. } else {
  7766. // 如果没有anime_script_id,只检查是否有acts数据
  7767. if (empty($episode_arr['acts'])) {
  7768. $validation_failed = true;
  7769. $validation_error_msg = '未生成分镜剧本相关的内容';
  7770. }
  7771. }
  7772. // 重试逻辑
  7773. while ($validation_failed && $retry_count < $max_retries) {
  7774. $retry_count++;
  7775. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  7776. 'reason' => $validation_error_msg,
  7777. 'anime_id' => $anime_id,
  7778. 'episode_number' => $episode_number
  7779. ]);
  7780. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  7781. 'reason' => $validation_error_msg,
  7782. 'anime_id' => $anime_id
  7783. ]);
  7784. // 发送流式重试提示
  7785. yield [
  7786. 'type' => 'retry',
  7787. 'retry_count' => $retry_count,
  7788. 'reason' => $validation_error_msg
  7789. ];
  7790. // 构建重试提示词
  7791. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  7792. if ($anime_script_id) {
  7793. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  7794. $retry_prompt .= "2. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  7795. $retry_prompt .= "3. 必须包含完整的分镜剧本内容\n";
  7796. } else {
  7797. $retry_prompt .= "1. 必须包含完整的分镜剧本内容\n";
  7798. }
  7799. // 添加重试消息到messages
  7800. $messages[] = [
  7801. 'role' => 'assistant',
  7802. 'content' => $fullContent
  7803. ];
  7804. $messages[] = [
  7805. 'role' => 'user',
  7806. 'content' => $retry_prompt
  7807. ];
  7808. // 更新post_data的messages
  7809. $post_data['messages'] = $messages;
  7810. // 重新调用API
  7811. try {
  7812. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7813. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7814. } else if (in_array($model, $this->gpt_text_models)) {
  7815. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7816. } else {
  7817. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7818. }
  7819. // 处理流式输出
  7820. $fullContent = '';
  7821. $fullReasoningContent = '';
  7822. foreach ($streamGenerator as $chunk) {
  7823. if (isset($chunk['type'])) {
  7824. if ($chunk['type'] === 'done') {
  7825. $fullContent = $chunk['full_content'];
  7826. $fullReasoningContent = $chunk['full_reasoning'];
  7827. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7828. } else {
  7829. yield $chunk;
  7830. }
  7831. }
  7832. }
  7833. // 重新解析内容
  7834. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  7835. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  7836. $episode_arr = handleEpisodeContentForAce($fullContent);
  7837. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  7838. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7839. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7840. // }
  7841. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  7842. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  7843. // 重新验证
  7844. $validation_failed = false;
  7845. $validation_error_msg = '';
  7846. if ($anime_script_id) {
  7847. if (empty($episode_arr['acts'])) {
  7848. $validation_failed = true;
  7849. $validation_error_msg = '未生成分镜剧本相关的内容';
  7850. } else {
  7851. // 检查主体列表 - 只验证生成的主体名是否都在预期列表中
  7852. $generated_roles = array_column($episode_arr['roles'], 'role');
  7853. // 过滤掉"旁白"角色
  7854. $generated_roles = array_filter($generated_roles, function($role) {
  7855. return $role !== '旁白';
  7856. });
  7857. $expected_roles = array_keys($extra_roles);
  7858. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7859. if (!empty($invalid_roles)) {
  7860. $validation_failed = true;
  7861. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7862. }
  7863. // 检查场景列表 - 只验证生成的场景名是否都在预期列表中
  7864. if (!$validation_failed) {
  7865. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7866. $expected_scenes = array_keys($extra_scenes);
  7867. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7868. if (!empty($invalid_scenes)) {
  7869. $validation_failed = true;
  7870. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7871. }
  7872. }
  7873. }
  7874. } else {
  7875. if (empty($episode_arr['acts'])) {
  7876. $validation_failed = true;
  7877. $validation_error_msg = '未生成分镜剧本相关的内容';
  7878. }
  7879. }
  7880. } catch (\Exception $e) {
  7881. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  7882. 'trace' => $e->getTraceAsString()
  7883. ]);
  7884. break;
  7885. }
  7886. }
  7887. // 如果重试后仍然失败
  7888. if ($validation_failed) {
  7889. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  7890. 'retry_count' => $retry_count,
  7891. 'last_error' => $validation_error_msg
  7892. ]);
  7893. try {
  7894. $now = date('Y-m-d H:i:s');
  7895. $records = [
  7896. [
  7897. 'uid' => $uid,
  7898. 'anime_id' => $anime_id,
  7899. 'sequence' => $episode_number,
  7900. 'role' => 'user',
  7901. 'content' => $prompt,
  7902. 'created_at' => $now,
  7903. 'updated_at' => $now
  7904. ],
  7905. [
  7906. 'uid' => $uid,
  7907. 'anime_id' => $anime_id,
  7908. 'sequence' => $episode_number,
  7909. 'role' => 'assistant',
  7910. 'content' => $fullContent,
  7911. 'created_at' => $now,
  7912. 'updated_at' => $now
  7913. ]
  7914. ];
  7915. DB::table('mp_anime_records')->insert($records);
  7916. } catch (\Exception $e) {
  7917. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7918. }
  7919. yield [
  7920. 'type' => 'done',
  7921. 'episode' => [],
  7922. 'answer' => $fullContent,
  7923. 'reasoning' => $fullReasoningContent,
  7924. 'usage' => $usage,
  7925. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  7926. ];
  7927. return;
  7928. }
  7929. // 验证成功,记录日志
  7930. if ($retry_count > 0) {
  7931. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  7932. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  7933. }
  7934. // 老逻辑
  7935. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  7936. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  7937. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  7938. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  7939. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  7940. $existing_props = is_array($existing_props) ? $existing_props : [];
  7941. $now = date('Y-m-d H:i:s');
  7942. try {
  7943. DB::beginTransaction();
  7944. $saveResult = $this->saveEpisodeVersionData(
  7945. $anime_id,
  7946. $episode_number,
  7947. $episode_arr,
  7948. $existing_roles,
  7949. $existing_scenes,
  7950. $existing_props,
  7951. $current_episode,
  7952. $base_episode,
  7953. $is_regenerate_version,
  7954. $content,
  7955. $now,
  7956. $ref_products
  7957. );
  7958. $episode = $saveResult['episode'];
  7959. $episode_id = $saveResult['episode_id'];
  7960. $merged_roles = $saveResult['merged_roles'];
  7961. $merged_scenes = $saveResult['merged_scenes'];
  7962. $merged_props = $saveResult['merged_props'];
  7963. $record_content = $origin_prompt;
  7964. if ($uploaded_content !== '') {
  7965. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  7966. }
  7967. $records = [
  7968. [
  7969. 'uid' => $uid,
  7970. 'anime_id' => $anime_id,
  7971. 'role' => 'user',
  7972. 'content' => $record_content,
  7973. 'sequence' => $episode_number,
  7974. 'episode_id' => $episode_id,
  7975. 'created_at' => $now,
  7976. 'updated_at' => $now
  7977. ],
  7978. [
  7979. 'uid' => $uid,
  7980. 'anime_id' => $anime_id,
  7981. 'role' => 'assistant',
  7982. 'content' => $fullContent,
  7983. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7984. 'sequence' => $episode_number,
  7985. 'episode_id' => $episode_id,
  7986. 'created_at' => $now,
  7987. 'updated_at' => $now
  7988. ]
  7989. ];
  7990. $boolen4 = DB::table('mp_anime_records')->insert($records);
  7991. if (!$boolen4) {
  7992. Utils::throwError('20003:对话记录保存失败');
  7993. }
  7994. // 保存模型到anime表
  7995. $update_anime_data = [
  7996. 'model' => $model,
  7997. 'updated_at' => $now
  7998. ];
  7999. if ($uploaded_content) {
  8000. $update_anime_data['content'] = $uploaded_content;
  8001. }
  8002. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  8003. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8004. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8005. 'anime_id' => $anime_id,
  8006. 'episode_number' => $episode_number,
  8007. 'model' => $model,
  8008. ]);
  8009. }catch (\Exception $e) {
  8010. DB::rollBack();
  8011. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  8012. yield [
  8013. 'type' => 'done',
  8014. 'answer' => $fullContent,
  8015. 'reasoning' => $fullReasoningContent,
  8016. 'usage' => $usage,
  8017. 'error' => $e->getMessage(),
  8018. ];
  8019. return;
  8020. }
  8021. DB::commit();
  8022. if ($is_global_generate_pics) {
  8023. // // 批量生成全局角色图片
  8024. // $this->batchSetGlobalRoleImg([
  8025. // 'anime_id' => $anime_id,
  8026. // ], true);
  8027. // // 批量生成全局场景图片
  8028. // $this->batchSetGlobalSceneImg([
  8029. // 'anime_id' => $anime_id,
  8030. // ], true);
  8031. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8032. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8033. }
  8034. $episode['episode_id'] = $episode_id;
  8035. $episode['roles'] = $merged_roles;
  8036. $episode['scenes'] = $merged_scenes;
  8037. $episode['props'] = $merged_props;
  8038. $episode['end_episode_sequence'] = $end_episode_sequence;
  8039. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  8040. yield [
  8041. 'type' => 'done',
  8042. 'episode' => $episode,
  8043. 'answer' => $fullContent,
  8044. 'reasoning' => $fullReasoningContent,
  8045. 'usage' => $usage
  8046. ];
  8047. }
  8048. /**
  8049. * chatForAce的非流式版本 - 用于定时任务
  8050. * 只获取最终 type=done 的数据,并验证必要字段
  8051. *
  8052. * @param array $data 请求数据
  8053. * @return array 生成结果
  8054. */
  8055. public function chatForAceNonStream($data) {
  8056. $finalResult = null;
  8057. // 调用流式方法,只保存 type=done 的数据
  8058. foreach ($this->chatForAce($data) as $chunk) {
  8059. // 只关注最终结果
  8060. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  8061. $finalResult = $chunk;
  8062. break; // 找到 done 就退出循环
  8063. }
  8064. }
  8065. // 验证最终结果
  8066. if (!$finalResult) {
  8067. return ['error' => '生成失败:未获取到最终结果'];
  8068. }
  8069. // 检查是否有错误
  8070. if (isset($finalResult['error']) && $finalResult['error']) {
  8071. return $finalResult;
  8072. }
  8073. // 验证必要字段
  8074. $episode = $finalResult['episode'] ?? [];
  8075. // 验证 roles
  8076. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  8077. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  8078. }
  8079. // 验证 scenes
  8080. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  8081. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  8082. }
  8083. // 验证 props(道具可以为空,但必须存在且为数组)
  8084. if (!isset($episode['props']) || !is_array($episode['props'])) {
  8085. $episode['props'] = [];
  8086. }
  8087. // 验证 acts(分镜剧本)
  8088. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  8089. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  8090. }
  8091. // 更新验证后的 episode 数据
  8092. $finalResult['episode'] = $episode;
  8093. // 记录验证成功日志
  8094. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  8095. 'roles_count' => count($episode['roles']),
  8096. 'scenes_count' => count($episode['scenes']),
  8097. 'props_count' => count($episode['props']),
  8098. 'acts_count' => count($episode['acts'])
  8099. ]);
  8100. return $finalResult;
  8101. }
  8102. /**
  8103. * 批量生成多个分集
  8104. *
  8105. * @param array $data 请求数据
  8106. * @return array 任务信息
  8107. */
  8108. public function batchGenerateEpisodes($data) {
  8109. $uid = Site::getUid();
  8110. $cpid = Site::getCpid();
  8111. $anime_id = getProp($data, 'anime_id');
  8112. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  8113. if (!$anime_id) {
  8114. Utils::throwError('20003:anime_id参数缺失');
  8115. }
  8116. if ($generate_episode_number < 1) {
  8117. Utils::throwError('20003:生成集数必须大于0');
  8118. }
  8119. // 获取动漫信息
  8120. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8121. if (!$anime) {
  8122. Utils::throwError('20003:该剧集不存在');
  8123. }
  8124. // 检查是否是全能模式
  8125. if ((int)getProp($anime, 'ace_mode') !== 1) {
  8126. Utils::throwError('20003:只有全能模式才支持批量生成');
  8127. }
  8128. // 检查是否是多剧集模式
  8129. if ((int)getProp($anime, 'is_multi') !== 1) {
  8130. Utils::throwError('20003:单剧集不支持批量生成');
  8131. }
  8132. // 获取当前已生成的最大集数
  8133. $currentMaxEpisode = DB::table('mp_anime_episodes')
  8134. ->where('anime_id', $anime_id)
  8135. ->where('is_default', 1)
  8136. ->max('episode_number');
  8137. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  8138. // 确定起始集数
  8139. $startEpisodeNumber = $currentMaxEpisode + 1;
  8140. // 计算结束集数
  8141. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  8142. // 检查是否超过总集数限制
  8143. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  8144. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  8145. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  8146. }
  8147. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  8148. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  8149. ->where('anime_id', $anime_id)
  8150. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  8151. ->whereIn('status', ['pending', 'processing', 'completed'])
  8152. ->count();
  8153. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  8154. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  8155. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  8156. if ($needEpisodeCount > 0) {
  8157. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS * $needEpisodeCount, $uid);
  8158. }
  8159. $now = date('Y-m-d H:i:s');
  8160. $createdTasks = [];
  8161. $skippedTasks = [];
  8162. // 为每一集创建详情记录
  8163. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  8164. // 检查是否已有该集的任务记录
  8165. $existingTask = DB::table('mp_batch_episode_generation_details')
  8166. ->where('anime_id', $anime_id)
  8167. ->where('episode_number', $episodeNumber)
  8168. ->first();
  8169. if ($existingTask) {
  8170. // 如果已存在且未完成,跳过
  8171. if (in_array($existingTask->status, ['pending', 'processing'])) {
  8172. $skippedTasks[] = $episodeNumber;
  8173. continue;
  8174. }
  8175. // 如果是失败状态,可以重新创建(删除旧记录)
  8176. if ($existingTask->status === 'failed') {
  8177. DB::table('mp_batch_episode_generation_details')
  8178. ->where('id', $existingTask->id)
  8179. ->delete();
  8180. }
  8181. // 如果是已完成状态,也跳过
  8182. if ($existingTask->status === 'completed') {
  8183. $skippedTasks[] = $episodeNumber;
  8184. continue;
  8185. }
  8186. }
  8187. // 准备任务数据
  8188. $taskData = [
  8189. 'anime_id' => $anime_id,
  8190. 'uid' => $uid,
  8191. 'cpid' => $cpid,
  8192. 'episode_number' => $episodeNumber,
  8193. 'status' => 'pending',
  8194. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  8195. 'retry_count' => 0,
  8196. 'created_at' => $now,
  8197. 'updated_at' => $now
  8198. ];
  8199. // 创建任务记录
  8200. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  8201. if ($taskId) {
  8202. $createdTasks[] = $episodeNumber;
  8203. }
  8204. }
  8205. if (empty($createdTasks)) {
  8206. if (!empty($skippedTasks)) {
  8207. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  8208. } else {
  8209. Utils::throwError('20003:创建批量生成任务失败');
  8210. }
  8211. }
  8212. return [
  8213. 'anime_id' => $anime_id,
  8214. 'start_episode' => $startEpisodeNumber,
  8215. 'end_episode' => $endEpisodeNumber,
  8216. 'total_episodes' => $generate_episode_number,
  8217. 'created_episodes' => $createdTasks,
  8218. 'skipped_episodes' => $skippedTasks,
  8219. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集。" .
  8220. "已创建: " . implode(',', $createdTasks) .
  8221. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : "")
  8222. ];
  8223. }
  8224. /**
  8225. * 获取批量生成任务状态
  8226. *
  8227. * @param array $data 请求数据
  8228. * @return array 任务状态信息
  8229. */
  8230. public function getBatchGenerationTaskStatus($data) {
  8231. $anime_id = getProp($data, 'anime_id');
  8232. if (!$anime_id) {
  8233. Utils::throwError('20003:anime_id参数缺失');
  8234. }
  8235. // 获取该anime的所有任务
  8236. $tasks = DB::table('mp_batch_episode_generation_details')
  8237. ->where('anime_id', $anime_id)
  8238. ->orderBy('episode_number')
  8239. ->get()
  8240. ->map(function($item) {
  8241. return [
  8242. 'id' => $item->id,
  8243. 'episode_number' => $item->episode_number,
  8244. 'status' => $item->status,
  8245. 'error_message' => $item->error_message,
  8246. 'retry_count' => $item->retry_count,
  8247. 'created_at' => $item->created_at,
  8248. 'updated_at' => $item->updated_at,
  8249. 'completed_at' => $item->completed_at
  8250. ];
  8251. })
  8252. ->toArray();
  8253. if (empty($tasks)) {
  8254. Utils::throwError('20003:该剧集没有批量生成任务');
  8255. }
  8256. // 统计各状态数量
  8257. $totalCount = count($tasks);
  8258. $pendingCount = 0;
  8259. $processingCount = 0;
  8260. $completedCount = 0;
  8261. $failedCount = 0;
  8262. foreach ($tasks as $task) {
  8263. switch ($task['status']) {
  8264. case 'pending':
  8265. $pendingCount++;
  8266. break;
  8267. case 'processing':
  8268. $processingCount++;
  8269. break;
  8270. case 'completed':
  8271. $completedCount++;
  8272. break;
  8273. case 'failed':
  8274. $failedCount++;
  8275. break;
  8276. }
  8277. }
  8278. // 计算进度百分比
  8279. $progress = 0;
  8280. if ($totalCount > 0) {
  8281. $progress = round(($completedCount / $totalCount) * 100, 2);
  8282. }
  8283. // 判断整体状态
  8284. $overallStatus = 'processing';
  8285. if ($completedCount === $totalCount) {
  8286. $overallStatus = 'completed';
  8287. } elseif ($pendingCount === $totalCount) {
  8288. $overallStatus = 'pending';
  8289. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  8290. $overallStatus = 'failed';
  8291. }
  8292. return [
  8293. 'anime_id' => $anime_id,
  8294. 'total_episodes' => $totalCount,
  8295. 'pending_count' => $pendingCount,
  8296. 'processing_count' => $processingCount,
  8297. 'completed_count' => $completedCount,
  8298. 'failed_count' => $failedCount,
  8299. 'progress' => $progress,
  8300. 'overall_status' => $overallStatus,
  8301. 'tasks' => $tasks
  8302. ];
  8303. }
  8304. /**
  8305. * 智能匹配并替换主体和场景名称
  8306. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  8307. *
  8308. * @param array $episode_arr 解析后的剧集数据
  8309. * @param array $extra_roles 强制主体设定(key为主体名称)
  8310. * @param array $extra_scenes 强制场景设定(key为场景名称)
  8311. * @return array 替换后的剧集数据
  8312. */
  8313. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  8314. $replaced_count = 0;
  8315. // 1. 处理主体列表
  8316. if (!empty($episode_arr['roles'])) {
  8317. foreach ($episode_arr['roles'] as &$role) {
  8318. $generated_role_name = $role['role'] ?? '';
  8319. // 跳过旁白
  8320. if ($generated_role_name === '旁白') {
  8321. continue;
  8322. }
  8323. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  8324. if (!isset($extra_roles[$generated_role_name])) {
  8325. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  8326. if ($matched_role) {
  8327. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  8328. $role['role'] = $matched_role;
  8329. $replaced_count++;
  8330. }
  8331. }
  8332. }
  8333. }
  8334. // 2. 处理场景列表
  8335. if (!empty($episode_arr['scenes'])) {
  8336. foreach ($episode_arr['scenes'] as &$scene) {
  8337. $generated_scene_name = $scene['scene'] ?? '';
  8338. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  8339. if (!isset($extra_scenes[$generated_scene_name])) {
  8340. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  8341. if ($matched_scene) {
  8342. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  8343. $scene['scene'] = $matched_scene;
  8344. $replaced_count++;
  8345. }
  8346. }
  8347. }
  8348. }
  8349. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  8350. if (!empty($episode_arr['acts'])) {
  8351. foreach ($episode_arr['acts'] as &$act) {
  8352. if (!empty($act['segments'])) {
  8353. foreach ($act['segments'] as &$segment) {
  8354. if (!empty($segment['segment_content'])) {
  8355. $original_content = $segment['segment_content'];
  8356. $replaced_content = $original_content;
  8357. // 替换场景名 - 在文本中查找并替换
  8358. foreach (array_keys($extra_scenes) as $full_scene_name) {
  8359. // 尝试找到可能的短名称
  8360. $potential_short_names = [];
  8361. // 提取场景名的主要部分(冒号之前)
  8362. if (mb_strpos($full_scene_name, ':') !== false) {
  8363. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8364. $potential_short_names[] = $short_name;
  8365. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  8366. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8367. $potential_short_names[] = $short_name;
  8368. }
  8369. // 替换场景字段中的短名称
  8370. foreach ($potential_short_names as $short_name) {
  8371. if ($short_name !== $full_scene_name) {
  8372. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  8373. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  8374. if ($new_content !== $replaced_content) {
  8375. $replaced_content = $new_content;
  8376. $replaced_count++;
  8377. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  8378. }
  8379. }
  8380. }
  8381. }
  8382. // 替换配音角色名(跳过旁白)
  8383. foreach (array_keys($extra_roles) as $full_role_name) {
  8384. if ($full_role_name === '旁白') {
  8385. continue;
  8386. }
  8387. // 尝试找到可能的短名称
  8388. $potential_short_names = [];
  8389. // 提取角色名的主要部分(短横线之前)
  8390. if (mb_strpos($full_role_name, '-') !== false) {
  8391. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  8392. $potential_short_names[] = $short_name;
  8393. }
  8394. // 替换配音台词中的短名称
  8395. foreach ($potential_short_names as $short_name) {
  8396. if ($short_name !== $full_role_name) {
  8397. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  8398. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  8399. if ($new_content !== $replaced_content) {
  8400. $replaced_content = $new_content;
  8401. $replaced_count++;
  8402. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  8403. }
  8404. }
  8405. }
  8406. }
  8407. // 如果有替换,更新segment_content
  8408. if ($replaced_content !== $original_content) {
  8409. $segment['segment_content'] = $replaced_content;
  8410. }
  8411. }
  8412. }
  8413. }
  8414. }
  8415. }
  8416. if ($replaced_count > 0) {
  8417. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  8418. 'replaced_count' => $replaced_count
  8419. ]);
  8420. }
  8421. return $episode_arr;
  8422. }
  8423. /**
  8424. * 查找匹配的名称
  8425. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  8426. *
  8427. * @param string $generated_name 生成的名称
  8428. * @param array $expected_names 预期的名称列表
  8429. * @return string|null 匹配到的名称,如果没有匹配则返回null
  8430. */
  8431. private function findMatchingName($generated_name, $expected_names) {
  8432. if (empty($generated_name)) {
  8433. return null;
  8434. }
  8435. // 尝试精确匹配
  8436. if (in_array($generated_name, $expected_names)) {
  8437. return $generated_name;
  8438. }
  8439. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  8440. foreach ($expected_names as $expected_name) {
  8441. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  8442. if (mb_strpos($expected_name, $generated_name) === 0) {
  8443. return $expected_name;
  8444. }
  8445. }
  8446. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  8447. // 这样可以处理一些变体,但优先级较低
  8448. foreach ($expected_names as $expected_name) {
  8449. if (mb_strpos($expected_name, $generated_name) !== false) {
  8450. return $expected_name;
  8451. }
  8452. }
  8453. return null;
  8454. }
  8455. /**
  8456. * 重新生成分段剧本
  8457. * @param array $data 包含以下字段:
  8458. * - prompt: string|null 用户修改要求(可选)
  8459. * - template_id: int|null 提示词模板ID(可选)
  8460. * - act_id: int|null 单个片段ID(与episode_id二选一)
  8461. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  8462. * @return array 返回生成结果
  8463. */
  8464. public function regenerateSegmentScript($data) {
  8465. $uid = Site::getUid();
  8466. $prompt = trim((string)getProp($data, 'prompt', ''));
  8467. $template_id = getProp($data, 'template_id', 0);
  8468. $act_id = getProp($data, 'act_id', 0);
  8469. $episode_id = getProp($data, 'episode_id', 0);
  8470. // 验证:prompt和template_id至少提供一个
  8471. if (empty($prompt) && empty($template_id)) {
  8472. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  8473. }
  8474. // 验证:act_id和episode_id二选一
  8475. if (empty($act_id) && empty($episode_id)) {
  8476. Utils::throwError('20003:请提供片段ID或剧集ID');
  8477. }
  8478. if (!empty($act_id) && !empty($episode_id)) {
  8479. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  8480. }
  8481. // 积分余额预检(仅剧集ID模式收费)
  8482. if (!empty($episode_id)) {
  8483. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  8484. }
  8485. // 如果提供了template_id,获取模板提示词
  8486. $template_prompt = '';
  8487. if ($template_id > 0) {
  8488. $template = DB::table('mp_prompt_templates')
  8489. ->where('id', $template_id)
  8490. ->where('is_deleted', 0)
  8491. ->first();
  8492. if (!$template) {
  8493. Utils::throwError('20003:提示词模板不存在或已删除');
  8494. }
  8495. $template_prompt = $template->template_prompt ?? '';
  8496. }
  8497. // 合并用户提示词和模板提示词
  8498. $final_prompt = '';
  8499. if (!empty($template_prompt)) {
  8500. $final_prompt = $template_prompt;
  8501. if (!empty($prompt)) {
  8502. $final_prompt .= "\n\n补充要求:" . $prompt;
  8503. }
  8504. } else {
  8505. $final_prompt = $prompt;
  8506. }
  8507. // 获取需要重新生成的内容参考
  8508. $reference_content = '';
  8509. $target_episode_id = 0;
  8510. $target_anime_id = 0;
  8511. $target_episode_number = 0;
  8512. if ($act_id > 0) {
  8513. // 单个片段模式:获取该片段的内容
  8514. $segment = DB::table('mp_episode_segments')
  8515. ->where('id', $act_id)
  8516. ->first();
  8517. if (!$segment) {
  8518. Utils::throwError('20003:片段不存在');
  8519. }
  8520. $target_episode_id = $segment->episode_id;
  8521. $target_anime_id = $segment->anime_id;
  8522. $target_episode_number = $segment->episode_number;
  8523. $reference_content = $segment->act_content ?? '';
  8524. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8525. } else {
  8526. // 整个剧集模式:获取所有片段的内容
  8527. $segments = DB::table('mp_episode_segments')
  8528. ->where('episode_id', $episode_id)
  8529. ->orderBy('act_number')
  8530. ->get();
  8531. if ($segments->isEmpty()) {
  8532. Utils::throwError('20003:该剧集没有片段数据');
  8533. }
  8534. $target_episode_id = $episode_id;
  8535. $target_anime_id = $segments[0]->anime_id;
  8536. $target_episode_number = $segments[0]->episode_number;
  8537. // 拼接所有片段内容,保留格式用于AI理解
  8538. $act_contents = [];
  8539. foreach ($segments as $seg) {
  8540. $act_number = $seg->act_number;
  8541. $act_content = $seg->act_content ?? '';
  8542. if (!empty($act_content)) {
  8543. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  8544. }
  8545. }
  8546. $reference_content = implode("\n\n", $act_contents);
  8547. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  8548. if ($episode_content) {
  8549. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  8550. }else {
  8551. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8552. }
  8553. }
  8554. if (empty($reference_content)) {
  8555. Utils::throwError('20003:没有可参考的片段内容');
  8556. }
  8557. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  8558. $episode = DB::table('mp_anime_episodes')
  8559. ->where('id', $target_episode_id)
  8560. ->first();
  8561. if (!$episode) {
  8562. Utils::throwError('20003:剧集不存在');
  8563. }
  8564. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  8565. $anime_script_id = getProp($anime, 'script_id');
  8566. $intro = $episode->intro ?? '';
  8567. $art_style = $episode->art_style ?? '';
  8568. $roles = json_decode($episode->roles ?? '[]', true);
  8569. $scenes = json_decode($episode->scenes ?? '[]', true);
  8570. $props = json_decode($episode->props ?? '[]', true);
  8571. // 构建提示词中的主体列表和场景列表参考
  8572. $roles_ref = '';
  8573. if (!empty($roles) && is_array($roles)) {
  8574. $roles_list = [];
  8575. foreach ($roles as $role) {
  8576. $role_name = getProp($role, 'role', '');
  8577. $role_desc = getProp($role, 'description', '');
  8578. $pic_prompt = getProp($role, 'pic_prompt', '');
  8579. $voice_prompt = getProp($role, 'voice_prompt', '');
  8580. if (!empty($role_name)) {
  8581. $role_line = $role_name;
  8582. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  8583. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  8584. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  8585. $roles_list[] = $role_line;
  8586. }
  8587. }
  8588. if (!empty($roles_list)) {
  8589. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  8590. }
  8591. }
  8592. $scenes_ref = '';
  8593. if (!empty($scenes) && is_array($scenes)) {
  8594. $scenes_list = [];
  8595. foreach ($scenes as $scene) {
  8596. $scene_name = getProp($scene, 'scene', '');
  8597. $scene_desc = getProp($scene, 'description', '');
  8598. $pic_prompt = getProp($scene, 'pic_prompt', '');
  8599. if (!empty($scene_name)) {
  8600. $scene_line = $scene_name;
  8601. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  8602. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  8603. $scenes_list[] = $scene_line;
  8604. }
  8605. }
  8606. if (!empty($scenes_list)) {
  8607. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  8608. }
  8609. }
  8610. $props_ref = '';
  8611. if (!empty($props) && is_array($props)) {
  8612. $props_list = [];
  8613. foreach ($props as $prop) {
  8614. $prop_name = getProp($prop, 'prop', '');
  8615. $prop_desc = getProp($prop, 'description', '');
  8616. $pic_prompt = getProp($prop, 'pic_prompt', '');
  8617. if (!empty($prop_name)) {
  8618. $prop_line = $prop_name;
  8619. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  8620. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  8621. $props_list[] = $prop_line;
  8622. }
  8623. }
  8624. if (!empty($props_list)) {
  8625. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  8626. }
  8627. }
  8628. // 构建美术风格参考
  8629. $art_style_ref = '';
  8630. if (!empty($art_style)) {
  8631. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  8632. }
  8633. // 构建内容简介参考
  8634. $intro_ref = '';
  8635. if (!empty($intro)) {
  8636. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  8637. }
  8638. // 构建完整的AI提示词
  8639. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  8640. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  8641. $user_prompt .= $intro_ref;
  8642. $user_prompt .= $art_style_ref;
  8643. $user_prompt .= $reference_content;
  8644. // $user_prompt .= $roles_ref;
  8645. // $user_prompt .= $scenes_ref;
  8646. $system_prompt = "\n\n【强制要求】\n";
  8647. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  8648. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  8649. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  8650. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  8651. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  8652. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  8653. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  8654. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  8655. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  8656. ###分段剧本
  8657. 片段数量:8
  8658. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8659. ##片段1
  8660. 时长:12s
  8661. 分镜1
  8662. 出场角色:刀疤脸
  8663. 场景:边境小镇街道
  8664. 出场道具:酒杯-高脚杯
  8665. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8666. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8667. 配音台词:
  8668. 背景音效:
  8669. 分镜2
  8670. 出场角色:刀疤脸
  8671. 场景:悦来酒馆
  8672. 出场道具:酒杯-高脚杯
  8673. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8674. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8675. 配音台词:
  8676. 背景音效:
  8677. 分镜3
  8678. 出场角色:刀疤脸
  8679. 场景:悦来酒馆
  8680. 出场道具:酒杯-高脚杯
  8681. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8682. 运镜:从中景推向令牌特写。
  8683. 配音台词:
  8684. 背景音效:
  8685. 分镜4
  8686. 出场角色:刀疤脸
  8687. 场景:悦来酒馆
  8688. 出场道具:酒杯-高脚杯
  8689. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8690. 运镜:极速推向酒水溅起的瞬间。
  8691. 配音台词:
  8692. 背景音效:
  8693. 分镜5
  8694. 出场角色:刀疤脸
  8695. 场景:悦来酒馆
  8696. 出场道具:酒杯-高脚杯
  8697. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8698. 运镜:固定机位,利用倾斜构图制造压迫感。
  8699. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8700. 背景音效:";
  8701. // 获取模型配置
  8702. $model = getProp($data, 'model');
  8703. if (!$model) {
  8704. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  8705. }
  8706. // 验证模型是否在可用模型表中
  8707. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8708. $model = 'deepseek-v4-pro';
  8709. }
  8710. // 模型兼容性处理
  8711. $thinkingMode = 'disabled';
  8712. $reasoningEffort = 'high';
  8713. if ($model === 'deepseek-chat') {
  8714. $model = 'deepseek-v4-flash';
  8715. $thinkingMode = 'disabled';
  8716. } elseif ($model === 'deepseek-reasoner') {
  8717. $model = 'deepseek-v4-flash';
  8718. $thinkingMode = 'enabled';
  8719. }
  8720. // 构建消息
  8721. $messages = [
  8722. [
  8723. 'role' => 'system',
  8724. 'content' => $system_prompt
  8725. ],
  8726. [
  8727. 'role' => 'user',
  8728. 'content' => $user_prompt
  8729. ]
  8730. ];
  8731. // dd($messages);
  8732. // 构建请求参数
  8733. $post_data = [
  8734. 'model' => $model,
  8735. 'messages' => $messages,
  8736. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8737. 'frequency_penalty' => 0,
  8738. 'presence_penalty' => 0,
  8739. 'response_format' => ['type' => 'text'],
  8740. 'thinking' => ['type' => $thinkingMode],
  8741. 'stream' => false // 非流式输出
  8742. ];
  8743. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8744. // 调用AI生成新的分段剧本
  8745. try {
  8746. $fullContent = '';
  8747. $usage = [];
  8748. // 根据模型类型选择调用方法
  8749. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8750. // DeepSeek 官方模型使用 DeepSeek API
  8751. $chatResult = $this->chatOnly($post_data);
  8752. } else if (in_array($model, $this->gpt_text_models)) {
  8753. // GPT 模型使用 TokenRouter API
  8754. $chatResult = $this->gpt54ChatOnly($post_data);
  8755. } else {
  8756. // 其他模型使用火山引擎API
  8757. $chatResult = $this->volcEngineChatCompletion($post_data);
  8758. }
  8759. if (is_array($chatResult)) {
  8760. $fullContent = $chatResult['fullContent'] ?? '';
  8761. $usage = $chatResult['usage'] ?? [];
  8762. }
  8763. $generated_content = $fullContent;
  8764. if (empty($generated_content)) {
  8765. Utils::throwError('20003:AI生成内容为空,请重试');
  8766. }
  8767. // 解析生成的内容 - 按片段分割
  8768. $parsed_segments = [];
  8769. // 先在开头添加换行符,确保第1片段也能被正确分割
  8770. $normalizedText = "\n" . $generated_content;
  8771. $parts = preg_split('/\n\s*##/', $normalizedText);
  8772. foreach ($parts as $part) {
  8773. $part = trim($part);
  8774. if (empty($part)) continue;
  8775. // 匹配"片段X"格式
  8776. if (!preg_match('/^片段\d+/', $part)) {
  8777. continue;
  8778. }
  8779. // 分离标题和内容
  8780. $lines = explode("\n", $part, 2);
  8781. $actTitle = trim($lines[0]);
  8782. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  8783. // 解析标题,提取序号
  8784. $actNumber = 0;
  8785. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  8786. $actNumber = intval($segmentTitleMatch[1]);
  8787. } else {
  8788. $actNumber = count($parsed_segments) + 1;
  8789. }
  8790. // 提取时长(仅保留数字)
  8791. $actDuration = 0;
  8792. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  8793. $actDurationStr = trim($actDurationMatch[1]);
  8794. // 提取数字部分(支持整数和小数)
  8795. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  8796. $actDuration = (float)$numMatch[1];
  8797. }
  8798. }
  8799. // 清理act_content:去除时长、旁白音色等非分镜内容行
  8800. // 只保留分镜内容,并确保分镜标记使用【】格式
  8801. $cleaned_content = '';
  8802. $content_lines = explode("\n", $actContent);
  8803. $is_capturing = false; // 标记是否开始捕获分镜内容
  8804. $count = 0;
  8805. foreach ($content_lines as $line) {
  8806. $trimmed_line = trim($line);
  8807. // 跳过时长和旁白音色行
  8808. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  8809. continue;
  8810. }
  8811. // 检测是否是分镜开始
  8812. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  8813. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  8814. $count++;
  8815. $is_capturing = true;
  8816. // 如果没有【】,则添加
  8817. if (!preg_match('/^【/u', $trimmed_line)) {
  8818. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  8819. }
  8820. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  8821. }
  8822. // 如果已经开始捕获,则添加该行
  8823. if ($is_capturing && !empty($trimmed_line)) {
  8824. $cleaned_content .= $trimmed_line."\n";
  8825. }
  8826. }
  8827. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  8828. $parsed_segments[] = [
  8829. 'act_number' => $actNumber,
  8830. 'act_title' => $actTitle,
  8831. 'act_duration' => $actDuration,
  8832. 'act_content' => $cleaned_content,
  8833. ];
  8834. }
  8835. if (empty($parsed_segments)) {
  8836. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  8837. }
  8838. // 收集所有资产名称(角色、场景、道具)
  8839. $product_names = [];
  8840. // 收集角色名称
  8841. if (!empty($roles) && is_array($roles)) {
  8842. foreach ($roles as $role) {
  8843. $role_name = getProp($role, 'role', '');
  8844. if (!empty($role_name)) {
  8845. $product_names[] = $role_name;
  8846. }
  8847. }
  8848. }
  8849. // 收集场景名称
  8850. if (!empty($scenes) && is_array($scenes)) {
  8851. foreach ($scenes as $scene) {
  8852. $scene_name = getProp($scene, 'scene', '');
  8853. if (!empty($scene_name)) {
  8854. $product_names[] = $scene_name;
  8855. }
  8856. }
  8857. }
  8858. // 收集道具名称
  8859. if (!empty($props) && is_array($props)) {
  8860. foreach ($props as $prop) {
  8861. $prop_name = getProp($prop, 'prop', '');
  8862. if (!empty($prop_name)) {
  8863. $product_names[] = $prop_name;
  8864. }
  8865. }
  8866. }
  8867. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  8868. $product_names = array_unique($product_names);
  8869. usort($product_names, function($a, $b) {
  8870. return mb_strlen($b) - mb_strlen($a);
  8871. });
  8872. // 处理每个片段的 act_show_content
  8873. foreach ($parsed_segments as &$segment) {
  8874. $act_content = getProp($segment, 'act_content', '');
  8875. if (empty($act_content)) {
  8876. $segment['act_show_content'] = '';
  8877. continue;
  8878. }
  8879. $processed_content = $act_content;
  8880. // 统一替换所有资产名称为 {资产名} 格式
  8881. // 使用占位符避免嵌套替换问题
  8882. $placeholder_map = [];
  8883. $placeholder_index = 0;
  8884. foreach ($product_names as $product_name) {
  8885. // 转义特殊字符
  8886. $escaped_product = preg_quote($product_name, '/');
  8887. // 检查是否匹配且未被 {} 包裹
  8888. $processed_content = preg_replace_callback(
  8889. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  8890. function($matches) use (&$placeholder_map, &$placeholder_index) {
  8891. // 使用唯一占位符
  8892. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  8893. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  8894. $placeholder_index++;
  8895. return $placeholder;
  8896. },
  8897. $processed_content
  8898. );
  8899. }
  8900. // 将所有占位符替换回实际内容
  8901. foreach ($placeholder_map as $placeholder => $replacement) {
  8902. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  8903. }
  8904. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  8905. $shot_counter = 0;
  8906. $processed_content = preg_replace_callback(
  8907. '/【(?:镜头|分镜)(\d+)】/u',
  8908. function($matches) use (&$shot_counter) {
  8909. $shot_counter++;
  8910. return '【镜头' . $shot_counter . '】';
  8911. },
  8912. $processed_content
  8913. );
  8914. $segment['act_show_content'] = $processed_content;
  8915. }
  8916. unset($segment); // 解除引用
  8917. // 保存到数据库
  8918. $now = date('Y-m-d H:i:s');
  8919. $saved_acts = []; // 用于记录保存后的片段信息
  8920. if ($act_id > 0) {
  8921. // 单个片段模式:更新单条记录
  8922. if (count($parsed_segments) > 0) {
  8923. $new_segment = $parsed_segments[0];
  8924. $update_data = [
  8925. 'act_content' => getProp($new_segment, 'act_content', ''),
  8926. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  8927. 'act_title' => getProp($new_segment, 'act_title', ''),
  8928. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  8929. 'updated_at' => $now,
  8930. ];
  8931. DB::table('mp_episode_segments')
  8932. ->where('id', $act_id)
  8933. ->update($update_data);
  8934. // 获取更新后的记录
  8935. $updated_act = DB::table('mp_episode_segments')
  8936. ->where('id', $act_id)
  8937. ->first();
  8938. if ($updated_act) {
  8939. $saved_acts[] = [
  8940. 'act_id' => $updated_act->id,
  8941. 'act_number' => $updated_act->act_number,
  8942. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  8943. 'act_content' => $updated_act->act_content,
  8944. 'act_show_content' => $updated_act->act_show_content,
  8945. 'video_url' => $updated_act->video_url ?? '',
  8946. 'video_duration' => $updated_act->video_duration ?? 0,
  8947. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  8948. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  8949. ];
  8950. }
  8951. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  8952. }
  8953. } else {
  8954. // 整个剧集模式:删除原有记录并批量保存新记录
  8955. DB::beginTransaction();
  8956. try {
  8957. // 删除原有的所有片段记录
  8958. DB::table('mp_episode_segments')
  8959. ->where('episode_id', $target_episode_id)
  8960. ->delete();
  8961. // 批量插入新的片段记录
  8962. $segments_to_insert = [];
  8963. foreach ($parsed_segments as $index => $segment) {
  8964. $act_number = $index + 1;
  8965. $segments_to_insert[] = [
  8966. 'anime_id' => $target_anime_id,
  8967. 'episode_id' => $target_episode_id,
  8968. 'episode_number' => $target_episode_number,
  8969. 'act_number' => $act_number,
  8970. 'act_title' => getProp($segment, 'act_title', ''),
  8971. 'act_duration' => getProp($segment, 'act_duration', 0),
  8972. 'act_content' => getProp($segment, 'act_content', ''),
  8973. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  8974. 'created_at' => $now,
  8975. 'updated_at' => $now,
  8976. ];
  8977. }
  8978. if (!empty($segments_to_insert)) {
  8979. DB::table('mp_episode_segments')->insert($segments_to_insert);
  8980. }
  8981. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8982. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8983. 'anime_id' => $target_anime_id,
  8984. 'episode_id' => $target_episode_id,
  8985. ]);
  8986. DB::commit();
  8987. // 查询保存后的所有片段记录
  8988. $saved_segments = DB::table('mp_episode_segments')
  8989. ->where('episode_id', $target_episode_id)
  8990. ->orderBy('act_number')
  8991. ->get();
  8992. foreach ($saved_segments as $saved_segment) {
  8993. $saved_acts[] = [
  8994. 'act_id' => $saved_segment->id,
  8995. 'act_number' => $saved_segment->act_number,
  8996. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  8997. 'act_content' => $saved_segment->act_content,
  8998. 'act_show_content' => $saved_segment->act_show_content,
  8999. 'video_url' => $saved_segment->video_url ?? '',
  9000. 'video_duration' => $saved_segment->video_duration ?? 0,
  9001. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  9002. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  9003. ];
  9004. }
  9005. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  9006. 'episode_id' => $target_episode_id,
  9007. 'segments_count' => count($segments_to_insert)
  9008. ]);
  9009. } catch (\Exception $e) {
  9010. DB::rollBack();
  9011. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  9012. Utils::throwError('20003:保存失败,请重试');
  9013. }
  9014. }
  9015. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  9016. return [
  9017. 'anime_id' => $target_anime_id,
  9018. 'episode_id' => $target_episode_id,
  9019. 'title' => getProp($episode, 'title', ''),
  9020. 'episode_number' => $target_episode_number,
  9021. 'is_generated' => getProp($episode, 'is_generated', 0),
  9022. 'acts' => $saved_acts,
  9023. ];
  9024. } catch (\Exception $e) {
  9025. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  9026. throw $e;
  9027. }
  9028. }
  9029. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  9030. {
  9031. $episode_arr = [
  9032. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  9033. 'intro' => getProp($script_arr, 'intro'),
  9034. 'art_style' => getProp($script_arr, 'art_style'),
  9035. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  9036. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  9037. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  9038. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  9039. ];
  9040. if (empty($episode_arr['acts'])) {
  9041. $fallback_episode_arr = handleEpisodeContent($fullContent);
  9042. if (!empty($fallback_episode_arr['acts'])) {
  9043. $episode_arr = array_merge($fallback_episode_arr, [
  9044. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  9045. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  9046. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  9047. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  9048. ]);
  9049. }
  9050. }
  9051. // if (!getProp($episode_arr, 'episode_title')) {
  9052. // $episode_title = '';
  9053. // $episodes = getProp($script_arr, 'episodes', []);
  9054. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  9055. // $episode_title = '第1集:' . $episodes[0]['title'];
  9056. // }
  9057. // if (!$episode_title) {
  9058. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  9059. // }
  9060. // $episode_arr['episode_title'] = $episode_title;
  9061. // }
  9062. return $episode_arr;
  9063. }
  9064. private function saveEpisodeVersionData(
  9065. int $anime_id,
  9066. int $episode_number,
  9067. array $episode_arr,
  9068. array $existing_roles,
  9069. array $existing_scenes,
  9070. array $existing_props,
  9071. $current_episode,
  9072. $base_episode,
  9073. bool $is_regenerate_version,
  9074. string $content,
  9075. string $now,
  9076. array $ref_products = []
  9077. ): array {
  9078. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  9079. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  9080. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  9081. // 过滤掉关键字段为空的条目
  9082. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  9083. return !empty($item['role'] ?? null);
  9084. }));
  9085. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  9086. return !empty($item['scene'] ?? null);
  9087. }));
  9088. $merged_props = array_values(array_filter($generated_props, function ($item) {
  9089. return !empty($item['prop'] ?? null);
  9090. }));
  9091. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  9092. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  9093. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  9094. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9095. $ace_mode = getProp($anime, 'ace_mode');
  9096. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  9097. $global_roles = json_decode(getProp($anime, 'roles'), true);
  9098. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  9099. $global_roles = is_array($global_roles) ? $global_roles : [];
  9100. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  9101. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  9102. $art_style_type = getProp($anime, 'art_style_type');
  9103. // 检查并创建 roles 的图片生成任务
  9104. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  9105. // 检查并创建 scenes 的图片生成任务
  9106. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  9107. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  9108. if ($arr && is_array($arr)) {
  9109. $merged_roles = $arr['roles'];
  9110. $merged_scenes = $arr['scenes'];
  9111. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  9112. }
  9113. // 确保数据是数组类型
  9114. if (!is_array($merged_roles)) {
  9115. dLog('deepseek')->error('merged_roles不是数组类型', [
  9116. 'type' => gettype($merged_roles),
  9117. 'value' => $merged_roles
  9118. ]);
  9119. $merged_roles = [];
  9120. }
  9121. if (!is_array($merged_scenes)) {
  9122. dLog('deepseek')->error('merged_scenes不是数组类型', [
  9123. 'type' => gettype($merged_scenes),
  9124. 'value' => $merged_scenes
  9125. ]);
  9126. $merged_scenes = [];
  9127. }
  9128. if (!is_array($merged_props)) {
  9129. dLog('deepseek')->error('merged_props不是数组类型', [
  9130. 'type' => gettype($merged_props),
  9131. 'value' => $merged_props
  9132. ]);
  9133. $merged_props = [];
  9134. }
  9135. // 同步新出现的主体和场景到全局
  9136. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  9137. $role_arr = [];
  9138. foreach ($merged_roles as $item) {
  9139. $role_arr[$item['role']] = $item;
  9140. }
  9141. $version_count = DB::table('mp_anime_episodes')
  9142. ->where('anime_id', $anime_id)
  9143. ->where('episode_number', $episode_number)
  9144. ->count('id');
  9145. $episode = [
  9146. 'anime_id' => $anime_id,
  9147. 'episode_number' => $episode_number,
  9148. 'title' => getProp($episode_arr, 'episode_title'),
  9149. 'content' => $content,
  9150. 'intro' => getProp($episode_arr, 'intro'),
  9151. 'art_style' => getProp($episode_arr, 'art_style'),
  9152. 'roles' => json_encode($merged_roles, 256),
  9153. 'scenes' => json_encode($merged_scenes, 256),
  9154. 'props' => json_encode($merged_props, 256),
  9155. 'generate_status' => '待执行',
  9156. 'generate_at' => $now,
  9157. 'is_default' => 1,
  9158. 'updated_at' => $now,
  9159. ];
  9160. $del_flag = false;
  9161. if ($is_regenerate_version) {
  9162. DB::table('mp_anime_episodes')
  9163. ->where('anime_id', $anime_id)
  9164. ->where('episode_number', $episode_number)
  9165. ->update(['is_default' => 0, 'updated_at' => $now]);
  9166. $episode['sequence'] = $version_count + 1;
  9167. $episode['created_at'] = $now;
  9168. $episode['cpid'] = Site::getCpid();
  9169. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9170. if (!$episode_id) {
  9171. Utils::throwError('20003:创建剧集版本失败');
  9172. }
  9173. } else {
  9174. $target_episode = $current_episode ?: $base_episode;
  9175. if ($target_episode) {
  9176. $episode_id = getProp($target_episode, 'id');
  9177. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  9178. DB::table('mp_anime_episodes')
  9179. ->where('anime_id', $anime_id)
  9180. ->where('episode_number', $episode_number)
  9181. ->where('id', '<>', $episode_id)
  9182. ->update(['is_default' => 0, 'updated_at' => $now]);
  9183. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  9184. if ($boolen === false) {
  9185. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  9186. Utils::throwError('20003:分集内容保存失败');
  9187. }
  9188. $del_flag = true;
  9189. } else {
  9190. DB::table('mp_anime_episodes')
  9191. ->where('anime_id', $anime_id)
  9192. ->where('episode_number', $episode_number)
  9193. ->update(['is_default' => 0, 'updated_at' => $now]);
  9194. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  9195. $episode['created_at'] = $now;
  9196. $episode['cpid'] = Site::getCpid();
  9197. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9198. if (!$episode_id) {
  9199. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  9200. Utils::throwError('20003:分集内容保存失败');
  9201. }
  9202. }
  9203. }
  9204. $segments = [];
  9205. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9206. // 如果是第2集及以后,获取上一集的主体音色数据
  9207. $previous_roles_voice = [];
  9208. if ($episode_number >= 2) {
  9209. $previous_episode = DB::table('mp_anime_episodes')
  9210. ->where('anime_id', $anime_id)
  9211. ->where('episode_number', $episode_number - 1)
  9212. ->where('is_default', 1)
  9213. ->first();
  9214. if ($previous_episode) {
  9215. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  9216. if (is_array($previous_roles)) {
  9217. foreach ($previous_roles as $prev_role) {
  9218. $role_name = getProp($prev_role, 'role');
  9219. if ($role_name) {
  9220. $previous_roles_voice[$role_name] = [
  9221. 'voice_name' => getProp($prev_role, 'voice_name'),
  9222. 'voice_type' => getProp($prev_role, 'voice_type'),
  9223. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  9224. ];
  9225. $voice_prompt = getProp($prev_role, 'voice_prompt');
  9226. if ($voice_prompt) {
  9227. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  9228. }
  9229. }
  9230. }
  9231. }
  9232. }
  9233. }
  9234. // 将继承的音色数据同步到当前集的主体列表
  9235. if (!empty($previous_roles_voice)) {
  9236. foreach ($merged_roles as &$role) {
  9237. $role_name = getProp($role, 'role');
  9238. if ($role_name && isset($previous_roles_voice[$role_name])) {
  9239. // 强制继承上一集的音色数据
  9240. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  9241. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  9242. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  9243. // 如果上一集有 voice_prompt 则继承,否则跳过
  9244. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  9245. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  9246. }
  9247. }
  9248. }
  9249. unset($role); // 解除引用
  9250. // 更新 role_arr 以便后续使用
  9251. $role_arr = [];
  9252. foreach ($merged_roles as $item) {
  9253. $role_arr[$item['role']] = $item;
  9254. }
  9255. }
  9256. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  9257. $emotion_list = array_flip($emotion_list);
  9258. foreach ($acts as $act) {
  9259. $act_segments = getProp($act, 'segments', []);
  9260. if (!is_array($act_segments)) {
  9261. continue;
  9262. }
  9263. if ((int)$ace_mode === 1) {
  9264. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  9265. $merged_parts = [];
  9266. foreach ($act_segments as $seg) {
  9267. $seg_num = getProp($seg, 'segment_number');
  9268. $seg_content = getProp($seg, 'segment_content');
  9269. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  9270. }
  9271. $act_content = implode("\n", $merged_parts);
  9272. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9273. $segments[] = [
  9274. 'anime_id' => $anime_id,
  9275. 'episode_id' => $episode_id,
  9276. 'episode_number' => $episode_number,
  9277. 'act_number' => getProp($act, 'act_number'),
  9278. 'act_title' => getProp($act, 'act_title'),
  9279. 'act_duration' => getProp($act, 'act_duration'),
  9280. 'act_content' => $act_content,
  9281. 'created_at' => $now,
  9282. 'updated_at' => $now
  9283. ];
  9284. } else {
  9285. foreach ($act_segments as $segment) {
  9286. $voice_actor = getProp($segment, 'voice_actor');
  9287. // 优先从上一集继承音色数据
  9288. $timbre_info = [];
  9289. if (isset($previous_roles_voice[$voice_actor])) {
  9290. // 从上一集继承音色数据
  9291. $timbre_info = $previous_roles_voice[$voice_actor];
  9292. } elseif (isset($role_arr[$voice_actor])) {
  9293. // 使用当前集的主体音色数据
  9294. $timbre_info = $role_arr[$voice_actor];
  9295. }
  9296. $voice_type = getProp($timbre_info, 'voice_type');
  9297. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  9298. if ($timbre_emotion) {
  9299. $timbre_emotion = explode(',', $timbre_emotion);
  9300. } else {
  9301. $timbre_emotion = [];
  9302. }
  9303. $emotion = getProp($segment, 'emotion', '中性');
  9304. if (!in_array($emotion, $timbre_emotion)) {
  9305. $emotion = '中性';
  9306. }
  9307. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  9308. $segments[] = [
  9309. 'anime_id' => $anime_id,
  9310. 'episode_id' => $episode_id,
  9311. 'episode_number' => $episode_number,
  9312. 'act_number' => getProp($act, 'act_number'),
  9313. 'act_title' => getProp($act, 'act_title'),
  9314. 'act_duration' => getProp($act, 'act_duration'),
  9315. 'segment_id' => getProp($segment, 'segment_id'),
  9316. 'segment_number' => getProp($segment, 'segment_number'),
  9317. 'segment_content' => getProp($segment, 'segment_content'),
  9318. 'description' => getProp($segment, 'description'),
  9319. 'composition' => getProp($segment, 'composition'),
  9320. 'camera_movement' => getProp($segment, 'camera_movement'),
  9321. 'voice_actor' => $voice_actor,
  9322. 'dialogue' => getProp($segment, 'dialogue'),
  9323. 'frame_type' => getProp($segment, 'frame_type'),
  9324. 'scene' => getProp($segment, 'scene'),
  9325. 'characters' => getProp($segment, 'characters'),
  9326. 'tail_frame' => getProp($segment, 'tail_frame'),
  9327. 'voice_name' => getProp($timbre_info, 'voice_name'),
  9328. 'voice_type' => $voice_type,
  9329. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  9330. 'emotion' => $emotion,
  9331. 'emotion_type' => $emotion_type,
  9332. 'gender' => getProp($segment, 'gender', '0'),
  9333. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  9334. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  9335. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  9336. 'pitch' => getProp($segment, 'pitch', 0),
  9337. 'created_at' => $now,
  9338. 'updated_at' => $now
  9339. ];
  9340. }
  9341. }
  9342. }
  9343. if ($segments) {
  9344. if ($del_flag) {
  9345. DB::table('mp_episode_segments')
  9346. ->where('anime_id', $anime_id)
  9347. ->where('episode_id', $episode_id)
  9348. ->delete();
  9349. }
  9350. $boolen = DB::table('mp_episode_segments')->insert($segments);
  9351. if (!$boolen) {
  9352. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  9353. Utils::throwError('20003:分镜内容保存失败');
  9354. }
  9355. }
  9356. dLog('deepseek')->info('segments', $segments);
  9357. // ace_mode=1: acts 返回值按合并格式调整
  9358. if ((int)$ace_mode === 1) {
  9359. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  9360. $act_map = [];
  9361. foreach ($table_act_data as $item) {
  9362. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  9363. }
  9364. $restructured_acts = [];
  9365. foreach ($acts as $act) {
  9366. $act_segments = getProp($act, 'segments', []);
  9367. if (!is_array($act_segments)) {
  9368. continue;
  9369. }
  9370. $merged_parts = [];
  9371. foreach ($act_segments as $seg) {
  9372. $seg_num = getProp($seg, 'segment_number');
  9373. $seg_content = getProp($seg, 'segment_content');
  9374. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  9375. }
  9376. $act_content = implode("\n", $merged_parts);
  9377. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9378. $restructured_acts[] = [
  9379. 'anime_id' => $anime_id,
  9380. 'episode_id' => $episode_id,
  9381. 'episode_number' => $episode_number,
  9382. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  9383. 'act_number' => getProp($act, 'act_number'),
  9384. 'act_title' => getProp($act, 'act_title'),
  9385. 'act_duration' => getProp($act, 'act_duration'),
  9386. 'act_content' => $act_content,
  9387. 'created_at' => $now,
  9388. 'updated_at' => $now,
  9389. ];
  9390. }
  9391. $acts = $restructured_acts;
  9392. }
  9393. $episode['episode_id'] = $episode_id;
  9394. $episode['roles'] = $merged_roles;
  9395. $episode['scenes'] = $merged_scenes;
  9396. $episode['props'] = $merged_props;
  9397. $episode['acts'] = $acts;
  9398. return [
  9399. 'episode' => $episode,
  9400. 'episode_id' => $episode_id,
  9401. 'merged_roles' => $merged_roles,
  9402. 'merged_scenes' => $merged_scenes,
  9403. 'merged_props' => $merged_props,
  9404. ];
  9405. }
  9406. private function buildEpisodeItemContent(array $items, string $nameKey): string
  9407. {
  9408. $content = '';
  9409. foreach ($items as $item) {
  9410. $name = trim((string)getProp($item, $nameKey));
  9411. if ($name === '' || $name === '旁白') {
  9412. continue;
  9413. }
  9414. $description = trim((string)getProp($item, 'description'));
  9415. $content .= $name . ': ' . $description;
  9416. if ($nameKey == 'role') {
  9417. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9418. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9419. $voice_name = trim(getProp($item, 'voice_name'));
  9420. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9421. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  9422. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9423. }else {
  9424. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9425. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9426. }
  9427. $content .= "\n";
  9428. }
  9429. return trim($content);
  9430. }
  9431. private function getEpisodeChatContent($animeId, $sequence, $content) {
  9432. if ((int)$sequence <= 0) {
  9433. return [];
  9434. }
  9435. $origin_content = '';
  9436. if ($content) {
  9437. $origin_content = '本集剧情内容:'.$content;
  9438. }else {
  9439. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  9440. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  9441. }
  9442. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  9443. // 获取分集信息
  9444. $episode = DB::table('mp_anime_episodes')
  9445. ->where('anime_id', $animeId)
  9446. ->where('episode_number', $sequence)
  9447. ->where('is_default', 1)
  9448. ->first();
  9449. if (!$episode) {
  9450. return [];
  9451. }
  9452. $episode_id = getProp($episode, 'id');
  9453. $episode_number = getProp($episode, 'episode_number');
  9454. $title = getProp($episode, 'title');
  9455. $intro = getProp($episode, 'intro');
  9456. $art_style = getProp($episode, 'art_style');
  9457. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9458. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9459. // 组装纯文本内容
  9460. $content = '';
  9461. // 添加分集标题和梗概
  9462. $content .= "###第{$episode_number}集:{$title}\n\n";
  9463. $content .= "###故事梗概\n";
  9464. $content .= trim($intro) . "\n\n";
  9465. // 添加美术风格
  9466. $content .= "###美术风格\n";
  9467. $content .= trim($art_style) . "\n\n";
  9468. // 添加主体列表
  9469. $content .= "###主体列表\n";
  9470. $pangbai_voice_prompt = "";
  9471. foreach ($roles as $role) {
  9472. $name = getProp($role, 'role');
  9473. $description = getProp($role, 'description');
  9474. $pic_prompt = getProp($role, 'pic_prompt');
  9475. $voice_prompt = getProp($role, 'voice_prompt');
  9476. $voice_name = getProp($role, 'voice_name');
  9477. $content .= "{$name}: {$description}";
  9478. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9479. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9480. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9481. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  9482. $content .= "\n";
  9483. }
  9484. $content .= "\n";
  9485. // 添加场景列表
  9486. $content .= "###场景列表\n";
  9487. foreach ($scenes as $scene) {
  9488. $name = getProp($scene, 'scene');
  9489. $description = getProp($scene, 'description');
  9490. $pic_prompt = getProp($scene, 'pic_prompt');
  9491. $content .= "{$name}: {$description}";
  9492. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9493. $content .= "\n";
  9494. }
  9495. $content .= "\n";
  9496. // 获取分镜信息
  9497. $segments = DB::table('mp_episode_segments')
  9498. ->where('anime_id', $animeId)
  9499. ->where('episode_id', $episode_id)
  9500. ->orderBy('segment_number')
  9501. ->get();
  9502. if ($segments && count($segments) > 0) {
  9503. if ((int)$ace_mode === 1) {
  9504. $content .= "###分段剧本\n";
  9505. // 获取片段数量
  9506. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  9507. $content .= "片段数量:{$act_count}\n";
  9508. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  9509. $content .= "\n";
  9510. }else {
  9511. $content .= "###分镜剧本\n";
  9512. }
  9513. // 按幕分组
  9514. $currentAct = null;
  9515. foreach ($segments as $segment) {
  9516. $act_number = getProp($segment, 'act_number');
  9517. $act_title = getProp($segment, 'act_title');
  9518. $act_duration = getProp($segment, 'act_duration');
  9519. $segment_number = getProp($segment, 'segment_number');
  9520. $segment_content = getProp($segment, 'segment_content');
  9521. $scene_description = getProp($segment, 'scene_description');
  9522. $scene_name = getProp($segment, 'scene_name');
  9523. $composition = getProp($segment, 'composition');
  9524. $camera_movement = getProp($segment, 'camera_movement');
  9525. $voice_type = getProp($segment, 'voice_type');
  9526. $characters = getProp($segment, 'characters');
  9527. $dialogue = getProp($segment, 'dialogue');
  9528. $frame_type = getProp($segment, 'frame_type');
  9529. $tail_frame_description = getProp($segment, 'tail_frame_description');
  9530. // 判断是否是全能模式
  9531. if ((int)$ace_mode === 1) { // 全能模式
  9532. // 如果是新的分段,添加分段标题
  9533. if ($act_number !== $currentAct) {
  9534. $currentAct = $act_number;
  9535. $content .= "##{$act_title}\n";
  9536. $content .= "时长:{$act_duration}s\n";
  9537. }
  9538. }else {
  9539. // 如果是新的幕,添加幕标题
  9540. if ($act_number !== $currentAct) {
  9541. $currentAct = $act_number;
  9542. $content .= "##第{$act_number}幕:{$scene_name}\n";
  9543. }
  9544. }
  9545. // 添加分镜信息
  9546. $content .= "分镜{$segment_number}\n";
  9547. $content .= "分镜内容:\n{$segment_content}\n";
  9548. // $content .= "画面描述:{$scene_description}\n";
  9549. // $content .= "场景:{$scene_name}\n";
  9550. // $content .= "构图设计:{$composition}\n";
  9551. // $content .= "运镜调度:{$camera_movement}\n";
  9552. // if (!empty($voice_type)) {
  9553. // $content .= "配音角色:{$voice_type}\n";
  9554. // }
  9555. // if (!empty($characters)) {
  9556. // $content .= "出镜角色:{$characters}\n";
  9557. // }
  9558. // if (!empty($dialogue)) {
  9559. // $content .= "台词内容:\"{$dialogue}\"\n";
  9560. // }
  9561. // $content .= "画面类型:{$frame_type}\n";
  9562. // $content .= "尾帧描述:{$tail_frame_description}\n";
  9563. $content .= "\n";
  9564. }
  9565. }
  9566. $content = trim($content);
  9567. if($content) $content = "上集剧本内容:\n{$content}";
  9568. return [
  9569. [
  9570. 'role' => 'user',
  9571. 'content' => $origin_content
  9572. ],
  9573. [
  9574. 'role' => 'assistant',
  9575. 'content' => $content
  9576. ]
  9577. ];
  9578. }
  9579. private function getEpisodeChatMessages($animeId, $sequence): array
  9580. {
  9581. if ((int)$sequence <= 0) {
  9582. return [];
  9583. }
  9584. return DB::table('mp_anime_records')
  9585. ->where('anime_id', $animeId)
  9586. ->where('sequence', $sequence)
  9587. ->where('episode_id', '>', 0)
  9588. ->select('role', 'content')
  9589. ->orderBy('created_at')
  9590. ->orderBy('id')
  9591. ->get()
  9592. ->map(function ($value) {
  9593. return (array)$value;
  9594. })
  9595. ->toArray();
  9596. }
  9597. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  9598. {
  9599. $existingMap = [];
  9600. foreach ($existingItems as $item) {
  9601. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9602. if ($itemKey === '') {
  9603. continue;
  9604. }
  9605. $existingMap[$itemKey] = $item;
  9606. }
  9607. if (!$generatedItems) {
  9608. return array_values($existingItems);
  9609. }
  9610. $merged = [];
  9611. foreach ($generatedItems as $item) {
  9612. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9613. if ($itemKey === '') {
  9614. continue;
  9615. }
  9616. if (isset($existingMap[$itemKey])) {
  9617. if (trim((string)getProp($item, 'description')) === '') {
  9618. $merged[] = $existingMap[$itemKey];
  9619. continue;
  9620. }
  9621. // 检查内容是否发生变化
  9622. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  9623. if (!$isChanged) {
  9624. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  9625. $mergedItem = [
  9626. $nameKey => trim((string)getProp($item, $nameKey)),
  9627. 'description' => trim((string)getProp($item, 'description')),
  9628. ];
  9629. // 如果有 pic_prompt,添加到合并项中
  9630. $picPrompt = getProp($item, 'pic_prompt');
  9631. if (!empty($picPrompt)) {
  9632. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9633. }
  9634. // 继承现有项的 URL
  9635. $existingUrl = getProp($existingMap[$itemKey], 'url');
  9636. if (!empty($existingUrl)) {
  9637. $mergedItem['url'] = $existingUrl;
  9638. }
  9639. // 继承现有项的 task_id
  9640. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  9641. if (!empty($existingTaskId)) {
  9642. $mergedItem['task_id'] = $existingTaskId;
  9643. }
  9644. // 继承现有项的 task_status
  9645. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  9646. if (!empty($existingTaskStatus)) {
  9647. $mergedItem['task_status'] = $existingTaskStatus;
  9648. }
  9649. // 保留生成项的音色字段
  9650. $voiceName = getProp($item, 'voice_name');
  9651. if (!empty($voiceName)) {
  9652. $mergedItem['voice_name'] = $voiceName;
  9653. }
  9654. $voiceType = getProp($item, 'voice_type');
  9655. if (!empty($voiceType)) {
  9656. $mergedItem['voice_type'] = $voiceType;
  9657. }
  9658. $audioUrl = getProp($item, 'voice_audio_url');
  9659. if (!empty($audioUrl)) {
  9660. $mergedItem['voice_audio_url'] = $audioUrl;
  9661. }
  9662. $merged[] = $mergedItem;
  9663. } else {
  9664. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  9665. $mergedItem = [
  9666. $nameKey => trim((string)getProp($item, $nameKey)),
  9667. 'description' => trim((string)getProp($item, 'description')),
  9668. ];
  9669. // 如果有 pic_prompt,添加到合并项中
  9670. $picPrompt = getProp($item, 'pic_prompt');
  9671. if (!empty($picPrompt)) {
  9672. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9673. }
  9674. // 保留生成项的音色字段
  9675. $voiceName = getProp($item, 'voice_name');
  9676. if (!empty($voiceName)) {
  9677. $mergedItem['voice_name'] = $voiceName;
  9678. }
  9679. $voiceType = getProp($item, 'voice_type');
  9680. if (!empty($voiceType)) {
  9681. $mergedItem['voice_type'] = $voiceType;
  9682. }
  9683. $audioUrl = getProp($item, 'voice_audio_url');
  9684. if (!empty($audioUrl)) {
  9685. $mergedItem['voice_audio_url'] = $audioUrl;
  9686. }
  9687. // 不继承 URL、task_id 和 task_status(重置状态)
  9688. $merged[] = $mergedItem;
  9689. }
  9690. } else {
  9691. // 新增项,保留生成项的所有字段
  9692. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  9693. }
  9694. }
  9695. return $merged ?: array_values($existingItems);
  9696. }
  9697. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  9698. {
  9699. $resetItem = [
  9700. $nameKey => trim((string)getProp($item, $nameKey)),
  9701. 'description' => trim((string)getProp($item, 'description')),
  9702. ];
  9703. // 保留指定的字段
  9704. foreach ($preserveFields as $field) {
  9705. $value = getProp($item, $field);
  9706. if (!empty($value)) {
  9707. $resetItem[$field] = $value;
  9708. }
  9709. }
  9710. return $resetItem;
  9711. }
  9712. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  9713. {
  9714. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  9715. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  9716. if ($existingKey !== $generatedKey) {
  9717. return true;
  9718. }
  9719. // 比较 description 是否变化
  9720. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  9721. return true;
  9722. }
  9723. // 比较 pic_prompt 是否变化
  9724. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  9725. }
  9726. private function normalizeEpisodeResourceKey($value): string
  9727. {
  9728. $value = trim((string)$value);
  9729. if ($value === '') {
  9730. return '';
  9731. }
  9732. return strtolower((string)preg_replace('/\s+/u', '', $value));
  9733. }
  9734. // 生成全局角色图片
  9735. private function batchSetGlobalRoleImg($data, $is_force=false) {
  9736. $anime_id = getProp($data, 'anime_id');
  9737. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9738. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9739. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9740. $art_style = getProp($anime, 'art_style');
  9741. $update_flag = false;
  9742. foreach ($roles as &$role) {
  9743. $role_name = getProp($role, 'role');
  9744. if ($role_name == '旁白') continue;
  9745. // 优先使用 pic_prompt,如果没有则使用 description
  9746. $pic_prompt = getProp($role, 'pic_prompt');
  9747. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  9748. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9749. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9750. // 参考图地址
  9751. $ref_img_url = getProp($role, 'url');
  9752. if (!$is_force && $ref_img_url) continue;
  9753. $update_flag = true;
  9754. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9755. try {
  9756. $params = [
  9757. 'prompt' => $description,
  9758. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  9759. 'ref_img_urls' => []
  9760. ];
  9761. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9762. $task_id = $task->id;
  9763. if (!$task_id) {
  9764. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  9765. }
  9766. $role['task_id'] = $task_id;
  9767. $role['task_status'] = 'processing';
  9768. } catch (\Exception $e) {
  9769. Utils::throwError("20003:" . $e->getMessage());
  9770. }
  9771. }
  9772. if (!$update_flag) return true;
  9773. // 保存角色信息
  9774. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9775. 'roles' => json_encode($roles, 256),
  9776. 'generate_status' => '执行中',
  9777. 'generate_at' => date('Y-m-d H:i:s'),
  9778. 'updated_at' => date('Y-m-d H:i:s')
  9779. ]);
  9780. if (!$boolen) {
  9781. Utils::throwError('20003:保存角色信息失败');
  9782. }
  9783. return $boolen;
  9784. }
  9785. // 生成全局场景图片
  9786. private function batchSetGlobalSceneImg($data, $is_force=false) {
  9787. $anime_id = getProp($data, 'anime_id');
  9788. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9789. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9790. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  9791. $art_style = getProp($anime, 'art_style');
  9792. $update_flag = false;
  9793. foreach ($scenes as &$scene) {
  9794. $scene_name = getProp($scene, 'scene');
  9795. // 优先使用 pic_prompt,如果没有则使用 description
  9796. $pic_prompt = getProp($scene, 'pic_prompt');
  9797. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  9798. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  9799. // 参考图地址
  9800. $ref_img_url = getProp($scene, 'url');
  9801. if (!$is_force && $ref_img_url) continue;
  9802. $update_flag = true;
  9803. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9804. try {
  9805. $params = [
  9806. 'prompt' => $description,
  9807. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  9808. 'ref_img_urls' => []
  9809. ];
  9810. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9811. $task_id = $task->id;
  9812. if (!$task_id) {
  9813. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  9814. }
  9815. $scene['task_id'] = $task_id;
  9816. $scene['task_status'] = 'processing';
  9817. } catch (\Exception $e) {
  9818. Utils::throwError("20003:" . $e->getMessage());
  9819. }
  9820. }
  9821. if (!$update_flag) return true;
  9822. // 保存角色信息
  9823. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9824. 'scenes' => json_encode($scenes, 256),
  9825. 'generate_status' => '执行中',
  9826. 'generate_at' => date('Y-m-d H:i:s'),
  9827. 'updated_at' => date('Y-m-d H:i:s')
  9828. ]);
  9829. if (!$boolen) {
  9830. Utils::throwError('20003:保存角色信息失败');
  9831. }
  9832. return $boolen;
  9833. }
  9834. // 生成分镜主体、场景和道具图片
  9835. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  9836. $character_prefix = '';
  9837. $scene_prefix = '';
  9838. $prop_prefix = '';
  9839. if ($art_style_type) {
  9840. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  9841. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  9842. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  9843. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  9844. }
  9845. $update_flag = false;
  9846. // 获取上一集的roles、scenes和props数据
  9847. $prev_roles = [];
  9848. $prev_scenes = [];
  9849. $prev_props = [];
  9850. if ($episode_number > 1) {
  9851. $prev_episode = DB::table('mp_anime_episodes')
  9852. ->where('anime_id', $anime_id)
  9853. ->where('episode_number', $episode_number - 1)
  9854. ->where('is_default', 1)
  9855. ->first();
  9856. if ($prev_episode) {
  9857. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  9858. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  9859. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  9860. dLog('deepseek')->info("获取上一集数据成功", [
  9861. 'anime_id' => $anime_id,
  9862. 'prev_episode_number' => $episode_number - 1,
  9863. 'prev_roles_count' => count($prev_roles),
  9864. 'prev_scenes_count' => count($prev_scenes),
  9865. 'prev_props_count' => count($prev_props)
  9866. ]);
  9867. }
  9868. }
  9869. // 处理角色图片生成
  9870. foreach ($roles as &$role) {
  9871. $role_name = getProp($role, 'role');
  9872. if ($role_name == '旁白') continue;
  9873. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  9874. if (isset($ref_products[$role_name])) {
  9875. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  9876. if ($role['url']) continue;
  9877. }
  9878. $role_description = getProp($role, 'description');
  9879. $role_pic_prompt = getProp($role, 'pic_prompt');
  9880. $role_url = getProp($role, 'url');
  9881. // 检查是否可以从上一集继承
  9882. $inherited = false;
  9883. if (!$is_force && !empty($prev_roles)) {
  9884. foreach ($prev_roles as $prev_role) {
  9885. $prev_role_name = getProp($prev_role, 'role');
  9886. $prev_description = getProp($prev_role, 'description');
  9887. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  9888. $prev_url = getProp($prev_role, 'url');
  9889. $prev_task_id = getProp($prev_role, 'task_id');
  9890. $prev_task_status = getProp($prev_role, 'task_status');
  9891. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  9892. if ($role_name == $prev_role_name
  9893. && $role_description == $prev_description
  9894. && $role_pic_prompt == $prev_pic_prompt
  9895. && !empty($prev_url)) {
  9896. $role['task_id'] = $prev_task_id;
  9897. $role['task_status'] = $prev_task_status;
  9898. $role['url'] = $prev_url;
  9899. $inherited = true;
  9900. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  9901. 'anime_id' => $anime_id,
  9902. 'episode_number' => $episode_number,
  9903. 'task_id' => $prev_task_id,
  9904. 'url' => $prev_url
  9905. ]);
  9906. break;
  9907. }
  9908. }
  9909. }
  9910. // 如果已继承或已有url,跳过生成
  9911. if ($inherited || (!$is_force && $role_url)) {
  9912. continue;
  9913. }
  9914. // 优先使用 pic_prompt,如果没有则使用 description
  9915. $pic_prompt = getProp($role, 'pic_prompt');
  9916. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  9917. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  9918. $update_flag = true;
  9919. // 调用AIImageGenerationService的生成图片任务接口
  9920. try {
  9921. $params = [
  9922. 'prompt' => $description,
  9923. 'ref_img_urls' => []
  9924. ];
  9925. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9926. $task_id = $task->id;
  9927. if (!$task_id) {
  9928. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  9929. continue; // 不中断,继续处理其他角色
  9930. }
  9931. $role['task_id'] = $task_id;
  9932. $role['task_status'] = 'processing';
  9933. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  9934. 'anime_id' => $anime_id,
  9935. 'episode_number' => $episode_number,
  9936. 'task_id' => $task_id
  9937. ]);
  9938. } catch (\Exception $e) {
  9939. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  9940. // 不抛出异常,继续处理其他角色
  9941. }
  9942. }
  9943. // 处理场景图片生成
  9944. foreach ($scenes as &$scene) {
  9945. $scene_name = getProp($scene, 'scene');
  9946. $scene_description = getProp($scene, 'description');
  9947. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  9948. $scene_url = getProp($scene, 'url');
  9949. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  9950. if (isset($ref_products[$scene_name])) {
  9951. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  9952. if ($scene['url']) continue;
  9953. }
  9954. // 检查是否可以从上一集继承
  9955. $inherited = false;
  9956. if (!$is_force && !empty($prev_scenes)) {
  9957. foreach ($prev_scenes as $prev_scene) {
  9958. $prev_scene_name = getProp($prev_scene, 'scene');
  9959. $prev_description = getProp($prev_scene, 'description');
  9960. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  9961. $prev_url = getProp($prev_scene, 'url');
  9962. $prev_task_id = getProp($prev_scene, 'task_id');
  9963. $prev_task_status = getProp($prev_scene, 'task_status');
  9964. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  9965. if ($scene_name == $prev_scene_name
  9966. && $scene_description == $prev_description
  9967. && $scene_pic_prompt == $prev_pic_prompt
  9968. && !empty($prev_url)) {
  9969. $scene['task_id'] = $prev_task_id;
  9970. $scene['task_status'] = $prev_task_status;
  9971. $scene['url'] = $prev_url;
  9972. $inherited = true;
  9973. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  9974. 'anime_id' => $anime_id,
  9975. 'episode_number' => $episode_number,
  9976. 'task_id' => $prev_task_id,
  9977. 'url' => $prev_url
  9978. ]);
  9979. break;
  9980. }
  9981. }
  9982. }
  9983. // 如果已继承或已有url,跳过生成
  9984. if ($inherited || (!$is_force && $scene_url)) {
  9985. continue;
  9986. }
  9987. // 优先使用 pic_prompt,如果没有则使用 description
  9988. $pic_prompt = getProp($scene, 'pic_prompt');
  9989. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  9990. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  9991. $update_flag = true;
  9992. // 调用AIImageGenerationService的生成图片任务接口
  9993. try {
  9994. $params = [
  9995. 'prompt' => $description,
  9996. 'ref_img_urls' => []
  9997. ];
  9998. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9999. $task_id = $task->id;
  10000. if (!$task_id) {
  10001. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  10002. continue; // 不中断,继续处理其他场景
  10003. }
  10004. $scene['task_id'] = $task_id;
  10005. $scene['task_status'] = 'processing';
  10006. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  10007. 'anime_id' => $anime_id,
  10008. 'episode_number' => $episode_number,
  10009. 'task_id' => $task_id
  10010. ]);
  10011. } catch (\Exception $e) {
  10012. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  10013. // 不抛出异常,继续处理其他场景
  10014. }
  10015. }
  10016. // 处理道具图片生成(逻辑与场景一致)
  10017. foreach ($props as &$prop) {
  10018. $prop_name = getProp($prop, 'prop');
  10019. $prop_description = getProp($prop, 'description');
  10020. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  10021. $prop_url = getProp($prop, 'url');
  10022. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  10023. if (isset($ref_products[$prop_name])) {
  10024. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  10025. if ($prop['url']) continue;
  10026. }
  10027. // 检查是否可以从上一集继承
  10028. $inherited = false;
  10029. if (!$is_force && !empty($prev_props)) {
  10030. foreach ($prev_props as $prev_prop) {
  10031. $prev_prop_name = getProp($prev_prop, 'prop');
  10032. $prev_description = getProp($prev_prop, 'description');
  10033. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  10034. $prev_url = getProp($prev_prop, 'url');
  10035. $prev_task_id = getProp($prev_prop, 'task_id');
  10036. $prev_task_status = getProp($prev_prop, 'task_status');
  10037. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  10038. if ($prop_name == $prev_prop_name
  10039. && $prop_description == $prev_description
  10040. && $prop_pic_prompt == $prev_pic_prompt
  10041. && !empty($prev_url)) {
  10042. $prop['task_id'] = $prev_task_id;
  10043. $prop['task_status'] = $prev_task_status;
  10044. $prop['url'] = $prev_url;
  10045. $inherited = true;
  10046. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  10047. 'anime_id' => $anime_id,
  10048. 'episode_number' => $episode_number,
  10049. 'task_id' => $prev_task_id,
  10050. 'url' => $prev_url
  10051. ]);
  10052. break;
  10053. }
  10054. }
  10055. }
  10056. // 如果已继承或已有url,跳过生成
  10057. if ($inherited || (!$is_force && $prop_url)) {
  10058. continue;
  10059. }
  10060. // 优先使用 pic_prompt,如果没有则使用 description
  10061. $pic_prompt = getProp($prop, 'pic_prompt');
  10062. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  10063. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10064. $update_flag = true;
  10065. // 调用AIImageGenerationService的生成图片任务接口
  10066. try {
  10067. $params = [
  10068. 'prompt' => $description,
  10069. 'ref_img_urls' => []
  10070. ];
  10071. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10072. $task_id = $task->id;
  10073. if (!$task_id) {
  10074. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  10075. continue; // 不中断,继续处理其他道具
  10076. }
  10077. $prop['task_id'] = $task_id;
  10078. $prop['task_status'] = 'processing';
  10079. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  10080. 'anime_id' => $anime_id,
  10081. 'episode_number' => $episode_number,
  10082. 'task_id' => $task_id
  10083. ]);
  10084. } catch (\Exception $e) {
  10085. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  10086. // 不抛出异常,继续处理其他道具
  10087. }
  10088. }
  10089. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10090. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  10091. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  10092. // // 保存剧集的角色和场景信息
  10093. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10094. // 'roles' => json_encode($roles, 256),
  10095. // 'scenes' => json_encode($scenes, 256),
  10096. // 'generate_status' => '执行中',
  10097. // 'generate_at' => date('Y-m-d H:i:s'),
  10098. // 'updated_at' => date('Y-m-d H:i:s')
  10099. // ]);
  10100. // if (!$boolen) {
  10101. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  10102. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  10103. // }
  10104. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  10105. // 'episode_id' => $episode_id,
  10106. 'roles_count' => count($roles),
  10107. 'scenes_count' => count($scenes),
  10108. 'props_count' => count($props)
  10109. ]);
  10110. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10111. }
  10112. /**
  10113. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  10114. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  10115. *
  10116. * @param int $anime_id 动漫对话ID
  10117. * @param array $episode_roles 剧集角色数据
  10118. * @param array $episode_scenes 剧集场景数据
  10119. * @param array $episode_props 剧集道具数据
  10120. * @return bool
  10121. */
  10122. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  10123. // 获取全局数据
  10124. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10125. if (!$anime) {
  10126. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10127. return false;
  10128. }
  10129. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10130. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10131. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  10132. $roles_added = false;
  10133. $roles_updated = false;
  10134. $scenes_added = false;
  10135. $props_added = false;
  10136. // 处理角色同步
  10137. foreach ($episode_roles as $episode_role) {
  10138. $episode_role_name = getProp($episode_role, 'role');
  10139. $episode_description = getProp($episode_role, 'description');
  10140. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10141. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  10142. // 跳过旁白
  10143. if ($episode_role_name == '旁白') {
  10144. continue;
  10145. }
  10146. // 检查全局中是否已存在相同的角色
  10147. $exists = false;
  10148. $global_role_index = -1;
  10149. foreach ($global_roles as $index => $global_role) {
  10150. $global_role_name = getProp($global_role, 'role');
  10151. $global_description = getProp($global_role, 'description');
  10152. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10153. // 如果role、description、pic_prompt三项都一致,则认为已存在
  10154. if ($episode_role_name == $global_role_name
  10155. && $episode_description == $global_description
  10156. && $episode_pic_prompt == $global_pic_prompt) {
  10157. $exists = true;
  10158. $global_role_index = $index;
  10159. break;
  10160. }
  10161. }
  10162. // 如果不存在,则添加到全局
  10163. if (!$exists) {
  10164. $global_roles[] = $episode_role;
  10165. $roles_added = true;
  10166. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  10167. 'anime_id' => $anime_id,
  10168. 'role' => $episode_role_name
  10169. ]);
  10170. } else {
  10171. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  10172. if (!empty($episode_voice_prompt)) {
  10173. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  10174. // 如果全局没有voice_prompt或与剧集不一致,则更新
  10175. if ($global_voice_prompt !== $episode_voice_prompt) {
  10176. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  10177. $roles_updated = true;
  10178. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  10179. 'anime_id' => $anime_id,
  10180. 'role' => $episode_role_name,
  10181. 'voice_prompt' => $episode_voice_prompt
  10182. ]);
  10183. }
  10184. }
  10185. }
  10186. }
  10187. // 处理场景同步
  10188. foreach ($episode_scenes as $episode_scene) {
  10189. $episode_scene_name = getProp($episode_scene, 'scene');
  10190. $episode_description = getProp($episode_scene, 'description');
  10191. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10192. // 检查全局中是否已存在相同的场景
  10193. $exists = false;
  10194. foreach ($global_scenes as $global_scene) {
  10195. $global_scene_name = getProp($global_scene, 'scene');
  10196. $global_description = getProp($global_scene, 'description');
  10197. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10198. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  10199. if ($episode_scene_name == $global_scene_name
  10200. && $episode_description == $global_description
  10201. && $episode_pic_prompt == $global_pic_prompt) {
  10202. $exists = true;
  10203. break;
  10204. }
  10205. }
  10206. // 如果不存在,则添加到全局
  10207. if (!$exists) {
  10208. $global_scenes[] = $episode_scene;
  10209. $scenes_added = true;
  10210. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  10211. 'anime_id' => $anime_id,
  10212. 'scene' => $episode_scene_name
  10213. ]);
  10214. }
  10215. }
  10216. // 处理道具同步(逻辑与场景一致)
  10217. foreach ($episode_props as $episode_prop) {
  10218. $episode_prop_name = getProp($episode_prop, 'prop');
  10219. $episode_description = getProp($episode_prop, 'description');
  10220. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  10221. // 检查全局中是否已存在相同的道具
  10222. $exists = false;
  10223. foreach ($global_props as $global_prop) {
  10224. $global_prop_name = getProp($global_prop, 'prop');
  10225. $global_description = getProp($global_prop, 'description');
  10226. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  10227. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  10228. if ($episode_prop_name == $global_prop_name
  10229. && $episode_description == $global_description
  10230. && $episode_pic_prompt == $global_pic_prompt) {
  10231. $exists = true;
  10232. break;
  10233. }
  10234. }
  10235. // 如果不存在,则添加到全局
  10236. if (!$exists) {
  10237. $global_props[] = $episode_prop;
  10238. $props_added = true;
  10239. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  10240. 'anime_id' => $anime_id,
  10241. 'prop' => $episode_prop_name
  10242. ]);
  10243. }
  10244. }
  10245. // 如果有新增或更新,则更新全局数据
  10246. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  10247. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10248. if ($roles_added || $roles_updated) {
  10249. $update_data['roles'] = json_encode($global_roles, 256);
  10250. }
  10251. if ($scenes_added) {
  10252. $update_data['scenes'] = json_encode($global_scenes, 256);
  10253. }
  10254. if ($props_added) {
  10255. $update_data['props'] = json_encode($global_props, 256);
  10256. }
  10257. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  10258. dLog('deepseek')->info('剧集数据同步到全局完成', [
  10259. 'anime_id' => $anime_id,
  10260. 'roles_added' => $roles_added,
  10261. 'roles_updated' => $roles_updated,
  10262. 'scenes_added' => $scenes_added,
  10263. 'props_added' => $props_added,
  10264. 'global_roles_count' => count($global_roles),
  10265. 'global_scenes_count' => count($global_scenes),
  10266. 'global_props_count' => count($global_props)
  10267. ]);
  10268. }
  10269. return true;
  10270. }
  10271. /**
  10272. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  10273. *
  10274. * @param int $anime_id 动漫对话ID
  10275. * @param int $episode_id 分集ID
  10276. * @return bool
  10277. */
  10278. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  10279. // 获取全局角色和场景数据
  10280. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10281. if (!$anime) {
  10282. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10283. return false;
  10284. }
  10285. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10286. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10287. // 获取指定的分集
  10288. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  10289. if (!$episode) {
  10290. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  10291. return false;
  10292. }
  10293. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10294. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10295. $roles_updated = false;
  10296. $scenes_updated = false;
  10297. // 继承角色的task_id、task_status和url
  10298. foreach ($episode_roles as &$episode_role) {
  10299. $episode_role_name = getProp($episode_role, 'role');
  10300. $episode_description = getProp($episode_role, 'description');
  10301. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10302. $episode_url = getProp($episode_role, 'url');
  10303. // 跳过旁白角色
  10304. if ($episode_role_name == '旁白') {
  10305. continue;
  10306. }
  10307. // 如果剧集中已有URL,跳过
  10308. if (!empty($episode_url)) {
  10309. continue;
  10310. }
  10311. // 遍历全局角色数据,查找匹配的角色
  10312. foreach ($global_roles as $global_role) {
  10313. $global_role_name = getProp($global_role, 'role');
  10314. $global_description = getProp($global_role, 'description');
  10315. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10316. $global_url = getProp($global_role, 'url');
  10317. $global_task_id = getProp($global_role, 'task_id');
  10318. $global_task_status = getProp($global_role, 'task_status');
  10319. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10320. if ($episode_role_name == $global_role_name
  10321. && $episode_description == $global_description
  10322. && $episode_pic_prompt == $global_pic_prompt) {
  10323. // 继承 task_id、task_status 和 url
  10324. if (!empty($global_task_id)) {
  10325. $episode_role['task_id'] = $global_task_id;
  10326. $episode_role['task_status'] = $global_task_status;
  10327. $roles_updated = true;
  10328. dLog('deepseek')->info('剧集角色继承全局task_id', [
  10329. 'episode_id' => $episode_id,
  10330. 'role' => $episode_role_name,
  10331. 'task_id' => $global_task_id,
  10332. 'task_status' => $global_task_status
  10333. ]);
  10334. }
  10335. if (!empty($global_url)) {
  10336. $episode_role['url'] = $global_url;
  10337. $roles_updated = true;
  10338. dLog('deepseek')->info('剧集角色继承全局url', [
  10339. 'episode_id' => $episode_id,
  10340. 'role' => $episode_role_name,
  10341. 'url' => $global_url
  10342. ]);
  10343. }
  10344. break;
  10345. }
  10346. }
  10347. }
  10348. // 继承场景的task_id、task_status和url
  10349. foreach ($episode_scenes as &$episode_scene) {
  10350. $episode_scene_name = getProp($episode_scene, 'scene');
  10351. $episode_description = getProp($episode_scene, 'description');
  10352. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10353. $episode_url = getProp($episode_scene, 'url');
  10354. // 如果剧集中已有URL,跳过
  10355. if (!empty($episode_url)) {
  10356. continue;
  10357. }
  10358. // 遍历全局场景数据,查找匹配的场景
  10359. foreach ($global_scenes as $global_scene) {
  10360. $global_scene_name = getProp($global_scene, 'scene');
  10361. $global_description = getProp($global_scene, 'description');
  10362. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10363. $global_url = getProp($global_scene, 'url');
  10364. $global_task_id = getProp($global_scene, 'task_id');
  10365. $global_task_status = getProp($global_scene, 'task_status');
  10366. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10367. if ($episode_scene_name == $global_scene_name
  10368. && $episode_description == $global_description
  10369. && $episode_pic_prompt == $global_pic_prompt) {
  10370. // 继承 task_id、task_status 和 url
  10371. if (!empty($global_task_id)) {
  10372. $episode_scene['task_id'] = $global_task_id;
  10373. $episode_scene['task_status'] = $global_task_status;
  10374. $scenes_updated = true;
  10375. dLog('deepseek')->info('剧集场景继承全局task_id', [
  10376. 'episode_id' => $episode_id,
  10377. 'scene' => $episode_scene_name,
  10378. 'task_id' => $global_task_id,
  10379. 'task_status' => $global_task_status
  10380. ]);
  10381. }
  10382. if (!empty($global_url)) {
  10383. $episode_scene['url'] = $global_url;
  10384. $scenes_updated = true;
  10385. dLog('deepseek')->info('剧集场景继承全局url', [
  10386. 'episode_id' => $episode_id,
  10387. 'scene' => $episode_scene_name,
  10388. 'url' => $global_url
  10389. ]);
  10390. }
  10391. break;
  10392. }
  10393. }
  10394. }
  10395. // 如果有更新,则保存到数据库
  10396. if ($roles_updated || $scenes_updated) {
  10397. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10398. if ($roles_updated) {
  10399. $update_data['roles'] = json_encode($episode_roles, 256);
  10400. }
  10401. if ($scenes_updated) {
  10402. $update_data['scenes'] = json_encode($episode_scenes, 256);
  10403. }
  10404. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  10405. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  10406. 'episode_id' => $episode_id,
  10407. 'roles_updated' => $roles_updated,
  10408. 'scenes_updated' => $scenes_updated
  10409. ]);
  10410. }
  10411. return true;
  10412. }
  10413. public function chatChangeImg($data) {
  10414. $segment = getProp($data, 'segment');
  10415. $segment_content = getProp($segment, 'segment_content');
  10416. $prompt = getProp($data, 'prompt');
  10417. $ref_img = getProp($data, 'ref_img');
  10418. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  10419. // 处理文本模型
  10420. $model = getProp($data, 'model');
  10421. if (!$model) {
  10422. // 用户没有输入,从anime表获取
  10423. $segment_id = getProp($segment, 'segment_id');
  10424. if ($segment_id) {
  10425. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  10426. if ($episode_id) {
  10427. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  10428. if ($anime_id) {
  10429. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  10430. }
  10431. }
  10432. }
  10433. if (!$model) {
  10434. // anime表也没有,使用默认值
  10435. $model = 'doubao-seed-2-0-mini-260215';
  10436. }
  10437. }
  10438. // 验证模型是否在可用模型表中
  10439. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10440. $model = 'doubao-seed-2-0-mini-260215';
  10441. }
  10442. $messages[] =
  10443. [
  10444. 'role' => 'user',
  10445. 'content' => $question
  10446. ];
  10447. $post_data = [
  10448. 'model' => $model,
  10449. 'messages' => $messages,
  10450. // 'max_tokens' => 8192,
  10451. 'temperature' => 0.7,
  10452. 'frequency_penalty' => 0,
  10453. 'presence_penalty' => 0,
  10454. 'response_format' => ['type' => 'text'],
  10455. 'stream' => false // 是否启用流式输出
  10456. ];
  10457. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10458. // DeepSeek 官方模型使用 DeepSeek API
  10459. $chatResult = $this->chatOnly($post_data);
  10460. } else if (in_array($model, $this->gpt_text_models)) {
  10461. // GPT-5.4 模型使用 TokenRouter API
  10462. $chatResult = $this->gpt54ChatOnly($post_data);
  10463. } else {
  10464. // 其他模型使用火山引擎API
  10465. $chatResult = $this->volcEngineChatCompletion($post_data);
  10466. }
  10467. if (is_array($chatResult)) {
  10468. extract($chatResult);
  10469. }else {
  10470. Utils::throwError('20003: 接口调用失败!');
  10471. }
  10472. return [
  10473. 'type' => 'done',
  10474. // 'episode' => $episode,
  10475. 'answer' => $fullContent,
  10476. 'reasoning' => $fullReasoningContent,
  10477. 'usage' => $usage
  10478. ];
  10479. }
  10480. // 仅调用deepseek对话接口
  10481. private function chatOnly($post_data) {
  10482. $post_data['max_tokens'] = 300000;
  10483. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10484. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  10485. $response = $result->getBody()->getContents();
  10486. $response_arr = json_decode($response, true);
  10487. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  10488. $fullContent = '';
  10489. $fullReasoningContent = [];
  10490. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10491. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10492. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10493. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  10494. }
  10495. return [
  10496. 'fullContent' => $fullContent,
  10497. 'fullReasoningContent' => $fullReasoningContent,
  10498. 'usage' => $usage
  10499. ];
  10500. }
  10501. // 仅调用 GPT-5.4 对话接口(非流式)
  10502. private function gpt54ChatOnly($post_data) {
  10503. $apiKey = env('GPT_54_API_KEY');
  10504. if (empty($apiKey)) {
  10505. Utils::throwError('20003:GPT-5.4 API Key未配置');
  10506. }
  10507. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10508. $headers = [
  10509. 'Authorization' => 'Bearer ' . $apiKey,
  10510. 'Content-Type' => 'application/json'
  10511. ];
  10512. // 移除 thinking 参数,GPT-5.4 不支持
  10513. if (isset($post_data['thinking'])) {
  10514. unset($post_data['thinking']);
  10515. }
  10516. if (isset($post_data['reasoning_effort'])) {
  10517. unset($post_data['reasoning_effort']);
  10518. }
  10519. $post_data['max_completion_tokens'] = 100000;
  10520. // 确保 stream 为 false
  10521. $post_data['stream'] = false;
  10522. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  10523. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  10524. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  10525. 'json' => $post_data,
  10526. 'headers' => $headers
  10527. ]);
  10528. $response = $result->getBody()->getContents();
  10529. $response_arr = json_decode($response, true);
  10530. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  10531. $fullContent = '';
  10532. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10533. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10534. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10535. }
  10536. return [
  10537. 'fullContent' => $fullContent,
  10538. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  10539. 'usage' => $usage
  10540. ];
  10541. }
  10542. private function splitContent($content) {
  10543. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  10544. $chapters = [];
  10545. // 匹配章节标题格式:
  10546. // 1. 标题可能独占一行,也可能在正文末尾或中间
  10547. // 2. 格式支持:
  10548. // - **第一集**
  10549. // - 第一集:
  10550. // - ###第1章 重生
  10551. // - ##第2章 相救
  10552. // - 第三章 共处一室
  10553. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  10554. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  10555. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  10556. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  10557. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  10558. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  10559. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  10560. // 先在每个标题前插入换行符(如果前面不是换行的话)
  10561. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  10562. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  10563. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  10564. // 用正则找出所有章节标题的位置
  10565. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  10566. $titleCount = count($matches[0]);
  10567. for ($i = 0; $i < $titleCount; $i++) {
  10568. // 获取当前章节标题
  10569. $titleLine = trim($matches[0][$i][0]);
  10570. // 去除标题开头的特殊符号
  10571. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  10572. // 去除标题结尾的冒号和特殊符号
  10573. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  10574. $cleanTitle = trim($cleanTitle);
  10575. // 获取当前标题的结束位置
  10576. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  10577. // 获取下一个章节标题的开始位置(如果存在)
  10578. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  10579. // 提取章节内容(从标题结束到下一个标题开始)
  10580. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  10581. // 清理内容:去除前后空白和分隔线
  10582. $chapterContent = trim($chapterContent);
  10583. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  10584. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  10585. if (!empty($cleanTitle) && !empty($chapterContent)) {
  10586. $chapters[] = [
  10587. 'title' => $cleanTitle,
  10588. 'content' => $chapterContent
  10589. ];
  10590. }
  10591. }
  10592. } else {
  10593. // 如果没有匹配到章节,返回整个内容
  10594. $chapters[] = [
  10595. 'title' => '',
  10596. 'content' => $content
  10597. ];
  10598. }
  10599. return $chapters;
  10600. }
  10601. public function getContentByBid($bid) {
  10602. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  10603. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  10604. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  10605. $content = '';
  10606. foreach ($chapters as $chapter) {
  10607. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  10608. }
  10609. return $content;
  10610. }
  10611. public function getContentByScriptId($script_id) {
  10612. $content = '';
  10613. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  10614. if ($contents) {
  10615. $content = implode(PHP_EOL, $contents);
  10616. }else {
  10617. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  10618. }
  10619. return $content;
  10620. }
  10621. /**
  10622. * 根据文件类型提取文本内容
  10623. *
  10624. * @param mixed $file 文件对象或文件路径
  10625. * @return string
  10626. */
  10627. public function extractFileContent($file) {
  10628. // 获取文件路径和扩展名
  10629. if (is_string($file)) {
  10630. $filePath = $file;
  10631. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  10632. } else {
  10633. // Laravel UploadedFile 对象
  10634. $filePath = $file->getRealPath();
  10635. $extension = strtolower($file->getClientOriginalExtension());
  10636. }
  10637. $content = '';
  10638. switch ($extension) {
  10639. case 'txt':
  10640. $content = $this->extractTxtContent($filePath);
  10641. break;
  10642. case 'pdf':
  10643. $content = $this->extractPdfContent($filePath);
  10644. break;
  10645. case 'doc':
  10646. case 'docx':
  10647. $content = $this->extractWordContent($filePath);
  10648. break;
  10649. // case 'jpg':
  10650. // case 'jpeg':
  10651. // case 'png':
  10652. // case 'gif':
  10653. // case 'bmp':
  10654. // case 'webp':
  10655. // $content = $this->extractImageContent($filePath);
  10656. // break;
  10657. default:
  10658. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  10659. }
  10660. return $content;
  10661. }
  10662. /**
  10663. * 提取 TXT 文件内容
  10664. */
  10665. private function extractTxtContent($filePath) {
  10666. if (!file_exists($filePath)) {
  10667. Utils::throwError('20003:文件不存在');
  10668. }
  10669. $content = file_get_contents($filePath);
  10670. // 尝试检测并转换编码
  10671. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  10672. if ($encoding && $encoding !== 'UTF-8') {
  10673. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  10674. }
  10675. return trim($content);
  10676. }
  10677. /**
  10678. * 提取 PDF 文件内容
  10679. */
  10680. private function extractPdfContent($filePath) {
  10681. if (!file_exists($filePath)) {
  10682. Utils::throwError('20003:文件不存在');
  10683. }
  10684. try {
  10685. $parser = new PdfParser();
  10686. $pdf = $parser->parseFile($filePath);
  10687. $content = $pdf->getText();
  10688. return trim($content);
  10689. } catch (\Exception $e) {
  10690. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  10691. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  10692. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  10693. }
  10694. }
  10695. /**
  10696. * 提取 Word 文件内容(支持 doc 和 docx)
  10697. */
  10698. private function extractWordContent($filePath) {
  10699. if (!file_exists($filePath)) {
  10700. Utils::throwError('20003:文件不存在');
  10701. }
  10702. try {
  10703. $phpWord = WordIOFactory::load($filePath);
  10704. $content = '';
  10705. foreach ($phpWord->getSections() as $section) {
  10706. foreach ($section->getElements() as $element) {
  10707. $content .= $this->extractWordElementText($element);
  10708. }
  10709. }
  10710. return trim($content);
  10711. } catch (\Exception $e) {
  10712. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  10713. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  10714. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  10715. }
  10716. }
  10717. /**
  10718. * 递归提取 Word 元素中的文本
  10719. */
  10720. private function extractWordElementText($element) {
  10721. $text = '';
  10722. if (method_exists($element, 'getText')) {
  10723. $text .= $element->getText() . "\n";
  10724. } elseif (method_exists($element, 'getElements')) {
  10725. foreach ($element->getElements() as $childElement) {
  10726. $text .= $this->extractWordElementText($childElement);
  10727. }
  10728. }
  10729. return $text;
  10730. }
  10731. /**
  10732. * 提取图片内容(使用火山引擎 OCR)
  10733. */
  10734. private function extractImageContent($filePath) {
  10735. if (!file_exists($filePath)) {
  10736. Utils::throwError('20003:文件不存在');
  10737. }
  10738. try {
  10739. // 读取图片并转换为 base64
  10740. $imageData = file_get_contents($filePath);
  10741. $base64Image = base64_encode($imageData);
  10742. // 调用火山引擎 OCR 服务
  10743. $content = $this->callVolcEngineOCR($base64Image);
  10744. return trim($content);
  10745. } catch (\Exception $e) {
  10746. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  10747. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  10748. Utils::throwError('20003:图片识别失败');
  10749. }
  10750. }
  10751. /**
  10752. * 调用火山引擎 OCR 服务识别图片文字
  10753. *
  10754. * @param string $base64Image base64 编码的图片数据
  10755. * @return string 识别的文字内容
  10756. */
  10757. private function callVolcEngineOCR($base64Image) {
  10758. $method = 'POST';
  10759. $service = 'cv';
  10760. $host = 'visual.volcengineapi.com';
  10761. $region = env('VOLC_REGION', 'cn-north-1');
  10762. $access_key = env('VOLC_AK');
  10763. $secret_key = env('VOLC_SK');
  10764. $action = 'OCRNormal';
  10765. $version = '2020-08-26';
  10766. if (!$access_key || !$secret_key) {
  10767. Utils::throwError('20003:请配置火山引擎 AK/SK');
  10768. }
  10769. // 请求体
  10770. $body = json_encode([
  10771. 'image_base64' => $base64Image
  10772. ]);
  10773. // 生成签名
  10774. $headers = $this->getVolcEngineSignHeaders(
  10775. $method, $service, $host, $region,
  10776. "Action={$action}&Version={$version}",
  10777. $access_key, $secret_key, $body
  10778. );
  10779. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10780. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  10781. 'headers' => $headers,
  10782. 'body' => $body
  10783. ]);
  10784. $response_arr = json_decode($response->getBody()->getContents(), true);
  10785. // 提取识别的文字
  10786. $textLines = [];
  10787. if (isset($response_arr['data']['line_texts'])) {
  10788. $textLines = $response_arr['data']['line_texts'];
  10789. } elseif (isset($response_arr['data']['ocr_infos'])) {
  10790. foreach ($response_arr['data']['ocr_infos'] as $info) {
  10791. if (isset($info['text'])) {
  10792. $textLines[] = $info['text'];
  10793. }
  10794. }
  10795. }
  10796. if (empty($textLines)) {
  10797. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  10798. return '';
  10799. }
  10800. return implode("\n", $textLines);
  10801. }
  10802. /**
  10803. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  10804. */
  10805. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  10806. $contentType = 'application/json';
  10807. $accept = 'application/json';
  10808. // 获取当前UTC时间
  10809. $t = new DateTime('now', new DateTimeZone('UTC'));
  10810. $xDate = $t->format('Ymd\THis\Z');
  10811. $dateStamp = $t->format('Ymd');
  10812. // 计算 body 的 sha256 哈希
  10813. $payloadHash = hash('sha256', $body);
  10814. // 1. 拼接规范请求串
  10815. $canonicalUri = '/';
  10816. $canonicalQueryString = $queryString;
  10817. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  10818. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  10819. $canonicalRequest = implode("\n", [
  10820. $method,
  10821. $canonicalUri,
  10822. $canonicalQueryString,
  10823. $canonicalHeaders,
  10824. $signedHeaders,
  10825. $payloadHash
  10826. ]);
  10827. // 2. 拼接待签名字符串
  10828. $algorithm = 'HMAC-SHA256';
  10829. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  10830. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  10831. $stringToSign = implode("\n", [
  10832. $algorithm,
  10833. $xDate,
  10834. $credentialScope,
  10835. $hashedCanonicalRequest
  10836. ]);
  10837. // 3. 计算签名
  10838. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  10839. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  10840. // 4. 添加签名到请求头
  10841. $authorizationHeader = sprintf(
  10842. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  10843. $algorithm,
  10844. $access_key,
  10845. $credentialScope,
  10846. $signedHeaders,
  10847. $signature
  10848. );
  10849. return [
  10850. 'Accept' => $accept,
  10851. 'Content-Type' => $contentType,
  10852. 'Host' => $host,
  10853. 'X-Date' => $xDate,
  10854. 'X-Content-Sha256'=> $payloadHash,
  10855. 'Authorization' => $authorizationHeader
  10856. ];
  10857. }
  10858. public function generateScriptWords($cid, $model = 'r1') {
  10859. ini_set('max_execution_time', 0);
  10860. if (!$cid) Utils::throwError('20003: 请选择章节!');
  10861. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  10862. // 模型兼容性处理和思考模式设置
  10863. $thinkingMode = 'disabled';
  10864. $reasoningEffort = 'high';
  10865. if ($model == 'r1') {
  10866. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  10867. $thinkingMode = 'enabled';
  10868. } else {
  10869. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  10870. $thinkingMode = 'disabled';
  10871. }
  10872. $messages = [
  10873. [
  10874. 'role' => 'system',
  10875. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  10876. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  10877. 2.非对话部分请全部用旁白角色代替
  10878. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  10879. ],
  10880. [
  10881. 'role' => 'user',
  10882. 'content' => $content
  10883. ]
  10884. ];
  10885. $post_data = [
  10886. 'model' => $model,
  10887. 'messages' => $messages,
  10888. // 'max_tokens' => 8192,
  10889. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  10890. 'frequency_penalty' => 0,
  10891. 'presence_penalty' => 0,
  10892. 'thinking' => ['type' => $thinkingMode],
  10893. 'response_format' => [
  10894. 'type' => 'text'
  10895. ],
  10896. 'stream' => false
  10897. ];
  10898. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  10899. // 根据模型类型选择调用方法
  10900. $fullContent = '';
  10901. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10902. // DeepSeek 官方模型使用 DeepSeek API
  10903. $chatResult = $this->chatOnly($post_data);
  10904. } else if (in_array($model, $this->gpt_text_models)) {
  10905. // GPT-5.4 模型使用 TokenRouter API
  10906. $chatResult = $this->gpt54ChatOnly($post_data);
  10907. } else {
  10908. // 其他模型使用火山引擎API
  10909. $chatResult = $this->volcEngineChatCompletion($post_data);
  10910. }
  10911. if (is_array($chatResult)) {
  10912. $fullContent = $chatResult['fullContent'];
  10913. }
  10914. return $fullContent;
  10915. }
  10916. /**
  10917. * 智能化解析集数信息
  10918. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  10919. *
  10920. * @param string $prompt 用户输入的提示词
  10921. * @return int|null 解析出的集数,如果没有找到则返回null
  10922. */
  10923. private function extractEpisodeNumber($prompt)
  10924. {
  10925. if (empty($prompt)) {
  10926. return null;
  10927. }
  10928. // 定义各种可能的表达模式
  10929. $patterns = [
  10930. // 基本模式:改成N集、调整成N集、修改成N集
  10931. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  10932. // 扩展模式:分成N集、拆分成N集、分割成N集
  10933. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  10934. // 数量模式:N集、共N集、总共N集
  10935. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  10936. // 制作模式:制作N集、生成N集、创建N集
  10937. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  10938. // 计划模式:计划N集、预计N集、打算N集
  10939. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  10940. // 需要模式:需要N集、要N集
  10941. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  10942. // 中文数字模式:改成三集、调整成五集等
  10943. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  10944. // 英文数字模式
  10945. '/(?: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',
  10946. ];
  10947. // 中文数字转阿拉伯数字的映射
  10948. $chineseNumbers = [
  10949. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  10950. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  10951. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  10952. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  10953. ];
  10954. // 逐个尝试匹配模式
  10955. foreach ($patterns as $pattern) {
  10956. if (preg_match($pattern, $prompt, $matches)) {
  10957. $number = trim($matches[1]);
  10958. // 如果是中文数字,转换为阿拉伯数字
  10959. if (isset($chineseNumbers[$number])) {
  10960. return $chineseNumbers[$number];
  10961. }
  10962. // 如果是阿拉伯数字,直接返回
  10963. if (is_numeric($number)) {
  10964. $episodeNum = intval($number);
  10965. // 合理性检查:集数应该在1-100之间
  10966. if ($episodeNum >= 1 && $episodeNum <= 100) {
  10967. return $episodeNum;
  10968. }
  10969. }
  10970. }
  10971. }
  10972. return null;
  10973. }
  10974. /**
  10975. * 调用火山引擎对话(Chat) API
  10976. *
  10977. * @param array $params 包含以下参数:
  10978. * - model: 模型ID(必填)
  10979. * - messages: 消息列表(必填)
  10980. * - stream: 是否流式输出(可选,默认false)
  10981. * - max_tokens: 最大输出token数(可选)
  10982. * - temperature: 采样温度(可选,默认1)
  10983. * - top_p: 核采样概率(可选,默认0.7)
  10984. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  10985. * - presence_penalty: 存在惩罚系数(可选,默认0)
  10986. * - stop: 停止词(可选)
  10987. * - tools: 工具列表(可选)
  10988. * @return array|Generator 非流式返回数组,流式返回生成器
  10989. */
  10990. public function volcEngineChatCompletion(array $params)
  10991. {
  10992. $apiKey = env('VOLC_AI_API_KEY');
  10993. if (empty($apiKey)) {
  10994. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  10995. }
  10996. // 构建请求参数
  10997. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  10998. $requestData = [
  10999. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  11000. 'messages' => $params['messages'] ?? [],
  11001. ];
  11002. if (!in_array($originalModel, $this->valid_text_models)) {
  11003. Utils::throwError('20003:该模型不支持!');
  11004. }
  11005. // 添加可选参数
  11006. if (isset($params['stream'])) {
  11007. $requestData['stream'] = $params['stream'];
  11008. }
  11009. if (isset($params['stream_options'])) {
  11010. $requestData['stream_options'] = $params['stream_options'];
  11011. }
  11012. if (isset($params['max_tokens'])) {
  11013. $requestData['max_tokens'] = $params['max_tokens'];
  11014. }else if (isset($params['max_completion_tokens'])) {
  11015. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  11016. }else {
  11017. $requestData['max_completion_tokens'] = 100000;
  11018. }
  11019. if (isset($params['temperature'])) {
  11020. $requestData['temperature'] = $params['temperature'];
  11021. }
  11022. if (isset($params['top_p'])) {
  11023. $requestData['top_p'] = $params['top_p'];
  11024. }
  11025. if (isset($params['frequency_penalty'])) {
  11026. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  11027. }
  11028. if (isset($params['presence_penalty'])) {
  11029. $requestData['presence_penalty'] = $params['presence_penalty'];
  11030. }
  11031. if (isset($params['stop'])) {
  11032. $requestData['stop'] = $params['stop'];
  11033. }
  11034. if (isset($params['tools'])) {
  11035. $requestData['tools'] = $params['tools'];
  11036. }
  11037. if (isset($params['tool_choice'])) {
  11038. $requestData['tool_choice'] = $params['tool_choice'];
  11039. }
  11040. if (isset($params['response_format'])) {
  11041. $requestData['response_format'] = $params['response_format'];
  11042. }
  11043. if (isset($params['thinking'])) {
  11044. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  11045. if (is_array($params['thinking'])) {
  11046. $requestData['thinking'] = $params['thinking'];
  11047. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  11048. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11049. }
  11050. } else {
  11051. $requestData['thinking'] = ['type' => $params['thinking']];
  11052. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  11053. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11054. }
  11055. }
  11056. } else {
  11057. $requestData['thinking'] = ['type' => 'disabled'];
  11058. }
  11059. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  11060. $client = new Client(['verify' => false, 'timeout' => 1800]);
  11061. try {
  11062. // 判断是否为流式输出
  11063. $isStream = isset($params['stream']) && $params['stream'] === true;
  11064. if ($isStream) {
  11065. // 流式输出
  11066. // 流式请求默认声明返回 usage(未显式传参时)
  11067. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  11068. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  11069. } else {
  11070. // 非流式输出
  11071. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11072. 'headers' => [
  11073. 'Authorization' => 'Bearer ' . $apiKey,
  11074. 'Content-Type' => 'application/json',
  11075. ],
  11076. 'json' => $requestData
  11077. ]);
  11078. $responseData = json_decode($response->getBody(), true);
  11079. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  11080. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  11081. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  11082. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  11083. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  11084. }
  11085. return [
  11086. 'fullContent' => $fullContent,
  11087. 'fullReasoningContent' => $fullReasoningContent,
  11088. 'usage' => $usage
  11089. ];
  11090. }
  11091. } catch (\Exception $e) {
  11092. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  11093. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  11094. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  11095. }
  11096. }
  11097. /**
  11098. * 火山引擎对话API流式输出
  11099. *
  11100. * @param Client $client HTTP客户端
  11101. * @param string $apiKey API密钥
  11102. * @param array $requestData 请求数据
  11103. * @return Generator
  11104. */
  11105. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  11106. {
  11107. try {
  11108. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11109. 'headers' => [
  11110. 'Authorization' => 'Bearer ' . $apiKey,
  11111. 'Content-Type' => 'application/json',
  11112. ],
  11113. 'json' => $requestData,
  11114. 'stream' => true
  11115. ]);
  11116. $body = $response->getBody();
  11117. $buffer = '';
  11118. $fullContent = '';
  11119. $fullReasoningContent = '';
  11120. $usage = [];
  11121. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  11122. // 逐行读取流式响应
  11123. while (!$body->eof()) {
  11124. $chunk = $body->read(1024);
  11125. $buffer .= $chunk;
  11126. // 按行分割
  11127. $lines = explode("\n", $buffer);
  11128. $buffer = array_pop($lines);
  11129. foreach ($lines as $line) {
  11130. $line = trim($line);
  11131. if (empty($line)) {
  11132. continue;
  11133. }
  11134. // 检查是否是SSE数据行
  11135. if (strpos($line, 'data: ') !== 0) {
  11136. continue;
  11137. }
  11138. $data = substr($line, 6);
  11139. if ($data === '[DONE]') {
  11140. dLog('deepseek')->info('收到结束标记');
  11141. break 2;
  11142. }
  11143. try {
  11144. $json = json_decode($data, true);
  11145. if (json_last_error() !== JSON_ERROR_NONE) {
  11146. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  11147. continue;
  11148. }
  11149. if (isset($json['choices'][0]['delta'])) {
  11150. $delta = $json['choices'][0]['delta'];
  11151. // 处理思维链内容
  11152. if (isset($delta['reasoning_content'])) {
  11153. $fullReasoningContent .= $delta['reasoning_content'];
  11154. yield [
  11155. 'type' => 'reasoning',
  11156. 'content' => $delta['reasoning_content'],
  11157. 'full_reasoning' => $fullReasoningContent
  11158. ];
  11159. }
  11160. // 处理回答内容
  11161. if (isset($delta['content'])) {
  11162. $fullContent .= $delta['content'];
  11163. yield [
  11164. 'type' => 'content',
  11165. 'content' => $delta['content'],
  11166. ];
  11167. }
  11168. }
  11169. // 获取使用统计信息
  11170. if (isset($json['usage'])) {
  11171. $usage = $json['usage'];
  11172. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  11173. }
  11174. } catch (\Exception $e) {
  11175. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  11176. continue;
  11177. }
  11178. }
  11179. }
  11180. dLog('deepseek')->info('流式读取完成', [
  11181. 'content_length' => strlen($fullContent),
  11182. 'reasoning_length' => strlen($fullReasoningContent)
  11183. ]);
  11184. yield [
  11185. 'type' => 'done',
  11186. 'full_content' => $fullContent,
  11187. 'full_reasoning' => $fullReasoningContent,
  11188. 'usage' => $usage
  11189. ];
  11190. } catch (\Exception $e) {
  11191. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  11192. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  11193. throw $e;
  11194. }
  11195. }
  11196. /**
  11197. * 检查并创建图片生成任务
  11198. *
  11199. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  11200. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  11201. * @param string $nameKey 资源名称字段('role' 或 'scene')
  11202. * @param string $art_style 美术风格
  11203. * @return array 更新后的资源列表
  11204. */
  11205. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  11206. {
  11207. // 确保参数为数组
  11208. $merged_items = is_array($merged_items) ? $merged_items : [];
  11209. $global_items = is_array($global_items) ? $global_items : [];
  11210. // 构建全局资源映射表,用于快速查找
  11211. $global_map = [];
  11212. foreach ($global_items as $item) {
  11213. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  11214. if ($itemKey === '') {
  11215. continue;
  11216. }
  11217. $global_map[$itemKey] = $item;
  11218. }
  11219. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  11220. foreach ($merged_items as &$item) {
  11221. $item_name = getProp($item, $nameKey);
  11222. $item_description = getProp($item, 'description');
  11223. // $item_url = getProp($item, 'url');
  11224. // // 如果已有图片URL,跳过
  11225. // if (!empty($item_url)) {
  11226. // continue;
  11227. // }
  11228. // 如果是旁白角色,跳过
  11229. if ($nameKey === 'role' && $item_name === '旁白') {
  11230. continue;
  11231. }
  11232. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  11233. if ($itemKey === '') {
  11234. continue;
  11235. }
  11236. $need_create_task = false;
  11237. // 条件1:在全局资源中找不到匹配的名称
  11238. if (!isset($global_map[$itemKey])) {
  11239. $need_create_task = true;
  11240. } else {
  11241. // 条件2:名称匹配但描述或 pic_prompt 不一致
  11242. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  11243. $current_description = trim((string)$item_description);
  11244. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  11245. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  11246. // 如果 description 或 pic_prompt 有变化,需要重新生成
  11247. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  11248. $need_create_task = true;
  11249. }
  11250. }
  11251. // 如果需要创建任务,调用图片生成服务
  11252. if ($need_create_task) {
  11253. try {
  11254. // 优先使用 pic_prompt,如果没有则使用 description
  11255. $pic_prompt = getProp($item, 'pic_prompt');
  11256. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  11257. // 添加美术风格前缀
  11258. if ($art_style) {
  11259. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  11260. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  11261. $description = "{$prefix}:{$description}";
  11262. }
  11263. $params = [
  11264. 'prompt' => $description,
  11265. 'ref_img_urls' => []
  11266. ];
  11267. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11268. $task_id = $task->id;
  11269. if ($task_id) {
  11270. $item['task_id'] = $task_id;
  11271. $item['task_status'] = 'processing';
  11272. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11273. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  11274. }
  11275. } catch (\Exception $e) {
  11276. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11277. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  11278. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  11279. // 不抛出异常,继续处理其他资源
  11280. }
  11281. }
  11282. }
  11283. return $merged_items;
  11284. }
  11285. /**
  11286. * 同步新出现的主体和场景到全局
  11287. *
  11288. * @param int $anime_id 动漫ID
  11289. * @param array $merged_roles 合并后的角色列表
  11290. * @param array $merged_scenes 合并后的场景列表
  11291. * @param array $global_roles 全局角色列表
  11292. * @param array $global_scenes 全局场景列表
  11293. * @return void
  11294. */
  11295. private function syncNewResourcesToGlobal(
  11296. int $anime_id,
  11297. array $merged_roles,
  11298. array $merged_scenes,
  11299. array $global_roles,
  11300. array $global_scenes
  11301. ): void {
  11302. // 构建全局角色映射表
  11303. $global_role_map = [];
  11304. foreach ($global_roles as $role) {
  11305. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  11306. if ($roleKey !== '') {
  11307. $global_role_map[$roleKey] = $role;
  11308. }
  11309. }
  11310. // 构建全局场景映射表
  11311. $global_scene_map = [];
  11312. foreach ($global_scenes as $scene) {
  11313. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  11314. if ($sceneKey !== '') {
  11315. $global_scene_map[$sceneKey] = $scene;
  11316. }
  11317. }
  11318. $need_update = false;
  11319. $new_global_roles = $global_roles;
  11320. $new_global_scenes = $global_scenes;
  11321. // 检查并添加新角色到全局
  11322. foreach ($merged_roles as $role) {
  11323. $role_name = getProp($role, 'role');
  11324. // 跳过旁白
  11325. if ($role_name === '旁白') {
  11326. continue;
  11327. }
  11328. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  11329. if ($roleKey === '') {
  11330. continue;
  11331. }
  11332. // 如果全局中不存在该角色,添加到全局
  11333. if (!isset($global_role_map[$roleKey])) {
  11334. $new_global_roles[] = [
  11335. 'role' => $role_name,
  11336. 'description' => getProp($role, 'description', ''),
  11337. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  11338. 'voice_name' => getProp($role, 'voice_name', ''),
  11339. 'voice_type' => getProp($role, 'voice_type', ''),
  11340. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  11341. 'url' => getProp($role, 'url', ''),
  11342. 'task_id' => getProp($role, 'task_id', ''),
  11343. 'task_status' => getProp($role, 'task_status', ''),
  11344. ];
  11345. $global_role_map[$roleKey] = true; // 标记已添加
  11346. $need_update = true;
  11347. dLog('deepseek')->info("新角色同步到全局", [
  11348. 'anime_id' => $anime_id,
  11349. 'role' => $role_name,
  11350. 'task_id' => getProp($role, 'task_id', ''),
  11351. ]);
  11352. }
  11353. // else {
  11354. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11355. // $global_role = $global_role_map[$roleKey];
  11356. // if (is_array($global_role)) {
  11357. // $updated = false;
  11358. // $update_fields = [];
  11359. // // 检查描述是否更新
  11360. // $current_description = trim((string)getProp($role, 'description'));
  11361. // $global_description = trim((string)getProp($global_role, 'description'));
  11362. // if ($current_description !== '' && $current_description !== $global_description) {
  11363. // $updated = true;
  11364. // $update_fields[] = 'description';
  11365. // }
  11366. // // 检查pic_prompt是否更新
  11367. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  11368. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  11369. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11370. // $updated = true;
  11371. // $update_fields[] = 'pic_prompt';
  11372. // }
  11373. // // 检查图片任务信息是否更新
  11374. // $current_task_id = getProp($role, 'task_id');
  11375. // $global_task_id = getProp($global_role, 'task_id');
  11376. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11377. // $updated = true;
  11378. // $update_fields[] = 'task_id';
  11379. // }
  11380. // // 如果有更新,同步到全局
  11381. // if ($updated) {
  11382. // foreach ($new_global_roles as &$global_role_item) {
  11383. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  11384. // if ($global_role_key === $roleKey) {
  11385. // if (in_array('description', $update_fields)) {
  11386. // $global_role_item['description'] = $current_description;
  11387. // }
  11388. // if (in_array('pic_prompt', $update_fields)) {
  11389. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  11390. // }
  11391. // if (in_array('task_id', $update_fields)) {
  11392. // $global_role_item['task_id'] = $current_task_id;
  11393. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  11394. // $global_role_item['url'] = getProp($role, 'url', '');
  11395. // }
  11396. // break;
  11397. // }
  11398. // }
  11399. // $need_update = true;
  11400. // dLog('deepseek')->info("角色信息更新到全局", [
  11401. // 'anime_id' => $anime_id,
  11402. // 'role' => $role_name,
  11403. // 'update_fields' => implode(',', $update_fields),
  11404. // ]);
  11405. // }
  11406. // }
  11407. // }
  11408. }
  11409. // 检查并添加新场景到全局
  11410. foreach ($merged_scenes as $scene) {
  11411. $scene_name = getProp($scene, 'scene');
  11412. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  11413. if ($sceneKey === '') {
  11414. continue;
  11415. }
  11416. // 如果全局中不存在该场景,添加到全局
  11417. if (!isset($global_scene_map[$sceneKey])) {
  11418. $new_global_scenes[] = [
  11419. 'scene' => $scene_name,
  11420. 'description' => getProp($scene, 'description', ''),
  11421. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  11422. 'url' => getProp($scene, 'url', ''),
  11423. 'task_id' => getProp($scene, 'task_id', ''),
  11424. 'task_status' => getProp($scene, 'task_status', ''),
  11425. ];
  11426. $global_scene_map[$sceneKey] = true; // 标记已添加
  11427. $need_update = true;
  11428. dLog('deepseek')->info("新场景同步到全局", [
  11429. 'anime_id' => $anime_id,
  11430. 'scene' => $scene_name,
  11431. 'task_id' => getProp($scene, 'task_id', ''),
  11432. ]);
  11433. }
  11434. // else {
  11435. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11436. // $global_scene = $global_scene_map[$sceneKey];
  11437. // if (is_array($global_scene)) {
  11438. // $updated = false;
  11439. // $update_fields = [];
  11440. // // 检查描述是否更新
  11441. // $current_description = trim((string)getProp($scene, 'description'));
  11442. // $global_description = trim((string)getProp($global_scene, 'description'));
  11443. // if ($current_description !== '' && $current_description !== $global_description) {
  11444. // $updated = true;
  11445. // $update_fields[] = 'description';
  11446. // }
  11447. // // 检查pic_prompt是否更新
  11448. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  11449. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  11450. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11451. // $updated = true;
  11452. // $update_fields[] = 'pic_prompt';
  11453. // }
  11454. // // 检查图片任务信息是否更新
  11455. // $current_task_id = getProp($scene, 'task_id');
  11456. // $global_task_id = getProp($global_scene, 'task_id');
  11457. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11458. // $updated = true;
  11459. // $update_fields[] = 'task_id';
  11460. // }
  11461. // // 如果有更新,同步到全局
  11462. // if ($updated) {
  11463. // foreach ($new_global_scenes as &$global_scene_item) {
  11464. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  11465. // if ($global_scene_key === $sceneKey) {
  11466. // if (in_array('description', $update_fields)) {
  11467. // $global_scene_item['description'] = $current_description;
  11468. // }
  11469. // if (in_array('pic_prompt', $update_fields)) {
  11470. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  11471. // }
  11472. // if (in_array('task_id', $update_fields)) {
  11473. // $global_scene_item['task_id'] = $current_task_id;
  11474. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  11475. // $global_scene_item['url'] = getProp($scene, 'url', '');
  11476. // }
  11477. // break;
  11478. // }
  11479. // }
  11480. // $need_update = true;
  11481. // dLog('deepseek')->info("场景信息更新到全局", [
  11482. // 'anime_id' => $anime_id,
  11483. // 'scene' => $scene_name,
  11484. // 'update_fields' => implode(',', $update_fields),
  11485. // ]);
  11486. // }
  11487. // }
  11488. // }
  11489. }
  11490. // 如果有新增或更新,更新数据库
  11491. if ($need_update) {
  11492. $update_data = [
  11493. 'roles' => json_encode($new_global_roles, 256),
  11494. 'scenes' => json_encode($new_global_scenes, 256),
  11495. 'updated_at' => date('Y-m-d H:i:s'),
  11496. ];
  11497. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  11498. if ($result !== false) {
  11499. dLog('deepseek')->info("全局角色和场景更新成功", [
  11500. 'anime_id' => $anime_id,
  11501. 'roles_count' => count($new_global_roles),
  11502. 'scenes_count' => count($new_global_scenes),
  11503. ]);
  11504. } else {
  11505. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  11506. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  11507. }
  11508. }
  11509. }
  11510. }