DeepSeekService.php 723 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013
  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. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  310. $originalContent = '';
  311. if ($script_id > 0) {
  312. $script = DB::table('mp_scripts')
  313. ->where('id', $script_id)
  314. ->where('is_deleted', 0)
  315. ->first();
  316. if (!$script) {
  317. Utils::throwError('20003:剧本不存在或已删除');
  318. }
  319. $originalContent = $script->content ?? '';
  320. if (empty($originalContent)) {
  321. Utils::throwError('20003:剧本内容为空');
  322. }
  323. // 将剧本内容添加到提示词前面
  324. if (!empty($originalContent)) {
  325. if (!empty($prompt)) {
  326. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  327. } else {
  328. $prompt = "原文内容:\n" . $originalContent;
  329. }
  330. }
  331. }
  332. // 新增: 如果提供了template_id,从数据库获取template_prompt
  333. if ($templateId > 0) {
  334. $template = DB::table('mp_prompt_templates')
  335. ->where('id', $templateId)
  336. ->where('is_deleted', 0)
  337. ->first();
  338. if (!$template) {
  339. Utils::throwError('20003:模板不存在或已删除');
  340. }
  341. $templatePrompt = $template->template_prompt ?? '';
  342. // 将模板提示词和用户输入的prompt组合
  343. // 模板为准,用户输入作为补充要求
  344. if (!empty($templatePrompt)) {
  345. if (!empty($prompt)) {
  346. $prompt = $templatePrompt . "\n\n" . $prompt;
  347. } else {
  348. $prompt = $templatePrompt;
  349. }
  350. }
  351. }
  352. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  353. if (empty($messages)) {
  354. $messages = [];
  355. // 添加系统提示词
  356. if (!empty($systemPrompt)) {
  357. $messages[] = [
  358. 'role' => 'system',
  359. 'content' => $systemPrompt
  360. ];
  361. }
  362. // 构建用户消息内容(支持文本+图片)
  363. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  364. $userMessage = [
  365. 'role' => 'user',
  366. 'content' => []
  367. ];
  368. // 添加文本内容
  369. if (!empty($prompt)) {
  370. $userMessage['content'][] = [
  371. 'type' => 'text',
  372. 'text' => $prompt
  373. ];
  374. }
  375. // 处理上传的图片文件
  376. if (!empty($images)) {
  377. if (!is_array($images)) {
  378. $images = [$images];
  379. }
  380. foreach ($images as $image) {
  381. $imageBase64 = $this->processImageToBase64($image);
  382. if ($imageBase64) {
  383. $userMessage['content'][] = [
  384. 'type' => 'image_url',
  385. 'image_url' => [
  386. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  387. ]
  388. ];
  389. }
  390. }
  391. }
  392. // 处理图片URL
  393. if (!empty($imageUrls)) {
  394. if (!is_array($imageUrls)) {
  395. $imageUrls = [$imageUrls];
  396. }
  397. foreach ($imageUrls as $url) {
  398. if (!empty($url)) {
  399. $userMessage['content'][] = [
  400. 'type' => 'image_url',
  401. 'image_url' => [
  402. 'url' => $url
  403. ]
  404. ];
  405. }
  406. }
  407. }
  408. // 如果只有文本内容,简化为字符串格式
  409. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  410. $userMessage['content'] = $userMessage['content'][0]['text'];
  411. }
  412. $messages[] = $userMessage;
  413. }
  414. }
  415. // 验证messages不为空
  416. if (empty($messages)) {
  417. Utils::throwError('20003:请提供有效的对话内容');
  418. }
  419. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  420. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  421. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  422. if ($model === 'deepseek-chat') {
  423. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  424. $model = 'deepseek-v4-flash';
  425. $thinkingMode = 'disabled';
  426. } elseif ($model === 'deepseek-reasoner') {
  427. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  428. $model = 'deepseek-v4-flash';
  429. $thinkingMode = 'enabled';
  430. }
  431. // 构建请求参数(非流式)
  432. $post_data = [
  433. 'model' => $model,
  434. 'messages' => $messages,
  435. 'temperature' => getProp($data, 'temperature', 1),
  436. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  437. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  438. 'thinking' => ['type' => $thinkingMode],
  439. 'stream' => false // 非流式输出
  440. ];
  441. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  442. // 添加可选参数
  443. if (isset($data['top_p'])) {
  444. $post_data['top_p'] = $data['top_p'];
  445. }
  446. // 新增: 根据response_format设置响应格式
  447. if ($responseFormat === 'json') {
  448. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  449. $hasJsonKeyword = false;
  450. foreach ($post_data['messages'] as $message) {
  451. if (isset($message['content'])) {
  452. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  453. if (stripos($content, 'json') !== false) {
  454. $hasJsonKeyword = true;
  455. break;
  456. }
  457. }
  458. }
  459. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  460. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  461. if (!$hasJsonKeyword) {
  462. $lastMessageIndex = count($post_data['messages']) - 1;
  463. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  464. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  465. // 如果content是字符串,直接追加
  466. if (is_string($lastContent)) {
  467. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  468. }
  469. // 如果content是数组(包含文本和图片),在文本部分追加
  470. else if (is_array($lastContent)) {
  471. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  472. if ($contentPart['type'] === 'text') {
  473. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  474. break;
  475. }
  476. }
  477. }
  478. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  479. }
  480. }
  481. // 设置response_format参数(所有支持的模型)
  482. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  483. // DeepSeek模型
  484. $post_data['response_format'] = ['type' => 'json_object'];
  485. } else if (in_array($model, $this->gpt_text_models)) {
  486. // GPT模型
  487. $post_data['response_format'] = ['type' => 'json_object'];
  488. } else if (in_array($model, $this->valid_text_models)) {
  489. // 火山引擎模型
  490. $post_data['response_format'] = ['type' => 'json_object'];
  491. }
  492. }
  493. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  494. $aiResult = null;
  495. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  496. // DeepSeek 官方模型使用现有的 chatOnly 方法
  497. $result = $this->chatOnly($post_data);
  498. // 记录实际使用的模型
  499. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  500. $aiResult = [
  501. 'content' => $result['fullContent'],
  502. 'reasoning_content' => $result['fullReasoningContent'],
  503. 'usage' => $result['usage'],
  504. 'model' => $model,
  505. 'finish_reason' => 'stop'
  506. ];
  507. } else if (in_array($model, $this->gpt_text_models)) {
  508. // GPT 模型使用现有的 gpt54ChatOnly 方法
  509. $result = $this->gpt54ChatOnly($post_data);
  510. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  511. $aiResult = [
  512. 'content' => $result['fullContent'],
  513. 'reasoning_content' => '',
  514. 'usage' => $result['usage'],
  515. 'model' => $model,
  516. 'finish_reason' => 'stop'
  517. ];
  518. } else if (in_array($model, $this->valid_text_models)) {
  519. // 火山引擎支持的模型使用火山引擎 API(非流式)
  520. $post_data['stream'] = false;
  521. $result = $this->volcEngineChatCompletion($post_data);
  522. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  523. 'requested_model' => $model,
  524. 'result_keys' => array_keys($result),
  525. 'has_fullContent' => isset($result['fullContent']),
  526. 'has_content' => isset($result['content'])
  527. ]);
  528. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  529. $aiResult = [
  530. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  531. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  532. 'usage' => $result['usage'] ?? [],
  533. 'model' => $model,
  534. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  535. ];
  536. } else {
  537. Utils::throwError('20003:不支持的模型: ' . $model);
  538. }
  539. // 新增: 如果提供了script_id,保存对话记录
  540. if ($script_id > 0 && $aiResult) {
  541. try {
  542. $uid = Site::getUid();
  543. $now = now();
  544. // 获取用户原始的prompt(不包含剧本内容)
  545. $originalPrompt = getProp($data, 'prompt', '');
  546. $recordsToInsert = [
  547. [
  548. 'uid' => $uid,
  549. 'script_id' => $script_id,
  550. 'sequence' => $sequence,
  551. 'role' => 'user',
  552. 'content' => $originalPrompt,
  553. 'created_at' => $now,
  554. 'updated_at' => $now,
  555. ],
  556. [
  557. 'uid' => $uid,
  558. 'script_id' => $script_id,
  559. 'sequence' => $sequence,
  560. 'role' => 'assistant',
  561. 'content' => $aiResult['content'],
  562. 'created_at' => $now,
  563. 'updated_at' => $now,
  564. ]
  565. ];
  566. DB::table('mp_script_records')->insert($recordsToInsert);
  567. // 获取刚插入的记录ID(假设按插入顺序返回)
  568. $insertedRecords = DB::table('mp_script_records')
  569. ->where('uid', $uid)
  570. ->where('script_id', $script_id)
  571. ->where('sequence', $sequence)
  572. ->orderBy('id', 'desc')
  573. ->limit(2)
  574. ->get()
  575. ->map(function ($record) {
  576. return [
  577. 'rid' => $record->id,
  578. 'script_id' => $record->script_id,
  579. 'sequence' => $record->sequence,
  580. 'role' => $record->role,
  581. 'content' => $record->content,
  582. 'created_at' => $record->created_at,
  583. ];
  584. })
  585. ->reverse()
  586. ->values()
  587. ->toArray();
  588. // 将记录信息添加到返回结果中
  589. $aiResult['records'] = $insertedRecords;
  590. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  591. } catch (\Exception $e) {
  592. // 记录错误但不影响主流程
  593. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  594. }
  595. }
  596. return $aiResult;
  597. }
  598. public function saveScriptChatHistory($data) {
  599. $uid = Site::getUid();
  600. $rid = getProp($data, 'rid');
  601. $script_id = getProp($data, 'script_id');
  602. $sequence = getProp($data, 'sequence', 0);
  603. $content = getProp($data, 'content');
  604. if (!$rid) {
  605. Utils::throwError('20003:请选择对话记录ID');
  606. }
  607. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  608. if (!$record) {
  609. Utils::throwError('20003:对话记录不存在');
  610. }
  611. if (!$script_id) {
  612. Utils::throwError('20003:请选择剧本');
  613. }
  614. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  615. if (!$script) {
  616. Utils::throwError('20003:剧本不存在');
  617. }
  618. // 批量插入数据
  619. return DB::table('mp_script_records')->where('id', $rid)->update([
  620. 'content' => $content,
  621. 'updated_at' => date('Y-m-d H:i:s')
  622. ]);
  623. }
  624. /**
  625. * 获取剧本的历史对话记录
  626. *
  627. * @param array $data 请求参数
  628. * @return array 返回历史记录数组
  629. */
  630. public function getScriptChatHistory($data) {
  631. $uid = Site::getUid();
  632. $script_id = getProp($data, 'script_id');
  633. $rid = getProp($data, 'rid');
  634. $sequence = getProp($data, 'sequence', null);
  635. if (!$script_id) {
  636. Utils::throwError('20003:请提供剧本ID');
  637. }
  638. // 验证剧本是否存在
  639. $script = DB::table('mp_scripts')
  640. ->where('id', $script_id)
  641. ->where('is_deleted', 0)
  642. ->first();
  643. if (!$script) {
  644. Utils::throwError('20003:剧本不存在');
  645. }
  646. // 构建查询
  647. $query = DB::table('mp_script_records')
  648. ->where('script_id', $script_id);
  649. // ->where('uid', $uid);
  650. // 如果提供了 sequence,则过滤指定剧集
  651. if ($sequence !== null) {
  652. $query->where('sequence', $sequence);
  653. }
  654. // 记录ID筛选
  655. if ($rid) {
  656. $query->where('id', $rid);
  657. }
  658. // 查询记录并按 id 正序排序
  659. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  660. ->orderBy('created_at', 'asc')
  661. ->orderBy('id', 'asc')
  662. ->get()
  663. ->map(function ($record) {
  664. return [
  665. 'rid' => $record->id,
  666. 'script_id' => $record->script_id,
  667. 'sequence' => $record->sequence,
  668. 'role' => $record->role,
  669. 'content' => $record->content,
  670. 'products' => $record->products ? json_decode($record->products) : [],
  671. 'created_at' => $record->created_at,
  672. ];
  673. })
  674. ->toArray();
  675. return $records;
  676. }
  677. /**
  678. * 处理图片转换为base64
  679. *
  680. * @param mixed $image 图片文件对象或文件路径
  681. * @return string|null base64编码的图片数据
  682. */
  683. private function processImageToBase64($image) {
  684. try {
  685. // 获取文件路径
  686. if (is_string($image)) {
  687. $filePath = $image;
  688. } else {
  689. // Laravel UploadedFile 对象
  690. $filePath = $image->getRealPath();
  691. }
  692. if (!file_exists($filePath)) {
  693. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  694. return null;
  695. }
  696. // 验证是否为图片文件
  697. $imageInfo = @getimagesize($filePath);
  698. if ($imageInfo === false) {
  699. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  700. return null;
  701. }
  702. // 读取图片并转换为base64
  703. $imageData = file_get_contents($filePath);
  704. $base64Image = base64_encode($imageData);
  705. dLog('deepseek')->info('图片转换成功', [
  706. 'size' => strlen($imageData),
  707. 'type' => $imageInfo['mime']
  708. ]);
  709. return $base64Image;
  710. } catch (\Exception $e) {
  711. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  712. return null;
  713. }
  714. }
  715. private function getArtStylePromptMappings($art_style='')
  716. {
  717. $arr = [
  718. '唯美真人风格' => [
  719. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  720. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  721. ],
  722. '真人古风风格' => [
  723. 'aliases' => ['真人古风风格', '真人古风'],
  724. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  725. ],
  726. '日系动漫风格' => [
  727. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  728. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  729. ],
  730. '国漫风格' => [
  731. 'aliases' => ['国漫风格', '国漫'],
  732. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  733. ],
  734. 'Q版卡通风格' => [
  735. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  736. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  737. ],
  738. '简约扁平风格' => [
  739. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  740. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  741. ],
  742. '武侠风格' => [
  743. 'aliases' => ['武侠风格', '武侠'],
  744. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  745. ],
  746. '古风仙侠风格' => [
  747. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  748. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  749. ],
  750. '新中式水墨风格' => [
  751. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  752. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  753. ],
  754. '写实插画风格' => [
  755. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  756. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  757. ],
  758. '3D卡通风格' => [
  759. 'aliases' => ['3D卡通风格', '3D卡通'],
  760. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  761. ],
  762. '条漫风格' => [
  763. 'aliases' => ['条漫风格', '条漫'],
  764. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  765. ],
  766. '赛博朋克风格' => [
  767. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  768. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  769. ],
  770. '暗黑悬疑风格' => [
  771. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  772. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  773. ],
  774. '治愈清新风格' => [
  775. 'aliases' => ['治愈清新风格', '治愈清新'],
  776. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  777. ],
  778. '3D真人风格' => [
  779. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  780. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  781. ],
  782. ];
  783. if($art_style) {
  784. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  785. }
  786. return $arr;
  787. $arr = [
  788. '唯美真人风格' => [
  789. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  790. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  791. 2. 色彩色调
  792. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  793. 3. 画质精度
  794. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  795. 4. 画面观感
  796. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  797. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  798. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  799. ],
  800. '真人古风风格' => [
  801. 'aliases' => ['真人古风风格', '真人古风'],
  802. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  803. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  804. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  805. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  806. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  807. ],
  808. '日系动漫风格' => [
  809. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  810. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  811. 正向提示词(中文)
  812. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  813. 必须遵守规则
  814. • 全程保持日系动漫风格,不混入其他画风
  815. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  816. • 画面适配所选画面比例,构图居中,主体突出
  817. • 线条干净、色彩统一,不杂乱、不突兀
  818. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  819. ],
  820. '国漫风格' => [
  821. 'aliases' => ['国漫风格', '国漫'],
  822. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  823. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  824. 必须遵守规则
  825. • 严格保持国漫画风,不串风格、不混画风
  826. • 角色形象统一,不随意改变五官、身材、服饰
  827. • 画面构图稳定,适合漫剧叙事展示
  828. • 色调统一,不出现脏色、杂色
  829. 禁止/避免词汇
  830. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  831. ],
  832. 'Q版卡通风格' => [
  833. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  834. 'prompt' => "风格说明
  835. 头大身小,造型可爱圆润,简约干净
  836. 正向提示词(中文)
  837. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  838. 必须遵守规则
  839. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  840. • 角色造型统一,表情可爱,不诡异
  841. • 画面简洁清爽,无多余复杂元素
  842. • 色彩明亮柔和,不刺眼
  843. 禁止/避免词汇
  844. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  845. ],
  846. '简约扁平风格' => [
  847. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  848. 'prompt' => "风格说明
  849. 色块简洁、无复杂渐变,现代极简风
  850. 正向提示词(中文)
  851. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  852. 必须遵守规则
  853. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  854. • 构图简洁,主体突出,无多余装饰
  855. • 色彩统一、干净,不杂乱
  856. 禁止/避免词汇
  857. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  858. ],
  859. '武侠风格' => [
  860. 'aliases' => ['武侠风格', '武侠'],
  861. 'prompt' => "风格说明
  862. 江湖气息,线条硬朗,动作感强
  863. 正向提示词(中文)
  864. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  865. 必须遵守规则
  866. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  867. • 角色形象、服饰、身材比例统一
  868. • 画面动作自然,不扭曲、不畸形
  869. 禁止/避免词汇
  870. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  871. ],
  872. '古风仙侠风格' => [
  873. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  874. 'prompt' => "风格说明
  875. 飘逸汉服、云雾仙气、唯美空灵
  876. 正向提示词(中文)
  877. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  878. 必须遵守规则
  879. • 保持古风仙侠统一画风,不混入现代、科幻元素
  880. • 角色服饰、发型、形象前后一致
  881. • 场景仙气飘逸,色调清雅统一
  882. • 画面唯美柔和,不阴暗、不诡异
  883. 禁止/避免词汇
  884. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  885. ],
  886. '新中式水墨风格' => [
  887. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  888. 'prompt' => "风格说明
  889. 淡墨渲染,毛笔笔触,留白意境
  890. 正向提示词(中文)
  891. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  892. 必须遵守规则
  893. • 严格保持水墨质感,不混入厚涂、写实、卡通
  894. • 色调淡雅统一,不浓艳杂乱
  895. • 画面干净有意境,不堆砌元素
  896. 禁止/避免词汇
  897. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  898. ],
  899. '写实插画风格' => [
  900. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  901. 'prompt' => "风格说明
  902. 接近真人比例,光影真实,质感细腻
  903. 正向提示词(中文)
  904. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  905. 必须遵守规则
  906. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  907. • 角色五官、身材、服饰高度统一
  908. • 画面清晰、光影自然、不扭曲
  909. 禁止/避免词汇
  910. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  911. ],
  912. '3D卡通风格' => [
  913. 'aliases' => ['3D卡通风格', '3D卡通'],
  914. 'prompt' => "风格说明
  915. 3D建模质感,柔和渲染,圆润可爱
  916. 正向提示词(中文)
  917. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  918. 必须遵守规则
  919. • 保持3D卡通统一质感,不出现2D杂乱线条
  920. • 角色模型、比例、形象前后一致
  921. • 画面干净,不模糊、不穿模
  922. 禁止/避免词汇
  923. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  924. ],
  925. '条漫风格' => [
  926. 'aliases' => ['条漫风格', '条漫'],
  927. 'prompt' => "风格说明
  928. 纵向分镜,上下滑动阅读,轻量化
  929. 正向提示词(中文)
  930. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  931. 必须遵守规则
  932. • 保持条漫纵向阅读逻辑,构图简洁
  933. • 画风统一,不混写实、3D、水墨
  934. • 画面干净,不杂乱
  935. 禁止/避免词汇
  936. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  937. ],
  938. '赛博朋克风格' => [
  939. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  940. 'prompt' => "风格说明
  941. 霓虹灯光、未来都市、暗色调、科技机械
  942. 正向提示词(中文)
  943. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  944. 必须遵守规则
  945. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  946. • 色调以暗调+霓虹为主,色彩统一
  947. • 画面科技感强,不杂乱
  948. 禁止/避免词汇
  949. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  950. ],
  951. '暗黑悬疑风格' => [
  952. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  953. 'prompt' => "风格说明
  954. 低饱和、冷色调、阴影重、神秘压抑
  955. 正向提示词(中文)
  956. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  957. 必须遵守规则
  958. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  959. • 画面氛围压抑神秘,但不低俗、不血腥
  960. • 角色形象统一,不崩坏
  961. 禁止/避免词汇
  962. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  963. ],
  964. '治愈清新风格' => [
  965. 'aliases' => ['治愈清新风格', '治愈清新'],
  966. 'prompt' => "风格说明
  967. 马卡龙色系、柔光、温暖干净
  968. 正向提示词(中文)
  969. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  970. 必须遵守规则
  971. • 保持治愈清新统一色调,不阴暗、不诡异
  972. • 画面柔和干净,无杂乱元素
  973. • 角色形象柔和可爱,不狰狞
  974. 禁止/避免词汇
  975. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  976. ],
  977. ];
  978. return $arr;
  979. }
  980. public function getArtStylePromptByInput($inputArtStyle): string
  981. {
  982. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  983. if ($normalizedInput === '') {
  984. return '';
  985. }
  986. return $this->getArtStylePromptMappings($normalizedInput);
  987. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  988. // foreach ($mapping['aliases'] as $alias) {
  989. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  990. // if ($normalizedAlias === '') {
  991. // continue;
  992. // }
  993. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  994. // return $mapping['prompt'];
  995. // }
  996. // }
  997. // }
  998. return '';
  999. }
  1000. public function getArtStyleShortPromptByInput($inputArtStyle) {
  1001. $stylePrefixes = [
  1002. '唯美真人风格' => [
  1003. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  1004. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  1005. ],
  1006. '真人古风风格' => [
  1007. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  1008. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  1009. ],
  1010. '日系动漫风格' => [
  1011. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  1012. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  1013. ],
  1014. '国漫风格' => [
  1015. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  1016. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  1017. ],
  1018. 'Q版卡通风格' => [
  1019. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  1020. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  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. '新中式水墨风格' => [
  1035. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  1036. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  1037. ],
  1038. '写实插画风格' => [
  1039. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  1040. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  1041. ],
  1042. '3D卡通风格' => [
  1043. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  1044. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  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. '治愈清新风格' => [
  1059. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  1060. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  1061. ]
  1062. ];
  1063. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  1064. }
  1065. private function normalizeArtStyleInput($value): string
  1066. {
  1067. $value = trim((string)$value);
  1068. if ($value === '') {
  1069. return '';
  1070. }
  1071. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  1072. return mb_strtolower($value, 'UTF-8');
  1073. }
  1074. private function replaceArtStyleSection(string $content, string $artStyle): string
  1075. {
  1076. if ($content === '' || $artStyle === '') {
  1077. return $content;
  1078. }
  1079. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  1080. if (!preg_match($pattern, $content)) {
  1081. return $content;
  1082. }
  1083. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  1084. }
  1085. /**
  1086. * DeepSeek流式输出处理方法
  1087. *
  1088. * @param array $post_data DeepSeek API请求参数
  1089. * @return \Generator 返回生成器,用于流式输出
  1090. */
  1091. private function deepSeekStreamResponse($post_data) {
  1092. // 设置最大输出tokens
  1093. $post_data['max_tokens'] = 300000;
  1094. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  1095. $post_data['stream_options'] = ['include_usage' => true];
  1096. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1097. $response = $client->post($this->url, [
  1098. 'json' => $post_data,
  1099. 'headers' => $this->headers,
  1100. 'stream' => true // 启用流式响应
  1101. ]);
  1102. $body = $response->getBody();
  1103. $fullContent = '';
  1104. $fullReasoningContent = '';
  1105. $usage = [];
  1106. $buffer = '';
  1107. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1108. // 逐行读取流式响应
  1109. while (!$body->eof()) {
  1110. $chunk = $body->read(1024); // 每次读取 1KB
  1111. $buffer .= $chunk;
  1112. // 按行分割
  1113. $lines = explode("\n", $buffer);
  1114. // 保留最后一个不完整的行
  1115. $buffer = array_pop($lines);
  1116. foreach ($lines as $line) {
  1117. $line = trim($line);
  1118. // 跳过空行
  1119. if (empty($line)) {
  1120. continue;
  1121. }
  1122. // 检查是否是 SSE 数据行
  1123. if (strpos($line, 'data: ') !== 0) {
  1124. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1125. continue;
  1126. }
  1127. $data = substr($line, 6); // 移除 "data: " 前缀
  1128. if ($data === '[DONE]') {
  1129. dLog('deepseek')->info('收到结束标记');
  1130. break 2; // 跳出两层循环
  1131. }
  1132. try {
  1133. $json = json_decode($data, true);
  1134. if (json_last_error() !== JSON_ERROR_NONE) {
  1135. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1136. continue;
  1137. }
  1138. if (isset($json['choices'][0]['delta'])) {
  1139. $delta = $json['choices'][0]['delta'];
  1140. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1141. if (isset($delta['reasoning_content'])) {
  1142. $fullReasoningContent .= $delta['reasoning_content'];
  1143. yield [
  1144. 'type' => 'reasoning',
  1145. 'content' => $delta['reasoning_content'],
  1146. 'full_reasoning' => $fullReasoningContent
  1147. ];
  1148. }
  1149. // 处理最终回答内容
  1150. if (isset($delta['content'])) {
  1151. $fullContent .= $delta['content'];
  1152. yield [
  1153. 'type' => 'content',
  1154. 'content' => $delta['content'],
  1155. ];
  1156. }
  1157. }
  1158. // 获取使用统计信息
  1159. if (isset($json['usage'])) {
  1160. $usage = $json['usage'];
  1161. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1162. }
  1163. } catch (\Exception $e) {
  1164. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1165. continue;
  1166. }
  1167. }
  1168. }
  1169. dLog('deepseek')->info('流式读取完成', [
  1170. 'content_length' => strlen($fullContent),
  1171. 'reasoning_length' => strlen($fullReasoningContent)
  1172. ]);
  1173. yield [
  1174. 'type' => 'done',
  1175. 'full_content' => $fullContent,
  1176. 'full_reasoning' => $fullReasoningContent,
  1177. 'usage' => $usage
  1178. ];
  1179. }
  1180. /**
  1181. * GPT 流式输出处理方法
  1182. *
  1183. * @param array $post_data GPT API请求参数
  1184. * @return \Generator 返回生成器,用于流式输出
  1185. */
  1186. private function gpt54StreamResponse($post_data) {
  1187. $apiKey = env('GPT_54_API_KEY');
  1188. if (empty($apiKey)) {
  1189. Utils::throwError('20003:GPT API Key未配置');
  1190. }
  1191. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1192. $headers = [
  1193. 'Authorization' => 'Bearer ' . $apiKey,
  1194. 'Content-Type' => 'application/json'
  1195. ];
  1196. // 移除 thinking 参数,GPT-5.4 不支持
  1197. if (isset($post_data['thinking'])) {
  1198. unset($post_data['thinking']);
  1199. }
  1200. if (isset($post_data['reasoning_effort'])) {
  1201. unset($post_data['reasoning_effort']);
  1202. }
  1203. $post_data['max_completion_tokens'] = 100000;
  1204. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  1205. $post_data['stream_options'] = ['include_usage' => true];
  1206. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  1207. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  1208. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  1209. 'json' => $post_data,
  1210. 'headers' => $headers,
  1211. 'stream' => true // 启用流式响应
  1212. ]);
  1213. $body = $response->getBody();
  1214. $fullContent = '';
  1215. $usage = [];
  1216. $buffer = '';
  1217. dLog('deepseek')->info('开始读取 GPT 流式响应');
  1218. // 逐行读取流式响应
  1219. while (!$body->eof()) {
  1220. $chunk = $body->read(1024); // 每次读取 1KB
  1221. $buffer .= $chunk;
  1222. // 按行分割
  1223. $lines = explode("\n", $buffer);
  1224. // 保留最后一个不完整的行
  1225. $buffer = array_pop($lines);
  1226. foreach ($lines as $line) {
  1227. $line = trim($line);
  1228. // 跳过空行
  1229. if (empty($line)) {
  1230. continue;
  1231. }
  1232. // 检查是否是 SSE 数据行
  1233. if (strpos($line, 'data: ') !== 0) {
  1234. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1235. continue;
  1236. }
  1237. $data = substr($line, 6); // 移除 "data: " 前缀
  1238. if ($data === '[DONE]') {
  1239. dLog('deepseek')->info('收到结束标记');
  1240. break 2; // 跳出两层循环
  1241. }
  1242. try {
  1243. $json = json_decode($data, true);
  1244. if (json_last_error() !== JSON_ERROR_NONE) {
  1245. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1246. continue;
  1247. }
  1248. if (isset($json['choices'][0]['delta'])) {
  1249. $delta = $json['choices'][0]['delta'];
  1250. // 处理回答内容
  1251. if (isset($delta['content'])) {
  1252. $fullContent .= $delta['content'];
  1253. yield [
  1254. 'type' => 'content',
  1255. 'content' => $delta['content'],
  1256. ];
  1257. }
  1258. }
  1259. // 获取使用统计信息
  1260. if (isset($json['usage'])) {
  1261. $usage = $json['usage'];
  1262. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1263. }
  1264. } catch (\Exception $e) {
  1265. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1266. continue;
  1267. }
  1268. }
  1269. }
  1270. dLog('deepseek')->info('流式读取完成', [
  1271. 'content_length' => strlen($fullContent)
  1272. ]);
  1273. yield [
  1274. 'type' => 'done',
  1275. 'full_content' => $fullContent,
  1276. 'full_reasoning' => '',
  1277. 'usage' => $usage
  1278. ];
  1279. }
  1280. // 与推理模型对话
  1281. public function chatWithReasoner($data) {
  1282. $content = getProp($data, 'content');
  1283. $model = getProp($data, 'model', 'r1');
  1284. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1285. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1286. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1287. if ($model == 'r1') {
  1288. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  1289. $thinkingMode = 'disabled';
  1290. } else {
  1291. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  1292. $thinkingMode = 'disabled';
  1293. }
  1294. // 获取可选情感(根据音色可支持情感选)
  1295. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  1296. $emotion_list = [];
  1297. foreach ($timbre_emotion as $emotion) {
  1298. $tmp = explode(',', $emotion);
  1299. $emotion_list = array_merge($emotion_list, $tmp);
  1300. }
  1301. $emotion_list = array_unique($emotion_list);
  1302. $emotion_str = implode('、', $emotion_list);
  1303. // // 获取可选情感
  1304. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  1305. // $emotion_str = implode('、', $emotion_list);
  1306. // 是否启用情感
  1307. $enable_emotion = getProp($data, 'enable_emotion', 0);
  1308. if ($enable_emotion) {
  1309. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  1310. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1311. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  1312. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  1313. }else {
  1314. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  1315. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1316. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  1317. }
  1318. $messages = [
  1319. [
  1320. 'role' => 'system',
  1321. 'content' => $sys_content
  1322. ],
  1323. [
  1324. 'role' => 'user',
  1325. 'content' => $content
  1326. ]
  1327. ];
  1328. $post_data = [
  1329. 'model' => $model,
  1330. 'messages' => $messages,
  1331. // 'max_tokens' => 8192,
  1332. 'temperature' => 1,
  1333. 'frequency_penalty' => 0,
  1334. 'presence_penalty' => 0,
  1335. 'thinking' => ['type' => $thinkingMode],
  1336. 'response_format' => [
  1337. 'type' => 'text'
  1338. ],
  1339. 'stream' => false
  1340. ];
  1341. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1342. // 根据模型类型选择调用方法
  1343. $fullContent = '';
  1344. $usage = [];
  1345. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1346. // DeepSeek 官方模型使用 DeepSeek API
  1347. $chatResult = $this->chatOnly($post_data);
  1348. } else if (in_array($model, $this->gpt_text_models)) {
  1349. // GPT-5.4 模型使用 TokenRouter API
  1350. $chatResult = $this->gpt54ChatOnly($post_data);
  1351. } else {
  1352. // 其他模型使用火山引擎API
  1353. $chatResult = $this->volcEngineChatCompletion($post_data);
  1354. }
  1355. if (is_array($chatResult)) {
  1356. $fullContent = $chatResult['fullContent'];
  1357. $usage = $chatResult['usage'];
  1358. }
  1359. // 处理获取到的剧本数据
  1360. $script_content = handleScriptWords($fullContent, $enable_emotion);
  1361. $result = [
  1362. 'origin_content' => $fullContent,
  1363. 'roles' => getProp($script_content, 'roles'),
  1364. 'words' => getProp($script_content, 'words'),
  1365. ];
  1366. return $result;
  1367. }
  1368. public function resetParagraphAudio($data) {
  1369. $bid = getProp($data, 'bid');
  1370. $cid = getProp($data, 'cid');
  1371. $version_id = getProp($data, 'version_id');
  1372. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  1373. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  1374. 'generate_status' => '待制作',
  1375. 'updated_at' => date('Y-m-d H:i:s')
  1376. ]);
  1377. }
  1378. public function saveParagraphAudio($data) {
  1379. $bid = getProp($data, 'bid');
  1380. $cid = getProp($data, 'cid');
  1381. $version_id = getProp($data, 'version_id');
  1382. $sequence = getProp($data, 'sequence');
  1383. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  1384. // 获取所有情感
  1385. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1386. $emotion_list = array_flip($emotion_list);
  1387. // 获取音色支持情感
  1388. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  1389. $timbre_emotion = explode(',', $timbre_emotion);
  1390. $emotion = getProp($data, 'emotion');
  1391. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  1392. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  1393. $list = [
  1394. 'bid' => $bid,
  1395. 'cid' => $cid,
  1396. 'version_id' => $version_id,
  1397. 'sequence' => $sequence,
  1398. 'role' => getProp($data, 'role'),
  1399. 'gender' => getProp($data, 'gender'),
  1400. 'text' => trim(getProp($data, 'text')),
  1401. 'emotion' => $emotion,
  1402. 'emotion_type' => $emotion_type,
  1403. 'voice_type' => getProp($data, 'voice_type'),
  1404. 'voice_name' => getProp($data, 'voice_name'),
  1405. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  1406. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  1407. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  1408. 'pitch' => getProp($data, 'pitch', 0),
  1409. // 'paragraph_audio_url' => '',
  1410. 'generate_status' => '制作中',
  1411. 'error_msg' => '',
  1412. 'updated_at' => date('Y-m-d H:i:s')
  1413. ];
  1414. $continue = false;
  1415. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  1416. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  1417. $list['generate_status'] = '制作成功';
  1418. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1419. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  1420. $continue = true;
  1421. }
  1422. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  1423. if ($id) {
  1424. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  1425. }else {
  1426. $list['created_at'] = date('Y-m-d H:i:s');
  1427. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  1428. $boolen = $id ? true : false;
  1429. }
  1430. // 如果更新成功则加入查询队列
  1431. if ($boolen) {
  1432. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  1433. Redis::sadd($redis_key, $id);
  1434. }
  1435. if ($boolen && !$continue) {
  1436. $boolen = false;
  1437. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1438. // 根据ID通过API通知合成音频
  1439. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  1440. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  1441. $response = $result->getBody()->getContents();
  1442. $response_arr = json_decode($response, true);
  1443. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1444. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1445. Log::info('通知火山生成段落音频失败: '.$error_msg);
  1446. Utils::throwError('20003:通知火山生成段落音频失败');
  1447. }
  1448. $boolen = true;
  1449. }
  1450. return $boolen;
  1451. }
  1452. public function insertAudioEffect($data) {
  1453. $audio_id = getProp($data, 'audio_id');
  1454. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1455. $bid = getProp($chapter_audio, 'bid');
  1456. $version_id = getProp($chapter_audio, 'version_id');
  1457. $cid = getProp($chapter_audio, 'cid');
  1458. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1459. $audio_effect_json = getProp($data, 'audio_effect_json');
  1460. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  1461. try {
  1462. DB::beginTransaction();
  1463. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1464. if (!$count) {
  1465. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1466. }else {
  1467. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1468. }
  1469. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1470. 'audio_effect_status' => '添加中',
  1471. 'audio_effect_json' => $audio_effect_json,
  1472. 'updated_at' => date('Y-m-d H:i:s')
  1473. ]);
  1474. if (!$boolen1) {
  1475. DB::rollBack();
  1476. Utils::throwError('20003:更新生成数据失败');
  1477. }
  1478. $id = DB::table('mp_audio_tasks')->insertGetId([
  1479. 'audio_id' => $audio_id,
  1480. 'generate_status' => '执行中',
  1481. 'generate_json' => json_encode([], 256),
  1482. 'bid' => $bid,
  1483. 'book_name' => getProp($chapter_audio, 'book_name'),
  1484. 'version_id' => $version_id,
  1485. 'version_name' => getProp($chapter_audio, 'version_name'),
  1486. 'cid' => $cid,
  1487. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1488. 'task_name' => $task_name,
  1489. 'created_at' => date('Y-m-d H:i:s'),
  1490. 'updated_at' => date('Y-m-d H:i:s')
  1491. ]);
  1492. if (!$id) {
  1493. DB::rollBack();
  1494. Utils::throwError('20003:创建任务失败');
  1495. }
  1496. }catch (\Exception $e) {
  1497. DB::rollBack();
  1498. Utils::throwError('20003:'.$e->getMessage());
  1499. }
  1500. DB::commit();
  1501. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1502. // 根据ID通过API通知合成音频
  1503. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1504. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1505. $response = $result->getBody()->getContents();
  1506. $response_arr = json_decode($response, true);
  1507. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1508. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1509. Log::info('通知火山插入音效失败: '.$error_msg);
  1510. Utils::throwError('20003:通知火山插入音效失败');
  1511. }
  1512. return true;
  1513. }
  1514. public function insertBgm($data) {
  1515. $audio_id = getProp($data, 'audio_id');
  1516. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1517. $bid = getProp($chapter_audio, 'bid');
  1518. $version_id = getProp($chapter_audio, 'version_id');
  1519. $cid = getProp($chapter_audio, 'cid');
  1520. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1521. $bgm_json = getProp($data, 'bgm_json');
  1522. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1523. if (!$bgm_json) {
  1524. $bgm_json = getProp($data, 'audio_effect_json');
  1525. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1526. }
  1527. try {
  1528. DB::beginTransaction();
  1529. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1530. if (!$count) {
  1531. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1532. }else {
  1533. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1534. }
  1535. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1536. 'bgm_status' => '添加中',
  1537. 'bgm_json' => $bgm_json,
  1538. 'updated_at' => date('Y-m-d H:i:s')
  1539. ]);
  1540. if (!$boolen1) {
  1541. DB::rollBack();
  1542. Utils::throwError('20003:更新生成数据失败');
  1543. }
  1544. $id = DB::table('mp_audio_tasks')->insertGetId([
  1545. 'audio_id' => $audio_id,
  1546. 'generate_status' => '执行中',
  1547. 'generate_json' => json_encode([], 256),
  1548. 'bid' => $bid,
  1549. 'book_name' => getProp($chapter_audio, 'book_name'),
  1550. 'version_id' => $version_id,
  1551. 'version_name' => getProp($chapter_audio, 'version_name'),
  1552. 'cid' => $cid,
  1553. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1554. 'task_name' => $task_name,
  1555. 'created_at' => date('Y-m-d H:i:s'),
  1556. 'updated_at' => date('Y-m-d H:i:s')
  1557. ]);
  1558. if (!$id) {
  1559. DB::rollBack();
  1560. Utils::throwError('20003:创建任务失败');
  1561. }
  1562. }catch (\Exception $e) {
  1563. DB::rollBack();
  1564. Utils::throwError('20003:'.$e->getMessage());
  1565. }
  1566. DB::commit();
  1567. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1568. // 根据ID通过API通知合成音频
  1569. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1570. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1571. $response = $result->getBody()->getContents();
  1572. $response_arr = json_decode($response, true);
  1573. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1574. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1575. Log::info('通知火山插入bgm失败: '.$error_msg);
  1576. Utils::throwError('20003:通知火山插入bgm失败');
  1577. }
  1578. return true;
  1579. }
  1580. public function getParagraphAudios($data) {
  1581. $bid = getProp($data, 'bid');
  1582. $cid = getProp($data, 'cid');
  1583. $version_id = getProp($data, 'version_id');
  1584. $sequence = getProp($data, 'sequence');
  1585. // 获取已生成的音频
  1586. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  1587. if ($sequence) $query->where('sequence', $sequence);
  1588. $paragraph_audios = $query->orderBy('sequence')->get();
  1589. $result = [];
  1590. foreach($paragraph_audios as $item) {
  1591. $result[] = [
  1592. 'sequence' => getProp($item, 'sequence'),
  1593. 'role' => getProp($item, 'role'),
  1594. 'gender' => getProp($item, 'gender'),
  1595. 'text' => trim(getProp($item, 'text')),
  1596. 'emotion' => getProp($item, 'emotion'),
  1597. 'emotion_type' => getProp($item, 'emotion_type'),
  1598. 'voice_type' => getProp($item, 'voice_type'),
  1599. 'voice_name' => getProp($item, 'voice_name'),
  1600. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1601. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1602. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1603. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1604. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  1605. ];
  1606. }
  1607. return $result;
  1608. }
  1609. // 新增合成任务
  1610. public function addGenerateTask($data) {
  1611. $bid = getProp($data, 'bid');
  1612. $cid = getProp($data, 'cid');
  1613. $version_id = getProp($data, 'version_id');
  1614. $generate_json = getProp($data, 'generate_json');
  1615. // 获取已生成的音频
  1616. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  1617. $paragraph_list = [];
  1618. foreach($paragraph_audios as $item) {
  1619. $paragraph_list[getProp($item, 'sequence')] = [
  1620. 'role' => getProp($item, 'role'),
  1621. 'gender' => getProp($item, 'gender'),
  1622. 'text' => trim(getProp($item, 'text')),
  1623. 'emotion' => getProp($item, 'emotion'),
  1624. 'emotion_type' => getProp($item, 'emotion_type'),
  1625. 'voice_type' => getProp($item, 'voice_type'),
  1626. 'voice_name' => getProp($item, 'voice_name'),
  1627. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1628. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1629. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1630. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1631. ];
  1632. }
  1633. // 更新角色-音色信息
  1634. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  1635. $existed_role_info = json_decode($existed_role_info, true);
  1636. if (!$existed_role_info) $existed_role_info = [];
  1637. // 获取情感信息
  1638. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1639. $emotion_list = array_flip($emotion_list);
  1640. // 获取音色对应情感组
  1641. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  1642. $timbre_emotion_list = [];
  1643. foreach($timbre_emotions as $item) {
  1644. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  1645. }
  1646. // 构造生成音频的json
  1647. $words = json_decode($generate_json, true);
  1648. // 最终合成前的参数组
  1649. $mp_chapter_paragraph_audios = [];
  1650. $sequence = 1;
  1651. $complete_paragraph_sequences = [];
  1652. foreach($words as &$word) {
  1653. 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:参数格式有误');
  1654. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  1655. $role = getProp($word, 'role');
  1656. $word['gender'] = (int)$word['gender'];
  1657. // 判断音色对应情感是否支持,不支持则调整为中性
  1658. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  1659. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  1660. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  1661. if (isset($emotion_list[getProp($word, 'emotion')])) {
  1662. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  1663. }else {
  1664. $word['emotion'] = '中性';
  1665. $word['emotion_type'] = 'neutral';
  1666. }
  1667. $existed_role_info[$role] = [
  1668. 'timbre_type' => $word['voice_type'],
  1669. 'timbre_name' => $word['voice_name'],
  1670. 'emotion' => $word['emotion'],
  1671. 'emotion_type' => $word['emotion_type'],
  1672. 'speed_ratio' => $word['speed_ratio'],
  1673. 'loudness_ratio'=> $word['loudness_ratio'],
  1674. 'emotion_scale' => $word['emotion_scale'],
  1675. 'pitch' => $word['pitch']
  1676. ];
  1677. $word['paragraph_audio_url'] = '';
  1678. // 判断生成参数是否相同,相同则直接使用已生成的音频
  1679. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  1680. // 如果音频存在并且参数都未改变则使用已生成的音频
  1681. if (getProp($paragraph, 'paragraph_audio_url')) {
  1682. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  1683. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  1684. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  1685. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  1686. // {
  1687. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1688. // }
  1689. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1690. }
  1691. $tmp = $word;
  1692. // 组装章节分句音频数据
  1693. // $tmp['sequence'] = getProp($word, 'sequence');
  1694. // $tmp['text'] = getProp($word, 'text');
  1695. // $tmp['emotion'] = getProp($word, 'emotion');
  1696. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  1697. // $tmp['voice_name'] = getProp($word, 'voice_name');
  1698. // $tmp['voice_type'] = getProp($word, 'voice_type');
  1699. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  1700. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  1701. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  1702. $tmp['bid'] = $bid;
  1703. $tmp['version_id'] = $version_id;
  1704. $tmp['cid'] = $cid;
  1705. $tmp['sequence'] = $sequence;
  1706. $tmp['created_at'] = date('Y-m-d H:i:s');
  1707. $tmp['updated_at'] = date('Y-m-d H:i:s');
  1708. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  1709. $mp_chapter_paragraph_audios[] = $tmp;
  1710. $complete_paragraph_sequences[] = $sequence;
  1711. $sequence++;
  1712. }
  1713. $generate_json = json_encode($words, 256);
  1714. // 判断是否有未生成字幕的段落
  1715. $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();
  1716. if ($no_subtitle_sequences) {
  1717. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  1718. }
  1719. try {
  1720. DB::beginTransaction();
  1721. $role_info = json_encode($existed_role_info, 256);
  1722. $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')]);
  1723. if (!$boolen) {
  1724. DB::rollBack();
  1725. Utils::throwError('20003:更新角色信息失败');
  1726. }
  1727. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  1728. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  1729. if (!$count) {
  1730. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1731. }else {
  1732. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1733. }
  1734. $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')]);
  1735. if (!$boolen1) {
  1736. DB::rollBack();
  1737. Utils::throwError('20003:更新生成数据失败');
  1738. }
  1739. $id = DB::table('mp_audio_tasks')->insertGetId([
  1740. 'audio_id' => getProp($chapter_audio, 'id'),
  1741. 'generate_status' => '执行中',
  1742. 'generate_json' => $generate_json,
  1743. 'bid' => $bid,
  1744. 'book_name' => getProp($chapter_audio, 'book_name'),
  1745. 'version_id' => $version_id,
  1746. 'version_name' => getProp($chapter_audio, 'version_name'),
  1747. 'cid' => $cid,
  1748. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1749. 'task_name' => $task_name,
  1750. 'created_at' => date('Y-m-d H:i:s'),
  1751. 'updated_at' => date('Y-m-d H:i:s')
  1752. ]);
  1753. if (!$id) {
  1754. DB::rollBack();
  1755. Utils::throwError('20003:创建任务失败');
  1756. }
  1757. // 删除不在段落序号范围内的其他数据
  1758. if ($complete_paragraph_sequences) {
  1759. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  1760. }
  1761. // // 删除章节分句音频数据并重新插入
  1762. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  1763. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  1764. // if (!$boolen3) {
  1765. // DB::rollBack();
  1766. // Utils::throwError('20003:更新章节分句音频失败');
  1767. // }
  1768. } catch (\Exception $e) {
  1769. DB::rollBack();
  1770. Utils::throwError('20003:'.$e->getMessage());
  1771. }
  1772. DB::commit();
  1773. // 通知火山生成音频
  1774. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1775. // 根据ID通过API通知合成音频
  1776. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  1777. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  1778. $response = $result->getBody()->getContents();
  1779. $response_arr = json_decode($response, true);
  1780. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1781. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1782. Log::info('通知火山生成音频失败: '.$error_msg);
  1783. Utils::throwError('20003:通知火山生成音频失败');
  1784. }
  1785. return true;
  1786. }
  1787. public function timbreList($data) {
  1788. $gender = getProp($data, 'gender');
  1789. $timbre_name = getProp($data, 'voice_name');
  1790. $category_id = getProp($data, 'category_id');
  1791. $age_stage = getProp($data, 'age_stage');
  1792. $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');
  1793. if ($gender) {
  1794. $query->where('gender', $gender);
  1795. }
  1796. if ($timbre_name) {
  1797. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  1798. }
  1799. if ($category_id) {
  1800. $query->where(function ($query) use ($category_id) {
  1801. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  1802. });
  1803. }
  1804. if ($age_stage) {
  1805. $query->where('age_stage', $age_stage);
  1806. }
  1807. $list = $query->get()->map(function ($value) {
  1808. $value = (array)$value;
  1809. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  1810. return $value;
  1811. })->toArray();
  1812. return $list;
  1813. }
  1814. // 生成火山临时token
  1815. public function setStsToken() {
  1816. // ************* 配置参数 *************
  1817. $method = 'GET';
  1818. $service = 'sts';
  1819. $host = 'open.volcengineapi.com';
  1820. $region = env('VOLC_REGION');
  1821. $endpoint = 'https://open.volcengineapi.com';
  1822. // $endpoint = 'https://tos-cn-beijing.volces.com';
  1823. $access_key = env('VOLC_AK');
  1824. $secret_key = env('VOLC_SK');
  1825. // 获取缓存中的token,如果没有则请求接口
  1826. $token = Redis::get('volc_sts_token');
  1827. if (!$token) {
  1828. // 查询参数
  1829. $query_parameters = [
  1830. 'Action' => 'AssumeRole',
  1831. 'RoleSessionName' => 'user@zw',
  1832. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  1833. 'Version' => '2018-01-01'
  1834. ];
  1835. // 生成URL编码的查询字符串
  1836. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  1837. // 获取签名头信息
  1838. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  1839. // 构建完整URL
  1840. $request_url = $endpoint . '?' . $request_parameters;
  1841. $client = new Client(['verify' => false]);
  1842. $response = $client->get($request_url, ['headers' => $headers]);
  1843. $response_arr = json_decode($response->getBody()->getContents(), true);
  1844. $result = [
  1845. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  1846. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  1847. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  1848. 'Region' => env('VOLC_REGION'),
  1849. 'Endpoint' => env('VOLC_END_POINT'),
  1850. 'Bucket' => env('VOLC_BUCKET'),
  1851. ];
  1852. // 缓存token
  1853. Redis::setex('volc_sts_token', 3000, json_encode($result));
  1854. return $result;
  1855. } else {
  1856. return json_decode($token, true);
  1857. }
  1858. // $response = $response['Response'];
  1859. // $access_key = $response['Credentials']['AccessKeyId'];
  1860. // $secret_key = $response['Credentials']['AccessKeySecret'];
  1861. // $security_token = $response['Credentials']['SecurityToken'];
  1862. // $expiration = $response['Credentials']['Expiration'];
  1863. // dd($response_arr);
  1864. }
  1865. public function emotionGroups($data) {
  1866. $id = getProp($data, 'group_id');
  1867. $group_name = getProp($data, 'group_name');
  1868. $voice_type = getProp($data, 'voice_type');
  1869. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  1870. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  1871. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  1872. if ($group_name) {
  1873. $query->where('group_name', 'like', "%{$group_name}%");
  1874. }
  1875. if ($id) {
  1876. $query->where('id', $id);
  1877. }
  1878. if ($voice_type) {
  1879. $query->where('voice_type', $voice_type);
  1880. }
  1881. return $query->orderBy('id')->get()->map(function ($value) {
  1882. return (array)$value;
  1883. })->toArray();
  1884. }
  1885. private function sign($key, $msg) {
  1886. return hash_hmac('sha256', $msg, $key, true);
  1887. }
  1888. // 生成签名密钥
  1889. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  1890. $kDate = $this->sign($key, $dateStamp);
  1891. $kRegion = $this->sign($kDate, $regionName);
  1892. $kService = $this->sign($kRegion, $serviceName);
  1893. $kSigning = $this->sign($kService, 'request');
  1894. return $kSigning;
  1895. }
  1896. // 获取签名头信息
  1897. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  1898. $contenttype = 'application/x-www-form-urlencoded';
  1899. $accept = 'application/json';
  1900. // 获取当前UTC时间
  1901. $t = new DateTime('now', new DateTimeZone('UTC'));
  1902. $xdate = $t->format('Ymd\THis\Z');
  1903. $datestamp = $t->format('Ymd');
  1904. // 1. 拼接规范请求串
  1905. $canonical_uri = '/';
  1906. $canonical_querystring = $request_parameters;
  1907. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  1908. $signed_headers = 'content-type;host;x-date';
  1909. // 空请求体的SHA256哈希
  1910. $payload_hash = hash('sha256', '');
  1911. $canonical_request = implode("\n", [
  1912. $method,
  1913. $canonical_uri,
  1914. $canonical_querystring,
  1915. $canonical_headers,
  1916. $signed_headers,
  1917. $payload_hash
  1918. ]);
  1919. // 2. 拼接待签名字符串
  1920. $algorithm = 'HMAC-SHA256';
  1921. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  1922. $hashed_canonical_request = hash('sha256', $canonical_request);
  1923. $string_to_sign = implode("\n", [
  1924. $algorithm,
  1925. $xdate,
  1926. $credential_scope,
  1927. $hashed_canonical_request
  1928. ]);
  1929. // 3. 计算签名
  1930. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  1931. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  1932. // 4. 添加签名到请求头
  1933. $authorization_header = sprintf(
  1934. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  1935. $algorithm,
  1936. $access_key,
  1937. $credential_scope,
  1938. $signed_headers,
  1939. $signature
  1940. );
  1941. return [
  1942. 'Accept' => $accept,
  1943. 'Content-Type' => $contenttype,
  1944. 'X-Date' => $xdate,
  1945. 'Authorization' => $authorization_header
  1946. ];
  1947. }
  1948. // 文字合成语音(火山引擎)
  1949. public function tts($data) {
  1950. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  1951. $headers = [
  1952. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  1953. 'Content-Type' => 'application/json; charset=UTF-8'
  1954. ];
  1955. $post_data = [
  1956. 'app' => [
  1957. 'appid' => env('VOLC_APPID'),
  1958. 'token' => env('VOLC_TOKEN'),
  1959. 'cluster' => 'volcano_tts'
  1960. ],
  1961. 'user' => [
  1962. 'uid' => 'mp_audio'
  1963. ],
  1964. // 'audio' => [
  1965. // 'voice_type' =>
  1966. // ],
  1967. ];
  1968. }
  1969. public function scriptList($data) {
  1970. $uid = Site::getUid();
  1971. $script_id = getProp($data, 'script_id');
  1972. $script_name = getProp($data, 'script_name');
  1973. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  1974. if ($script_id) {
  1975. $query->where('id', $script_id);
  1976. }
  1977. if ($script_name) {
  1978. $query->where('script_name', 'like', "%{$script_name}%");
  1979. }
  1980. return $query->orderBy('created_at', 'desc')->paginate(12);
  1981. }
  1982. public function scripts($data) {
  1983. $uid = Site::getUid();
  1984. $script_id = getProp($data, 'script_id');
  1985. $script_name = getProp($data, 'script_name');
  1986. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  1987. if ($script_id) {
  1988. $query->where('id', $script_id);
  1989. }
  1990. if ($script_name) {
  1991. $query->where('script_name', 'like', "%{$script_name}%");
  1992. }
  1993. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  1994. return (array)$value;
  1995. })->toArray();
  1996. }
  1997. public function scriptInfo($data) {
  1998. $uid = Site::getUid();
  1999. $script_id = getProp($data, 'script_id');
  2000. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  2001. // ->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();
  2002. ->selectRaw('id as script_id, script_name')->first();
  2003. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2004. $script = (array)$script;
  2005. // 获取分集组信息
  2006. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  2007. ->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')
  2008. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  2009. $value = (array)$value;
  2010. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  2011. return (array)$value;
  2012. })->toArray();
  2013. $script['group'] = $groups;
  2014. return $script;
  2015. }
  2016. public function createScript($data) {
  2017. $script_name = getProp($data, 'script_name');
  2018. $uid = Site::getUid(); // 获取当前用户ID
  2019. $cpid = Site::getCpid(); // 获取当前公司组ID
  2020. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  2021. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  2022. $script_name .= '_'.date('YmdHis');
  2023. }
  2024. return DB::table('mp_scripts')->insertGetId([
  2025. 'script_name' => $script_name,
  2026. 'user_id' => $uid,
  2027. 'cpid' => $cpid,
  2028. 'created_at' => date('Y-m-d H:i:s'),
  2029. 'updated_at' => date('Y-m-d H:i:s')
  2030. ]);
  2031. }
  2032. public function editScript($data) {
  2033. $script_id = getProp($data, 'script_id');
  2034. $script_name = getProp($data, 'script_name');
  2035. $uid = Site::getUid(); // 获取当前用户ID
  2036. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  2037. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  2038. if ($id && (int)$id !== (int)$script_id) {
  2039. $script_name .= '_'.date('YmdHis');
  2040. }
  2041. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2042. 'script_name' => $script_name,
  2043. 'updated_at' => date('Y-m-d H:i:s')
  2044. ]);
  2045. }
  2046. public function delScript($data) {
  2047. $script_id = getProp($data, 'script_id');
  2048. $uid = Site::getUid(); // 获取当前用户ID
  2049. if (!$script_id) Utils::throwError('20003:请选择剧本');
  2050. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2051. 'is_deleted' => 1,
  2052. 'updated_at' => date('Y-m-d H:i:s')
  2053. ]);
  2054. }
  2055. public function createEpisode($data) {
  2056. $script_id = getProp($data, 'script_id');
  2057. $group_name = getProp($data, 'group_name');
  2058. $remark = getProp($data, 'remark');
  2059. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  2060. $uid = Site::getUid(); // 获取当前用户ID
  2061. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  2062. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  2063. $group_name .= '_'.date('YmdHis');
  2064. }
  2065. return DB::table('mp_script_episode_group')->insertGetId([
  2066. 'script_id' => $script_id,
  2067. 'group_name' => $group_name,
  2068. 'user_id' => $uid,
  2069. 'remark' => $remark,
  2070. 'created_at' => date('Y-m-d H:i:s'),
  2071. 'updated_at' => date('Y-m-d H:i:s')
  2072. ]);
  2073. }
  2074. public function editEpisode($data) {
  2075. $group_id = getProp($data, 'group_id');
  2076. $start_episode_number = getProp($data, 'start_episode_number');
  2077. $end_episode_number = getProp($data, 'end_episode_number');
  2078. $group_name = getProp($data, 'group_name');
  2079. $uid = Site::getUid(); // 获取当前用户ID
  2080. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  2081. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  2082. if ($id && (int)$id !== (int)$group_id) {
  2083. $group_name .= '_'.date('YmdHis');
  2084. }
  2085. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2086. 'group_name' => $group_name,
  2087. 'start_episode_number' => $start_episode_number,
  2088. 'end_episode_number' => $end_episode_number,
  2089. 'updated_at' => date('Y-m-d H:i:s')
  2090. ]);
  2091. }
  2092. public function delEpisode($data) {
  2093. $group_id = getProp($data, 'group_id');
  2094. $uid = Site::getUid(); // 获取当前用户ID
  2095. if (!$group_id) Utils::throwError('20003:请选择分集');
  2096. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2097. 'is_deleted' => 1,
  2098. 'updated_at' => date('Y-m-d H:i:s')
  2099. ]);
  2100. }
  2101. /**
  2102. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2103. *
  2104. * @param array $data 包含以下参数:
  2105. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2106. * - question: 用户问题(可选)
  2107. * - model: 使用的模型(r1 或 v3,默认 v3)
  2108. * @return \Generator 返回生成器,用于流式输出
  2109. */
  2110. public function generateEpisodes($data) {
  2111. $script_id = getProp($data, 'script_id');
  2112. $group_id = getProp($data, 'group_id');
  2113. // $file = getProp($data, 'file');
  2114. $file = '';
  2115. $content = getProp($data, 'content', '');
  2116. // $bid = getProp($data, 'bid', 0);
  2117. $bid = 0;
  2118. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2119. if (!$group) {
  2120. Utils::throwError('20003:剧本分集不存在');
  2121. }
  2122. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  2123. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  2124. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  2125. $prompt = getProp($data, 'prompt');
  2126. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  2127. $model = getProp($data, 'model');
  2128. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2129. Utils::throwError('20003:该模型不存在!');
  2130. }
  2131. // 检查是否存在重叠的剧集序号范围
  2132. $exists_groups = DB::table('mp_script_episode_group')
  2133. ->where('script_id', $script_id)
  2134. ->where('id', '<>', $group_id) // 排除当前组
  2135. ->where('is_deleted', 0)
  2136. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2137. // 检查新范围是否与现有范围重叠
  2138. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2139. // 新范围的开始在现有范围内
  2140. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2141. ->where('end_episode_number', '>=', $start_episode_sequence);
  2142. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2143. // 新范围的结束在现有范围内
  2144. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2145. ->where('end_episode_number', '>=', $end_episode_sequence);
  2146. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2147. // 新范围完全包含现有范围
  2148. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2149. ->where('end_episode_number', '<=', $end_episode_sequence);
  2150. });
  2151. })
  2152. ->select('start_episode_number', 'end_episode_number')
  2153. ->get();
  2154. if ($exists_groups->isNotEmpty()) {
  2155. $conflict_ranges = [];
  2156. foreach ($exists_groups as $group) {
  2157. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2158. }
  2159. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2160. }
  2161. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2162. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2163. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2164. if ($model === 'deepseek-chat') {
  2165. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2166. $model = 'deepseek-v4-flash';
  2167. $thinkingMode = 'disabled';
  2168. } elseif ($model === 'deepseek-reasoner') {
  2169. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2170. $model = 'deepseek-v4-flash';
  2171. $thinkingMode = 'enabled';
  2172. }
  2173. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2174. if (!$script) {
  2175. Utils::throwError('20003:剧本不存在');
  2176. }
  2177. $content = getProp($group, 'content');
  2178. if (!$file && !$content && !$bid) {
  2179. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2180. }
  2181. // 提取文件内容
  2182. if ($file) {
  2183. $content = $this->extractFileContent($file);
  2184. if (!$content) {
  2185. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2186. }
  2187. } elseif ($bid) {
  2188. $content = $this->getContentByBid($bid);
  2189. if (!$content) {
  2190. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2191. }
  2192. } elseif ($content) {
  2193. $content = filterContent($content);
  2194. } elseif ($prompt) {
  2195. $content = filterContent($prompt);
  2196. } else {
  2197. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2198. }
  2199. // 构建消息
  2200. $messages = [
  2201. $this->sys_message,
  2202. [
  2203. 'role' => 'user',
  2204. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2205. ]
  2206. ];
  2207. $post_data = [
  2208. 'model' => $model,
  2209. 'messages' => $messages,
  2210. // 'max_tokens' => 8192,
  2211. 'temperature' => 0.7,
  2212. 'frequency_penalty' => 0,
  2213. 'presence_penalty' => 0,
  2214. 'thinking' => ['type' => $thinkingMode],
  2215. 'response_format' => ['type' => 'text'],
  2216. 'stream' => true
  2217. ];
  2218. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2219. // 根据模型类型选择调用方法
  2220. $fullContent = '';
  2221. $fullReasoningContent = '';
  2222. $usage = [];
  2223. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2224. // DeepSeek 官方模型使用 DeepSeek API
  2225. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2226. } else if (in_array($model, $this->gpt_text_models)) {
  2227. // GPT-5.4 模型使用 TokenRouter API
  2228. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2229. } else {
  2230. // 其他模型使用火山引擎API
  2231. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2232. }
  2233. // 处理流式输出
  2234. foreach ($streamGenerator as $chunk) {
  2235. if (isset($chunk['type'])) {
  2236. if ($chunk['type'] === 'done') {
  2237. // 最终结果
  2238. $fullContent = $chunk['full_content'];
  2239. $fullReasoningContent = $chunk['full_reasoning'];
  2240. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2241. } else {
  2242. // 逐块yield数据
  2243. yield $chunk;
  2244. }
  2245. }
  2246. }
  2247. dLog('deepseek')->info('完整内容: '.$fullContent);
  2248. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2249. // 处理完整内容并返回最终结果
  2250. $script_arr = [];
  2251. if ($fullContent) {
  2252. $script_arr = extractScriptContent($fullContent);
  2253. }
  2254. logDB('deepseek', 'info', '解析内容', $script_arr);
  2255. if (!$script_arr['episodes']) {
  2256. Utils::throwError('20003:未生成剧本相关信息');
  2257. // yield [
  2258. // 'type' => 'done',
  2259. // 'script' => $script_arr,
  2260. // 'msg' => '未生成剧本相关信息',
  2261. // 'answer' => $fullContent,
  2262. // 'reasoning' => $fullReasoningContent,
  2263. // 'usage' => $usage
  2264. // ];
  2265. // return ;
  2266. }
  2267. try {
  2268. DB::beginTransaction();
  2269. // // 返回前保存剧本内容
  2270. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2271. // 'content' => $content,
  2272. // 'updated_at' => date('Y-m-d H:i:s')
  2273. // ]);
  2274. // if (!$boolen) {
  2275. // Utils::throwError('20003:保存剧本内容失败');
  2276. // }
  2277. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2278. // 'start_episode_number' => $start_episode_sequence,
  2279. // 'end_episode_number' => $end_episode_sequence,
  2280. // 'updated_at' => date('Y-m-d H:i:s')
  2281. // ]);
  2282. // if (!$boolen1) {
  2283. // Utils::throwError('20003:保存分集失败');
  2284. // }
  2285. $episode_content = '';
  2286. $episodes = [];
  2287. foreach ($script_arr['episodes'] as $item) {
  2288. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  2289. // $episodes[] = [
  2290. // 'script_id' => $script_id,
  2291. // 'episode_number' => $item['episode_number'],
  2292. // 'episode_name' => $item['episode_name'],
  2293. // 'episode_content' => $item['episode_content'],
  2294. // 'created_at' => date('Y-m-d H:i:s'),
  2295. // 'updated_at' => date('Y-m-d H:i:s'),
  2296. // ];
  2297. }
  2298. if ($episode_content) {
  2299. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2300. 'episode_content' => $episode_content,
  2301. 'updated_at' => date('Y-m-d H:i:s')
  2302. ]);
  2303. if (!$boolen2) {
  2304. Utils::throwError('20003:保存分集内容失败');
  2305. }
  2306. }else {
  2307. Utils::throwError('20003:分集剧本解析失败');
  2308. }
  2309. }catch (\Exception $e) {
  2310. DB::rollBack();
  2311. Utils::throwError('20003:'.$e->getMessage());
  2312. }
  2313. DB::commit();
  2314. yield [
  2315. 'type' => 'done',
  2316. 'script' => $script_arr,
  2317. 'episode_content' => $episode_content,
  2318. 'answer' => $fullContent,
  2319. 'reasoning' => $fullReasoningContent,
  2320. 'usage' => $usage
  2321. ];
  2322. }
  2323. public function chatWithFileStream($data) {
  2324. $script_id = getProp($data, 'script_id');
  2325. $group_id = getProp($data, 'group_id');
  2326. $file = getProp($data, 'file');
  2327. $content = getProp($data, 'content', '');
  2328. $bid = getProp($data, 'bid', 0);
  2329. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2330. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2331. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  2332. $prompt = getProp($data, 'prompt');
  2333. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2334. if (!empty($prompt)) {
  2335. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2336. }
  2337. $question = getProp($data, 'question', $baseQuestion);
  2338. $model = getProp($data, 'model');
  2339. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2340. Utils::throwError('20003:该模型不存在!');
  2341. }
  2342. // 检查是否存在重叠的剧集序号范围
  2343. $exists_groups = DB::table('mp_script_episode_group')
  2344. ->where('script_id', $script_id)
  2345. ->where('id', '<>', $group_id)
  2346. ->where('is_deleted', 0)
  2347. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2348. // 检查新范围是否与现有范围重叠
  2349. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2350. // 新范围的开始在现有范围内
  2351. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2352. ->where('end_episode_number', '>=', $start_episode_sequence);
  2353. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2354. // 新范围的结束在现有范围内
  2355. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2356. ->where('end_episode_number', '>=', $end_episode_sequence);
  2357. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2358. // 新范围完全包含现有范围
  2359. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2360. ->where('end_episode_number', '<=', $end_episode_sequence);
  2361. });
  2362. })
  2363. ->select('start_episode_number', 'end_episode_number')
  2364. ->get();
  2365. if ($exists_groups->isNotEmpty()) {
  2366. $conflict_ranges = [];
  2367. foreach ($exists_groups as $group) {
  2368. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2369. }
  2370. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2371. }
  2372. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2373. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2374. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2375. if ($model === 'deepseek-chat') {
  2376. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2377. $model = 'deepseek-v4-flash';
  2378. $thinkingMode = 'disabled';
  2379. } elseif ($model === 'deepseek-reasoner') {
  2380. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2381. $model = 'deepseek-v4-flash';
  2382. $thinkingMode = 'enabled';
  2383. }
  2384. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2385. if (!$script) {
  2386. Utils::throwError('20003:剧本不存在');
  2387. }
  2388. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2389. if (!$group) {
  2390. Utils::throwError('20003:剧本分集不存在');
  2391. }
  2392. if (!$file && !$content && !$bid) {
  2393. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2394. }
  2395. // 提取文件内容
  2396. if ($file) {
  2397. $content = $this->extractFileContent($file);
  2398. if (!$content) {
  2399. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2400. }
  2401. } elseif ($bid) {
  2402. $content = $this->getContentByBid($bid);
  2403. if (!$content) {
  2404. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2405. }
  2406. } elseif ($content) {
  2407. $content = filterContent($content);
  2408. } elseif ($prompt) {
  2409. $content = filterContent($prompt);
  2410. } else {
  2411. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2412. }
  2413. // 构建消息
  2414. $messages = [
  2415. [
  2416. 'role' => 'system',
  2417. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  2418. 强制要求:\n
  2419. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2420. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  2421. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  2422. 普通要求:\n
  2423. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  2424. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  2425. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  2426. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  2427. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  2428. 示例如下:\n
  2429. ###剧本名:西昆仑
  2430. ###故事梗概
  2431. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2432. ###剧本亮点
  2433. 亮点1:绝境奇药,生死一线
  2434. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2435. 亮点2:结拜兄妹,化解尴尬
  2436. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2437. 亮点3:纤发夺命,情愫暗涌
  2438. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2439. ###人物关系
  2440. 阿雪与梁萧之间存在兄妹之情。
  2441. ###核心矛盾
  2442. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2443. ###主体列表
  2444. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2445. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2446. 阴阳球:天地异宝,能化生精气,救人于危难。
  2447. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2448. ###美术风格
  2449. 基础画风风格词:厚涂古风
  2450. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2451. ###场景列表
  2452. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  2453. [
  2454. 'role' => 'user',
  2455. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2456. ]
  2457. ];
  2458. $post_data = [
  2459. 'model' => $model,
  2460. 'messages' => $messages,
  2461. // 'max_tokens' => 8192,
  2462. 'temperature' => 0.7,
  2463. 'frequency_penalty' => 0,
  2464. 'presence_penalty' => 0,
  2465. 'thinking' => ['type' => $thinkingMode],
  2466. 'response_format' => ['type' => 'text'],
  2467. 'stream' => true
  2468. ];
  2469. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2470. // 根据模型类型选择调用方法
  2471. $fullContent = '';
  2472. $fullReasoningContent = '';
  2473. $usage = [];
  2474. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2475. // DeepSeek 官方模型使用 DeepSeek API
  2476. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2477. } else if (in_array($model, $this->gpt_text_models)) {
  2478. // GPT-5.4 模型使用 TokenRouter API
  2479. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2480. } else {
  2481. // 其他模型使用火山引擎API
  2482. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2483. }
  2484. // 处理流式输出
  2485. foreach ($streamGenerator as $chunk) {
  2486. if (isset($chunk['type'])) {
  2487. if ($chunk['type'] === 'done') {
  2488. // 最终结果
  2489. $fullContent = $chunk['full_content'];
  2490. $fullReasoningContent = $chunk['full_reasoning'];
  2491. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2492. } else {
  2493. // 逐块yield数据
  2494. yield $chunk;
  2495. }
  2496. }
  2497. }
  2498. dLog('deepseek')->info('完整内容: '.$fullContent);
  2499. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2500. // 处理完整内容并返回最终结果
  2501. $script_arr = [];
  2502. if ($fullContent) {
  2503. $script_arr = extractScriptContent($fullContent);
  2504. }
  2505. logDB('deepseek', 'info', '解析内容', $script_arr);
  2506. if (!$script_arr['roles']) {
  2507. Utils::throwError('20003:未生成剧本相关信息');
  2508. // yield [
  2509. // 'type' => 'done',
  2510. // 'script' => $script_arr,
  2511. // 'msg' => '未生成剧本相关信息',
  2512. // 'answer' => $fullContent,
  2513. // 'reasoning' => $fullReasoningContent,
  2514. // 'usage' => $usage
  2515. // ];
  2516. }
  2517. try {
  2518. DB::beginTransaction();
  2519. // // 返回前保存剧本内容
  2520. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2521. // 'content' => $content,
  2522. // 'status' => '解析完成',
  2523. // 'updated_at' => date('Y-m-d H:i:s')
  2524. // ]);
  2525. // if (!$boolen) {
  2526. // Utils::throwError('20003:保存剧本内容失败');
  2527. // }
  2528. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2529. 'start_episode_number' => $start_episode_sequence,
  2530. 'end_episode_number' => $end_episode_sequence,
  2531. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2532. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2533. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2534. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2535. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2536. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2537. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2538. 'status' => '解析完成',
  2539. 'content' => $content,
  2540. 'updated_at' => date('Y-m-d H:i:s')
  2541. ]);
  2542. if (!$boolen1) {
  2543. Utils::throwError('20003:保存分集失败');
  2544. }
  2545. // $episodes = [];
  2546. // foreach ($script_arr['episodes'] as $item) {
  2547. // $episodes[] = [
  2548. // 'script_id' => $script_id,
  2549. // 'episode_number' => $item['episode_number'],
  2550. // 'episode_name' => $item['episode_name'],
  2551. // 'episode_content' => $item['episode_content'],
  2552. // 'created_at' => date('Y-m-d H:i:s'),
  2553. // 'updated_at' => date('Y-m-d H:i:s'),
  2554. // ];
  2555. // }
  2556. // if ($episodes) {
  2557. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2558. // if (!$boolen2) {
  2559. // Utils::throwError('20003:保存分集内容失败');
  2560. // }
  2561. // }else {
  2562. // Utils::throwError('20003:分集剧本解析失败');
  2563. // }
  2564. }catch (\Exception $e) {
  2565. DB::rollBack();
  2566. Utils::throwError('20003:'.$e->getMessage());
  2567. }
  2568. DB::commit();
  2569. yield [
  2570. 'type' => 'done',
  2571. 'script' => $script_arr,
  2572. 'answer' => $fullContent,
  2573. 'reasoning' => $fullReasoningContent,
  2574. 'usage' => $usage
  2575. ];
  2576. }
  2577. /**
  2578. * 上传文件识别文字内容并与 DeepSeek 进行对话
  2579. *
  2580. * @param array $data 包含以下参数:
  2581. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2582. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  2583. * - model: 使用的模型(r1 或 v3,默认 v3)
  2584. * @return array
  2585. */
  2586. public function chatWithFile($data) {
  2587. $script_id = getProp($data, 'script_id');
  2588. $file = getProp($data, 'file');
  2589. $content = getProp($data, 'content', '');
  2590. $bid = getProp($data, 'bid', 0);
  2591. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2592. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2593. $prompt = getProp($data, 'prompt');
  2594. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2595. if (!empty($prompt)) {
  2596. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2597. }
  2598. $question = getProp($data, 'question', $baseQuestion);
  2599. // 处理文本模型
  2600. $model = getProp($data, 'model');
  2601. if (!$model) {
  2602. // 用户没有输入,使用默认值
  2603. $model = 'doubao-seed-2-0-mini-260215';
  2604. }
  2605. // 验证模型是否在可用模型表中
  2606. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2607. $model = 'doubao-seed-2-0-mini-260215';
  2608. }
  2609. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2610. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2611. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2612. if ($model === 'deepseek-chat') {
  2613. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2614. $model = 'deepseek-v4-flash';
  2615. $thinkingMode = 'disabled';
  2616. } elseif ($model === 'deepseek-reasoner') {
  2617. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2618. $model = 'deepseek-v4-flash';
  2619. $thinkingMode = 'enabled';
  2620. }
  2621. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2622. if (!$script) {
  2623. Utils::throwError('20003:剧本不存在');
  2624. }
  2625. if (!$file && !$content && !$bid) {
  2626. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2627. }
  2628. // 提取文件内容
  2629. if ($file) {
  2630. $content = $this->extractFileContent($file);
  2631. if (!$content) {
  2632. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2633. }
  2634. } elseif ($bid) {
  2635. $content = $this->getContentByBid($bid);
  2636. if (!$content) {
  2637. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2638. }
  2639. } elseif ($content) {
  2640. $content = filterContent($content);
  2641. } elseif ($prompt) {
  2642. $content = filterContent($prompt);
  2643. } else {
  2644. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2645. }
  2646. // 构建消息
  2647. $messages = [
  2648. $this->sys_message,
  2649. [
  2650. 'role' => 'user',
  2651. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2652. ]
  2653. ];
  2654. $post_data = [
  2655. 'model' => $model,
  2656. 'messages' => $messages,
  2657. // 'max_tokens' => 8192,
  2658. 'temperature' => 0.7,
  2659. 'frequency_penalty' => 0,
  2660. 'presence_penalty' => 0,
  2661. 'thinking' => ['type' => $thinkingMode],
  2662. 'response_format' => ['type' => 'text'],
  2663. 'stream' => false
  2664. ];
  2665. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2666. // 根据模型类型选择调用方法
  2667. $fullContent = '';
  2668. $usage = [];
  2669. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2670. // DeepSeek 官方模型使用 DeepSeek API
  2671. $chatResult = $this->chatOnly($post_data);
  2672. } else if (in_array($model, $this->gpt_text_models)) {
  2673. // GPT-5.4 模型使用 TokenRouter API
  2674. $chatResult = $this->gpt54ChatOnly($post_data);
  2675. } else {
  2676. // 其他模型使用火山引擎API
  2677. $chatResult = $this->volcEngineChatCompletion($post_data);
  2678. }
  2679. if (is_array($chatResult)) {
  2680. $fullContent = $chatResult['fullContent'];
  2681. $usage = $chatResult['usage'];
  2682. }
  2683. $script_arr = [];
  2684. // 处理结果
  2685. if ($fullContent) {
  2686. $script_arr = extractScriptContent($fullContent);
  2687. }
  2688. // 返回前保存剧本内容
  2689. DB::table('mp_scripts')->where('id', $script_id)->update([
  2690. 'content' => $content,
  2691. 'updated_at' => date('Y-m-d H:i:s')
  2692. ]);
  2693. return [
  2694. 'script' => $script_arr,
  2695. 'answer' => $fullContent,
  2696. 'usage' => $usage
  2697. ];
  2698. }
  2699. public function getEpisodeContent($data) {
  2700. $group_id = getProp($data, 'group_id');
  2701. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  2702. }
  2703. public function saveEpisodeContent($data) {
  2704. $script_id = getProp($data, 'script_id');
  2705. $group_id = getProp($data, 'group_id');
  2706. $start_episode_sequence = getProp($data, 'start_episode_number');
  2707. $end_episode_sequence = getProp($data, 'end_episode_number');
  2708. // 检查是否存在重叠的剧集序号范围
  2709. $exists_groups = DB::table('mp_script_episode_group')
  2710. ->where('script_id', $script_id)
  2711. ->where('id', '<>', $group_id) // 排除当前组
  2712. ->where('is_deleted', 0)
  2713. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2714. // 检查新范围是否与现有范围重叠
  2715. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2716. // 新范围的开始在现有范围内
  2717. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2718. ->where('end_episode_number', '>=', $start_episode_sequence);
  2719. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2720. // 新范围的结束在现有范围内
  2721. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2722. ->where('end_episode_number', '>=', $end_episode_sequence);
  2723. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2724. // 新范围完全包含现有范围
  2725. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2726. ->where('end_episode_number', '<=', $end_episode_sequence);
  2727. });
  2728. })
  2729. ->select('start_episode_number', 'end_episode_number')
  2730. ->get();
  2731. if ($exists_groups->isNotEmpty()) {
  2732. $conflict_ranges = [];
  2733. foreach ($exists_groups as $group) {
  2734. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2735. }
  2736. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2737. }
  2738. $episode_content = getProp($data, 'episode_content');
  2739. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  2740. 'content' => $episode_content,
  2741. 'start_episode_number' => $start_episode_sequence,
  2742. 'end_episode_number' => $end_episode_sequence,
  2743. 'updated_at' => date('Y-m-d H:i:s')
  2744. ]);
  2745. $script_arr =getProp($data, 'script', []);
  2746. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  2747. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2748. $script_id = getProp($data, 'script_id');
  2749. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  2750. try {
  2751. DB::beginTransaction();
  2752. $update_data = [
  2753. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2754. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2755. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2756. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2757. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2758. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2759. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2760. 'status' => 3,
  2761. 'start_episode_sequence' => $start_episode_sequence,
  2762. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  2763. 'episode_num' => count($script_arr['episodes']),
  2764. 'updated_at' => date('Y-m-d H:i:s')
  2765. ];
  2766. // 保存剧本内容
  2767. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  2768. if (!$boolen) {
  2769. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  2770. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  2771. Utils::throwError('20003:剧本内容保存失败');
  2772. }
  2773. // 保存分集内容
  2774. // 删除历史分集内容
  2775. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  2776. $episodes = [];
  2777. $sequence = 1;
  2778. foreach ($script_arr['episodes'] as $episode) {
  2779. $segment_number = 1;
  2780. foreach($episode['segments'] as $segment) {
  2781. $episodes[] = [
  2782. 'script_id' => $script_id,
  2783. 'episode_number' => $episode['episode_number'],
  2784. 'title' => $episode['title'],
  2785. // 'content' => $episode['content'],
  2786. 'content' => '',
  2787. 'segment_number' => $segment_number,
  2788. 'segment_content' => $segment['segment_content'],
  2789. 'sequence' => $sequence,
  2790. 'created_at' => date('Y-m-d H:i:s'),
  2791. 'updated_at' => date('Y-m-d H:i:s')
  2792. ];
  2793. $sequence++;
  2794. $segment_number++;
  2795. }
  2796. }
  2797. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2798. if (!$boolen2) {
  2799. dLog('deepseek')->info('分集内容保存失败', $episodes);
  2800. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  2801. Utils::throwError('20003:分集内容保存失败');
  2802. }
  2803. } catch (\Exception $e) {
  2804. DB::rollBack();
  2805. Utils::throwError('20003:'.$e->getMessage());
  2806. }
  2807. DB::commit();
  2808. return true;
  2809. }
  2810. public function getBookContent($data) {
  2811. $bid = getProp($data, 'bid');
  2812. $start_sequence = getProp($data, 'start_sequence');
  2813. $end_sequence = getProp($data, 'end_sequence');
  2814. $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])
  2815. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  2816. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  2817. return $return_content;
  2818. }
  2819. public function exportScript($data) {
  2820. $filename = getProp($data, 'filename');
  2821. $script_id = getProp($data, 'script_id');
  2822. $group_id = getProp($data, 'group_id');
  2823. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  2824. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  2825. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2826. $script = (array)$script;
  2827. // 获取分集组信息
  2828. if ($group_id) {
  2829. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2830. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2831. ->get()->map(function($value) {
  2832. return (array)$value;
  2833. })->toArray();
  2834. }else {
  2835. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2836. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2837. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  2838. return (array)$value;
  2839. })->toArray();
  2840. }
  2841. if (!$groups) Utils::throwError('20003:分集不存在');
  2842. $script['group'] = $groups;
  2843. $export_type = getProp($data, 'export_type', 'txt');
  2844. // 生成文件名
  2845. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  2846. // 根据导出类型生成不同格式的文件
  2847. switch ($export_type) {
  2848. case 'txt':
  2849. return $this->exportScriptAsTxt($script, $filename);
  2850. case 'pdf':
  2851. return $this->exportScriptAsPdf($script, $filename);
  2852. default:
  2853. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  2854. }
  2855. }
  2856. /**
  2857. * 导出剧本为TXT格式
  2858. */
  2859. private function exportScriptAsTxt($script, $filename) {
  2860. // 构建TXT内容
  2861. $content = $this->buildScriptContent($script);
  2862. // 设置响应头,直接下载
  2863. header('Content-Type: text/plain; charset=utf-8');
  2864. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  2865. header('Content-Length: ' . strlen($content));
  2866. // 输出内容并结束
  2867. echo $content;
  2868. exit();
  2869. }
  2870. /**
  2871. * 导出剧本为PDF格式
  2872. */
  2873. private function exportScriptAsPdf($script, $filename) {
  2874. // 使用HTML转PDF的方式来更好地支持中文
  2875. $htmlContent = $this->buildScriptHtmlForPdf($script);
  2876. // 创建PDF实例
  2877. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  2878. // 设置文档信息
  2879. $pdf->SetCreator('剧本导出系统');
  2880. $pdf->SetAuthor('系统');
  2881. $pdf->SetTitle($script['script_name']);
  2882. $pdf->SetSubject('剧本导出');
  2883. // 设置边距
  2884. $pdf->SetMargins(15, 15, 15);
  2885. $pdf->SetAutoPageBreak(TRUE, 15);
  2886. // 添加页面
  2887. $pdf->AddPage();
  2888. // 注册并使用 simsun.ttf 字体
  2889. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  2890. // 使用HTML内容生成PDF
  2891. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  2892. // 直接输出PDF文件供下载
  2893. header('Content-Type: application/pdf');
  2894. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  2895. // 直接输出PDF内容
  2896. $pdf->Output($filename . '.pdf', 'D');
  2897. exit();
  2898. }
  2899. /**
  2900. * 构建用于PDF的HTML内容
  2901. */
  2902. private function buildScriptHtmlForPdf($script) {
  2903. $html = '<style>
  2904. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  2905. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  2906. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  2907. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  2908. .info { margin-bottom: 8px; }
  2909. .group { margin-bottom: 30px; page-break-inside: avoid; }
  2910. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  2911. .segment { margin-bottom: 10px; margin-left: 20px; }
  2912. .episode-content { white-space: pre-wrap; }
  2913. </style>';
  2914. // 标题
  2915. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  2916. // 处理分组数据
  2917. if (!empty($script['group']) && is_array($script['group'])) {
  2918. $groups = (array)$script['group'];
  2919. foreach ($groups as $group) {
  2920. $html .= '<div class="group">';
  2921. // 分组标题
  2922. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  2923. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  2924. // 故事梗概
  2925. if (!empty($group['intro'])) {
  2926. $html .= '<h3>故事梗概</h3>';
  2927. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  2928. }
  2929. // 剧本亮点
  2930. if (!empty($group['highlights'])) {
  2931. $html .= '<h3>剧本亮点</h3>';
  2932. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  2933. }
  2934. // 人物关系
  2935. if (!empty($group['role_relationship'])) {
  2936. $html .= '<h3>人物关系</h3>';
  2937. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  2938. }
  2939. // 核心矛盾
  2940. if (!empty($group['core_contradiction'])) {
  2941. $html .= '<h3>核心矛盾</h3>';
  2942. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  2943. }
  2944. // 主体列表
  2945. if (!empty($group['roles']) && is_array($group['roles'])) {
  2946. $html .= '<h3>主体列表</h3>';
  2947. $html .= '<ul>';
  2948. foreach ($group['roles'] as $role) {
  2949. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  2950. }
  2951. $html .= '</ul>';
  2952. }
  2953. // 美术风格
  2954. if (!empty($group['art_style'])) {
  2955. $html .= '<h3>美术风格</h3>';
  2956. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  2957. }
  2958. // 场景列表
  2959. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  2960. $html .= '<h3>场景列表</h3>';
  2961. $html .= '<ul>';
  2962. foreach ($group['scenes'] as $scene) {
  2963. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  2964. }
  2965. $html .= '</ul>';
  2966. }
  2967. // 分集剧本
  2968. if (!empty($group['episode_content'])) {
  2969. $html .= '<h3>分集剧本</h3>';
  2970. // 去除零宽字符和其他不可见字符
  2971. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  2972. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  2973. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  2974. }
  2975. $html .= '</div>';
  2976. }
  2977. }
  2978. return $html;
  2979. }
  2980. /**
  2981. * 构建PDF内容
  2982. */
  2983. private function buildPdfContent($pdf, $script) {
  2984. // 标题
  2985. $pdf->SetFont('dejavusans', 'B', 18);
  2986. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  2987. $pdf->Ln(5);
  2988. // 基本信息
  2989. $pdf->SetFont('dejavusans', '', 12);
  2990. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  2991. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  2992. $pdf->Ln(5);
  2993. // 剧本简介
  2994. if (!empty($script['intro'])) {
  2995. $pdf->SetFont('dejavusans', 'B', 14);
  2996. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  2997. $pdf->SetFont('dejavusans', '', 12);
  2998. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  2999. $pdf->Ln(3);
  3000. }
  3001. // 亮点
  3002. if (!empty($script['highlights'])) {
  3003. $pdf->SetFont('dejavusans', 'B', 14);
  3004. $pdf->Cell(0, 10, '亮点', 0, 1);
  3005. $pdf->SetFont('dejavusans', '', 12);
  3006. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  3007. $pdf->Ln(3);
  3008. }
  3009. // 核心矛盾
  3010. if (!empty($script['core_contradiction'])) {
  3011. $pdf->SetFont('dejavusans', 'B', 14);
  3012. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  3013. $pdf->SetFont('dejavusans', '', 12);
  3014. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  3015. $pdf->Ln(3);
  3016. }
  3017. // 艺术风格
  3018. if (!empty($script['art_style'])) {
  3019. $pdf->SetFont('dejavusans', 'B', 14);
  3020. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  3021. $pdf->SetFont('dejavusans', '', 12);
  3022. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  3023. $pdf->Ln(3);
  3024. }
  3025. // 备注
  3026. if (!empty($script['remark'])) {
  3027. $pdf->SetFont('dejavusans', 'B', 14);
  3028. $pdf->Cell(0, 10, '备注', 0, 1);
  3029. $pdf->SetFont('dejavusans', '', 12);
  3030. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  3031. $pdf->Ln(3);
  3032. }
  3033. // 角色列表
  3034. if (!empty($script['roles']) && is_array($script['roles'])) {
  3035. $pdf->SetFont('dejavusans', 'B', 14);
  3036. $pdf->Cell(0, 10, '角色列表', 0, 1);
  3037. $pdf->SetFont('dejavusans', '', 12);
  3038. foreach ($script['roles'] as $index => $role) {
  3039. if (is_array($role) || is_object($role)) {
  3040. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  3041. } else {
  3042. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  3043. }
  3044. }
  3045. $pdf->Ln(3);
  3046. }
  3047. // 角色关系
  3048. if (!empty($script['role_relationship'])) {
  3049. $pdf->SetFont('dejavusans', 'B', 14);
  3050. $pdf->Cell(0, 10, '角色关系', 0, 1);
  3051. $pdf->SetFont('dejavusans', '', 12);
  3052. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  3053. $pdf->Ln(3);
  3054. }
  3055. // 场景列表
  3056. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  3057. $pdf->SetFont('dejavusans', 'B', 14);
  3058. $pdf->Cell(0, 10, '场景列表', 0, 1);
  3059. $pdf->SetFont('dejavusans', '', 12);
  3060. foreach ($script['scenes'] as $index => $scene) {
  3061. if (is_array($scene) || is_object($scene)) {
  3062. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  3063. } else {
  3064. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  3065. }
  3066. }
  3067. $pdf->Ln(5);
  3068. }
  3069. // 分集内容
  3070. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  3071. $pdf->SetFont('dejavusans', 'B', 16);
  3072. $pdf->Cell(0, 12, '分集内容', 0, 1);
  3073. $pdf->Ln(3);
  3074. foreach ($script['episodes'] as $episode) {
  3075. // 检查是否需要新页面
  3076. if ($pdf->GetY() > 250) {
  3077. $pdf->AddPage();
  3078. }
  3079. $pdf->SetFont('dejavusans', 'B', 14);
  3080. $episodeTitle = '第' . $episode['episode_number'] . '集';
  3081. if (!empty($episode['title'])) {
  3082. $episodeTitle .= ':' . $episode['title'];
  3083. }
  3084. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  3085. // 处理分段内容
  3086. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  3087. $pdf->SetFont('dejavusans', '', 12);
  3088. foreach ($episode['segments'] as $segment) {
  3089. if (!empty($segment['segment_content'])) {
  3090. // 如果有分段编号,显示分段标题
  3091. if (!empty($segment['segment_number'])) {
  3092. $pdf->SetFont('dejavusans', 'B', 12);
  3093. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  3094. $pdf->SetFont('dejavusans', '', 12);
  3095. }
  3096. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  3097. $pdf->Ln(2);
  3098. }
  3099. }
  3100. }
  3101. $pdf->Ln(5);
  3102. }
  3103. }
  3104. }
  3105. /**
  3106. * 构建剧本文本内容
  3107. */
  3108. private function buildScriptContent($script) {
  3109. $content = '';
  3110. $groups = $script['group'];
  3111. $groups = (array)$groups;
  3112. foreach ($groups as $group) {
  3113. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  3114. // 剧本基本信息
  3115. if (!empty($group['intro'])) {
  3116. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  3117. }
  3118. if (!empty($group['highlights'])) {
  3119. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  3120. }
  3121. if (!empty($group['role_relationship'])) {
  3122. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  3123. }
  3124. if (!empty($group['core_contradiction'])) {
  3125. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  3126. }
  3127. if (!empty($group['roles']) && is_array($group['roles'])) {
  3128. $content .= "###主体列表\n";
  3129. foreach ($group['roles'] as $role) {
  3130. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  3131. }
  3132. $content .= "\n\n";
  3133. }
  3134. if (!empty($group['art_style'])) {
  3135. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  3136. }
  3137. // 场景信息
  3138. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3139. $content .= "###场景列表\n";
  3140. foreach ($group['scenes'] as $scene) {
  3141. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  3142. }
  3143. $content .= "\n\n";
  3144. }
  3145. // 分集内容
  3146. if (!empty($group['episode_content'])) {
  3147. $content .= "###分集剧本\n";
  3148. $content .= $group['episode_content'];
  3149. // foreach ($script['episodes'] as $episode) {
  3150. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  3151. // // if (!empty($episode['episode_name'])) {
  3152. // // $content .= ":" . $episode['episode_name'];
  3153. // // }
  3154. // // $content .= "\n";
  3155. // $content .= $episode['episode_content'] . "\n\n";
  3156. // }
  3157. }
  3158. }
  3159. return $content;
  3160. }
  3161. /**
  3162. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3163. *
  3164. * @param array $data 包含以下参数:
  3165. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3166. * - question: 用户问题(可选)
  3167. * - model: 使用的模型(r1 或 v3,默认 v3)
  3168. * @return \Generator 返回生成器,用于流式输出
  3169. */
  3170. public function addChat($data) {
  3171. $uid = Site::getUid();
  3172. $anime_id = getProp($data, 'anime_id');
  3173. if (!$anime_id) Utils::throwError('20003:请选择对话');
  3174. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3175. if (!$anime) Utils::throwError('20003:对话不存在');
  3176. $file = getProp($data, 'file');
  3177. $content = getProp($data, 'content', '');
  3178. $bid = getProp($data, 'bid', 0);
  3179. $script_id = getProp($data, 'script_id', 0);
  3180. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  3181. $prompt = getProp($data, 'prompt');
  3182. $user_anime_name = getProp($anime, 'anime_name');
  3183. // 处理文本模型
  3184. $model = getProp($data, 'model');
  3185. if (!$model) {
  3186. // 用户没有输入,从anime表获取
  3187. $model = getProp($anime, 'model');
  3188. if (!$model) {
  3189. // anime表也没有,使用默认值
  3190. $model = 'doubao-seed-2-0-mini-260215';
  3191. }
  3192. }
  3193. // 验证模型是否在可用模型表中
  3194. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3195. $model = 'doubao-seed-2-0-mini-260215';
  3196. }
  3197. $is_multi = getProp($anime, 'is_multi');
  3198. $is_single = (int)$is_multi !== 1;
  3199. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3200. if ($prompt) {
  3201. $question .= "本次修改要求如下:\n{$prompt}";
  3202. }
  3203. // if (!$file && !$content && !$bid) {
  3204. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3205. // }
  3206. // 提取文件内容
  3207. if ($file) {
  3208. $content = $this->extractFileContent($file);
  3209. if (!$content) {
  3210. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3211. }
  3212. } elseif ($script_id) {
  3213. $content = $this->getContentByScriptId($script_id);
  3214. if (!$content) {
  3215. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3216. }
  3217. } elseif ($bid) {
  3218. $content = $this->getContentByBid($bid);
  3219. if (!$content) {
  3220. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3221. }
  3222. } elseif ($content) {
  3223. $content = filterContent($content);
  3224. } else {
  3225. $content = getProp($anime, 'content');
  3226. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3227. $need_generate_content = true;
  3228. }
  3229. }
  3230. // 美术风格
  3231. $input_art_style = getProp($data, 'art_style');
  3232. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3233. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3234. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3235. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3236. 中年女:邻居阿姨
  3237. 老年男:幽默大爷
  3238. 老年女:婆婆
  3239. 萌娃:奶气萌娃";
  3240. // 判断是否需要生成原文内容
  3241. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3242. // 如果需要生成原文内容,添加额外的要求
  3243. $content_generation_requirement = $need_generate_content
  3244. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3245. : "";
  3246. // 美术风格
  3247. if (!$mappedArtStyle) {
  3248. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3249. }else {
  3250. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3251. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3252. }else {
  3253. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3254. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3255. }
  3256. }
  3257. $systemPrompt = $is_single
  3258. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3259. 强制要求:
  3260. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3261. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3262. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3263. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3264. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3265. 普通要求:
  3266. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3267. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3268. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  3269. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3270. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3271. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3272. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3273. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3274. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3275. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3276. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3277. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3278. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3279. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3280. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3281. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3282. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3283. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3284. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3285. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3286. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3287. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3288. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3289. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3290. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3291. 5.{$mappedArtStyle_prompt}\n\n
  3292. 示例如下:\n
  3293. ###剧本名:西昆仑
  3294. ###故事梗概
  3295. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3296. ###剧本亮点
  3297. 亮点1:绝境奇药,生死一线
  3298. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3299. 亮点2:结拜兄妹,化解尴尬
  3300. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3301. 亮点3:纤发夺命,情愫暗涌
  3302. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3303. ###人物关系
  3304. 阿雪与梁萧之间存在兄妹之情。
  3305. ###核心矛盾
  3306. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3307. ###主体列表
  3308. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3309. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3310. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3311. 姿态:站立。}{{甜心小美}}
  3312. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3313. 全景,正面拍摄,青年女性,亚洲人。
  3314. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3315. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3316. 姿态:站立。}{{阳光青年}}
  3317. ###美术风格
  3318. 基础画风风格词:厚涂古风
  3319. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3320. ###场景列表
  3321. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3322. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3323. 无人物。}
  3324. ###分镜剧本
  3325. ##第1幕:徐家老旧厨房 白天 室内
  3326. 分镜1
  3327. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3328. 场景:徐家老旧厨房
  3329. 构图设计:全景,低角度仰视
  3330. 运镜调度:手持拍摄
  3331. 配音角色:旁白
  3332. 出镜角色:许芸-校服装、徐母
  3333. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3334. 画面类型:普通画面
  3335. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3336. 分镜2
  3337. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3338. 场景:徐家老旧厨房
  3339. 构图设计:近景,徐母面部特写
  3340. 运镜调度:固定镜头
  3341. 配音角色:徐母
  3342. 出镜角色:徐母
  3343. 台词内容:问我夜不归宿死哪儿去了。
  3344. 画面类型:对口型
  3345. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3346. ##第2幕:徐家简陋客厅 黄昏 室内
  3347. 分镜3
  3348. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3349. 场景:徐家简陋客厅
  3350. 构图设计:全景,景深虚化
  3351. 运镜调度:固定镜头
  3352. 配音角色:旁白
  3353. 出镜角色:无
  3354. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3355. 画面类型:普通画面
  3356. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3357. 分镜4
  3358. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3359. 场景:徐家简陋客厅
  3360. 构图设计:特写,火车票
  3361. 运镜调度:固定镜头
  3362. 配音角色:旁白
  3363. 出镜角色:无
  3364. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3365. 画面类型:普通画面
  3366. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  3367. "
  3368. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3369. 强制要求:\n
  3370. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3371. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3372. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3373. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3374. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3375. 普通要求:\n
  3376. 1.剧本名(必须生成)必须与文档内容高度相关
  3377. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3378. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3379. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3380. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3381. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3382. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3383. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3384. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3385. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3386. 4.{$mappedArtStyle_prompt}\n\n
  3387. 示例如下:\n
  3388. ###剧本名:西昆仑
  3389. ###故事梗概
  3390. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3391. ###剧本亮点
  3392. 亮点1:绝境奇药,生死一线
  3393. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3394. 亮点2:结拜兄妹,化解尴尬
  3395. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3396. 亮点3:纤发夺命,情愫暗涌
  3397. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3398. ###人物关系
  3399. 阿雪与梁萧之间存在兄妹之情。
  3400. ###核心矛盾
  3401. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3402. ###主体列表
  3403. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3404. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3405. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3406. 姿态:站立。}{{甜心小美}}
  3407. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3408. 全景,正面拍摄,青年女性,亚洲人。
  3409. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3410. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3411. 姿态:站立。}{{阳光青年}}
  3412. ###美术风格
  3413. 基础画风风格词:厚涂古风
  3414. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3415. ###场景列表
  3416. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3417. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3418. 无人物。}";
  3419. // 构建消息
  3420. $messages = [
  3421. [
  3422. 'role' => 'system',
  3423. 'content' => $systemPrompt
  3424. ],
  3425. [
  3426. 'role' => 'user',
  3427. 'content' => "以下是文档内容:
  3428. {$content}
  3429. 用户问题:
  3430. {$question}"
  3431. ]
  3432. ];
  3433. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3434. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3435. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3436. if ($model === 'deepseek-chat') {
  3437. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3438. $model = 'deepseek-v4-flash';
  3439. $thinkingMode = 'disabled';
  3440. } elseif ($model === 'deepseek-reasoner') {
  3441. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3442. $model = 'deepseek-v4-flash';
  3443. $thinkingMode = 'enabled';
  3444. }
  3445. $post_data = [
  3446. 'model' => $model,
  3447. 'messages' => $messages,
  3448. // 'max_tokens' => 8192,
  3449. 'temperature' => 0.7,
  3450. 'frequency_penalty' => 0,
  3451. 'presence_penalty' => 0,
  3452. 'response_format' => ['type' => 'text'],
  3453. 'thinking' => ['type'=>$thinkingMode],
  3454. 'stream' => true // 启用流式输出
  3455. ];
  3456. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3457. // 根据模型类型选择调用方法
  3458. $fullContent = '';
  3459. $fullReasoningContent = '';
  3460. $usage = [];
  3461. try {
  3462. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3463. // DeepSeek 官方模型使用 DeepSeek API
  3464. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3465. } else if (in_array($model, $this->gpt_text_models)) {
  3466. // GPT-5.4 模型使用 TokenRouter API
  3467. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3468. } else {
  3469. // 其他模型使用火山引擎API
  3470. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3471. }
  3472. // 验证返回值类型
  3473. if (!is_iterable($streamGenerator)) {
  3474. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  3475. dLog('deepseek')->error('addChat流式生成器无效', [
  3476. 'generator_type' => $errorType,
  3477. 'model' => $model,
  3478. 'anime_id' => $anime_id
  3479. ]);
  3480. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  3481. 'type' => $errorType,
  3482. 'model' => $model
  3483. ]);
  3484. yield [
  3485. 'type' => 'error',
  3486. 'script' => [],
  3487. 'episode' => [],
  3488. 'answer' => '',
  3489. 'reasoning' => '',
  3490. 'usage' => [],
  3491. 'error' => '接口返回数据异常,请重新请求'
  3492. ];
  3493. return;
  3494. }
  3495. // 处理流式输出
  3496. foreach ($streamGenerator as $chunk) {
  3497. if (isset($chunk['type'])) {
  3498. if ($chunk['type'] === 'done') {
  3499. // 最终结果
  3500. $fullContent = $chunk['full_content'];
  3501. $fullReasoningContent = $chunk['full_reasoning'];
  3502. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3503. } else {
  3504. // 逐块yield数据
  3505. yield $chunk;
  3506. }
  3507. }
  3508. }
  3509. } catch (\Exception $e) {
  3510. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  3511. 'model' => $model,
  3512. 'anime_id' => $anime_id,
  3513. 'trace' => $e->getTraceAsString()
  3514. ]);
  3515. logDB('deepseek', 'error', 'addChat流式处理失败', [
  3516. 'error' => $e->getMessage(),
  3517. 'model' => $model
  3518. ]);
  3519. yield [
  3520. 'type' => 'error',
  3521. 'script' => [],
  3522. 'episode' => [],
  3523. 'answer' => '',
  3524. 'reasoning' => '',
  3525. 'usage' => [],
  3526. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  3527. ];
  3528. return;
  3529. }
  3530. dLog('deepseek')->info('完整内容: '.$fullContent);
  3531. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3532. // 处理完整内容并返回最终结果
  3533. $script_arr = [];
  3534. if ($fullContent) {
  3535. $script_arr = handleScriptContent($fullContent);
  3536. dLog('deepseek')->info('解析内容', $script_arr);
  3537. logDB('deepseek', 'info', '解析内容', $script_arr);
  3538. }
  3539. if (empty($script_arr['roles'])) {
  3540. // 未生成剧本相关内容,保存对话记录并返回提示
  3541. dLog('deepseek')->info('未生成剧本相关的内容');
  3542. try {
  3543. DB::beginTransaction();
  3544. $now = date('Y-m-d H:i:s');
  3545. // 保存对话记录
  3546. $records = [
  3547. [
  3548. 'uid' => $uid,
  3549. 'anime_id' => $anime_id,
  3550. 'sequence' => 0,
  3551. 'role' => 'user',
  3552. 'content' => $prompt,
  3553. 'created_at' => $now,
  3554. 'updated_at' => $now
  3555. ],
  3556. [
  3557. 'uid' => $uid,
  3558. 'anime_id' => $anime_id,
  3559. 'sequence' => 0,
  3560. 'role' => 'assistant',
  3561. // 'content' => $fullContent,
  3562. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  3563. 'created_at' => $now,
  3564. 'updated_at' => $now
  3565. ]
  3566. ];
  3567. DB::table('mp_anime_records')->insert($records);
  3568. DB::commit();
  3569. } catch (\Exception $e) {
  3570. DB::rollBack();
  3571. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3572. }
  3573. yield [
  3574. 'type' => 'done',
  3575. 'script' => [],
  3576. 'episode' => [],
  3577. 'answer' => $fullContent,
  3578. 'reasoning' => $fullReasoningContent,
  3579. 'usage' => $usage,
  3580. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  3581. ];
  3582. return;
  3583. }
  3584. // 如果需要生成原文内容,从script_arr中提取
  3585. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  3586. $content = $script_arr['content'];
  3587. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  3588. if (!$content) {
  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. }
  3601. // 替换美术风格
  3602. if ($mappedArtStyle !== '') {
  3603. $script_arr['art_style'] = $mappedArtStyle;
  3604. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  3605. }
  3606. // 新建动漫
  3607. if ($user_anime_name == '新剧本策划') {
  3608. $anime_name = getProp($script_arr, 'script_name');
  3609. // if (!$anime_name) {
  3610. // // 未识别到剧本名,保存对话记录并返回提示
  3611. // dLog('deepseek')->info('未能识别到剧本名称');
  3612. // try {
  3613. // DB::beginTransaction();
  3614. // $now = date('Y-m-d H:i:s');
  3615. // // 保存对话记录
  3616. // $records = [
  3617. // [
  3618. // 'uid' => $uid,
  3619. // 'anime_id' => $anime_id,
  3620. // 'sequence' => 0,
  3621. // 'role' => 'user',
  3622. // 'content' => $prompt,
  3623. // 'created_at' => $now,
  3624. // 'updated_at' => $now
  3625. // ],
  3626. // [
  3627. // 'uid' => $uid,
  3628. // 'anime_id' => $anime_id,
  3629. // 'sequence' => 0,
  3630. // 'role' => 'assistant',
  3631. // 'content' => '未能生成剧本名称,请重试',
  3632. // 'created_at' => $now,
  3633. // 'updated_at' => $now
  3634. // ]
  3635. // ];
  3636. // DB::table('mp_anime_records')->insert($records);
  3637. // DB::commit();
  3638. // } catch (\Exception $e) {
  3639. // DB::rollBack();
  3640. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3641. // }
  3642. // yield [
  3643. // 'type' => 'done',
  3644. // 'script' => [],
  3645. // 'episode' => [],
  3646. // 'answer' => $fullContent,
  3647. // 'reasoning' => $fullReasoningContent,
  3648. // 'usage' => $usage,
  3649. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  3650. // ];
  3651. // return;
  3652. // }
  3653. // 确认对话名称唯一性
  3654. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  3655. $anime_name = $anime_name . '_' . date('YmdHis');
  3656. }
  3657. }else {
  3658. $anime_name = $user_anime_name;
  3659. }
  3660. $table_data = [
  3661. 'user_id' => $uid,
  3662. 'anime_name' => $anime_name,
  3663. 'model' => $model,
  3664. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3665. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3666. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3667. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3668. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3669. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3670. 'art_style_type' => $input_art_style,
  3671. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3672. 'status' => '解析完成',
  3673. 'content' => $content,
  3674. 'is_multi' => $is_multi,
  3675. 'ace_mode' => $ace_mode,
  3676. 'generate_status' => '待执行',
  3677. 'updated_at' => date('Y-m-d H:i:s')
  3678. ];
  3679. if ($table_data['content']) {
  3680. $chapters = splitContent($table_data['content']);
  3681. $chapter_count = count($chapters);
  3682. if ($chapter_count > 0) {
  3683. $table_data['start_episode_sequence'] = 1;
  3684. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  3685. }
  3686. }
  3687. // 如果有剧本ID则进行绑定
  3688. if ($script_id) {
  3689. $table_data['script_id'] = $script_id;
  3690. }
  3691. $single_episode = [];
  3692. try {
  3693. DB::beginTransaction();
  3694. $now = date('Y-m-d H:i:s');
  3695. // 更新动漫大纲
  3696. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3697. if (!$boolen) {
  3698. dLog('deepseek')->info('动漫保存失败', $table_data);
  3699. Utils::throwError('20003:动漫保存失败');
  3700. }
  3701. // 保存对话记录
  3702. $records = [
  3703. [
  3704. 'uid' => $uid,
  3705. 'anime_id' => $anime_id,
  3706. 'sequence' => 0,
  3707. 'role' => 'user',
  3708. 'content' => $prompt,
  3709. 'created_at' => date('Y-m-d H:i:s'),
  3710. 'updated_at' => date('Y-m-d H:i:s')
  3711. ],
  3712. [
  3713. 'uid' => $uid,
  3714. 'anime_id' => $anime_id,
  3715. 'sequence' => 0,
  3716. 'role' => 'assistant',
  3717. 'content' => $fullContent,
  3718. 'created_at' => date('Y-m-d H:i:s'),
  3719. 'updated_at' => date('Y-m-d H:i:s')
  3720. ]
  3721. ];
  3722. // 保存对话记录
  3723. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3724. if (!$boolen3) {
  3725. Utils::throwError('20003:对话记录保存失败');
  3726. }
  3727. if ($is_single) {
  3728. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3729. if (empty($episode_arr['acts'])) {
  3730. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3731. }
  3732. $saveResult = $this->saveEpisodeVersionData(
  3733. $anime_id,
  3734. 1,
  3735. $episode_arr,
  3736. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3737. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3738. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  3739. null,
  3740. null,
  3741. false,
  3742. $content,
  3743. $now
  3744. );
  3745. $single_episode = $saveResult['episode'];
  3746. $episode_id = $saveResult['episode_id'];
  3747. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3748. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3749. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3750. 'props' => json_encode($saveResult['merged_props'], 256),
  3751. 'updated_at' => $now
  3752. ]);
  3753. if ($boolen5 === false) {
  3754. Utils::throwError('20003:单剧集主表资源同步失败');
  3755. }
  3756. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3757. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3758. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  3759. $episode_record_content = '确认分镜大纲';
  3760. if ($content !== '') {
  3761. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  3762. }
  3763. $episode_records = [
  3764. [
  3765. 'uid' => $uid,
  3766. 'anime_id' => $anime_id,
  3767. 'role' => 'user',
  3768. 'content' => $episode_record_content,
  3769. 'sequence' => 1,
  3770. 'episode_id' => $episode_id,
  3771. 'created_at' => $now,
  3772. 'updated_at' => $now
  3773. ],
  3774. [
  3775. 'uid' => $uid,
  3776. 'anime_id' => $anime_id,
  3777. 'role' => 'assistant',
  3778. 'content' => $fullContent,
  3779. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3780. 'sequence' => 1,
  3781. 'episode_id' => $episode_id,
  3782. 'created_at' => $now,
  3783. 'updated_at' => $now
  3784. ]
  3785. ];
  3786. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3787. if (!$boolen4) {
  3788. Utils::throwError('20003:单剧集分镜记录保存失败');
  3789. }
  3790. }
  3791. }catch (\Exception $e) {
  3792. DB::rollBack();
  3793. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  3794. yield [
  3795. 'type' => 'done',
  3796. 'answer' => $fullContent,
  3797. 'reasoning' => $fullReasoningContent,
  3798. 'usage' => $usage,
  3799. 'error' => $e->getMessage(),
  3800. ];
  3801. return;
  3802. }
  3803. DB::commit();
  3804. dLog('deepseek')->info('保存完毕');
  3805. if ($is_single && !empty($single_episode)) {
  3806. // $this->batchSetGlobalRoleImg([
  3807. // 'anime_id' => $anime_id,
  3808. // ]);
  3809. // $this->batchSetGlobalSceneImg([
  3810. // 'anime_id' => $anime_id,
  3811. // ]);
  3812. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  3813. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  3814. }
  3815. $table_data['anime_id'] = $anime_id;
  3816. $table_data['roles'] = json_decode($table_data['roles'], true);
  3817. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  3818. // $table_data['episodes'] = $script_arr['episodes'];
  3819. unset($table_data['created_at']);
  3820. unset($table_data['updated_at']);
  3821. unset($table_data['status']);
  3822. dLog('deepseek')->info('开始返回');
  3823. yield [
  3824. 'type' => 'done',
  3825. 'script' => $table_data,
  3826. 'episode' => $single_episode,
  3827. 'answer' => $fullContent,
  3828. 'reasoning' => $fullReasoningContent,
  3829. 'usage' => $usage
  3830. ];
  3831. }
  3832. public function reGenerateAnime($data) {
  3833. $uid = Site::getUid();
  3834. $file = getProp($data, 'file');
  3835. $content = getProp($data, 'content', '');
  3836. $bid = getProp($data, 'bid', 0);
  3837. $script_id = getProp($data, 'script_id', 0);
  3838. $anime_id = getProp($data, 'anime_id');
  3839. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3840. if (!$anime) {
  3841. Utils::throwError('20003:该对话不存在');
  3842. }
  3843. $user_anime_name = getProp($anime, 'anime_name');
  3844. $prompt = getProp($data, 'prompt');
  3845. // 处理文本模型
  3846. $model = getProp($data, 'model');
  3847. if (!$model) {
  3848. // 用户没有输入,从anime表获取
  3849. $model = getProp($anime, 'model');
  3850. if (!$model) {
  3851. // anime表也没有,使用默认值
  3852. $model = 'doubao-seed-2-0-mini-260215';
  3853. }
  3854. }
  3855. // 验证模型是否在可用模型表中
  3856. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3857. $model = 'doubao-seed-2-0-mini-260215';
  3858. }
  3859. $is_multi = getProp($anime, 'is_multi', 1);
  3860. $is_single = (int)$is_multi !== 1;
  3861. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  3862. if ($is_single) {
  3863. $episode_exists = DB::table('mp_anime_episodes')
  3864. ->where('anime_id', $anime_id)
  3865. ->where('sequence', 1)
  3866. ->exists();
  3867. if ($episode_exists) {
  3868. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  3869. }
  3870. }
  3871. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3872. if ($prompt) {
  3873. $question .= "本次修改要求如下:\n{$prompt}";
  3874. }
  3875. // 提取文件内容
  3876. if ($file) {
  3877. $content = $this->extractFileContent($file);
  3878. if (!$content) {
  3879. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3880. }
  3881. } elseif ($script_id) {
  3882. $content = $this->getContentByScriptId($script_id);
  3883. if (!$content) {
  3884. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3885. }
  3886. } elseif ($bid) {
  3887. $content = $this->getContentByBid($bid);
  3888. if (!$content) {
  3889. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3890. }
  3891. } elseif ($content) {
  3892. $content = filterContent($content);
  3893. }else {
  3894. $content = filterContent(getProp($anime, 'content'));
  3895. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3896. $need_generate_content = true;
  3897. }
  3898. }
  3899. // 判断是否需要生成原文内容
  3900. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3901. // 如果需要生成原文内容,添加额外的要求
  3902. $content_generation_requirement = $need_generate_content
  3903. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3904. : "";
  3905. // 美术风格
  3906. $input_art_style = getProp($anime, 'art_style');
  3907. if (!$input_art_style) {
  3908. $input_art_style = getProp($data, 'art_style');
  3909. }
  3910. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3911. // 美术风格
  3912. if (!$mappedArtStyle) {
  3913. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3914. }else {
  3915. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3916. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3917. }else {
  3918. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3919. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3920. }
  3921. }
  3922. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3923. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3924. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3925. 中年女:邻居阿姨
  3926. 老年男:幽默大爷
  3927. 老年女:婆婆
  3928. 萌娃:奶气萌娃";
  3929. $system_message = ['role'=>'system', 'content'=>$is_single
  3930. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3931. 强制要求:
  3932. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3933. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3934. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3935. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3936. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3937. 普通要求:
  3938. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3939. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3940. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3941. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3942. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3943. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3944. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3945. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3946. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3947. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3948. 3.$mappedArtStyle_prompt\n\n
  3949. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3950. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3951. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3952. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3953. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3954. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3955. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3956. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3957. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3958. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3959. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3960. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3961. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3962. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3963. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3964. 示例如下:\n
  3965. ###剧本名:西昆仑
  3966. ###故事梗概
  3967. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3968. ###剧本亮点
  3969. 亮点1:绝境奇药,生死一线
  3970. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3971. 亮点2:结拜兄妹,化解尴尬
  3972. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3973. 亮点3:纤发夺命,情愫暗涌
  3974. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3975. ###人物关系
  3976. 阿雪与梁萧之间存在兄妹之情。
  3977. ###核心矛盾
  3978. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3979. ###主体列表
  3980. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3981. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3982. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3983. 姿态:站立。}{{甜心小美}}
  3984. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3985. 全景,正面拍摄,青年女性,亚洲人。
  3986. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3987. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3988. 姿态:站立。}{{阳光青年}}
  3989. ###美术风格
  3990. 基础画风风格词:厚涂古风
  3991. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3992. ###场景列表
  3993. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3994. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3995. 无人物。}
  3996. ###分镜剧本
  3997. ##第1幕:徐家老旧厨房 白天 室内
  3998. 分镜1
  3999. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4000. 场景:徐家老旧厨房
  4001. 构图设计:全景,低角度仰视
  4002. 运镜调度:手持拍摄
  4003. 配音角色:旁白
  4004. 出镜角色:许芸-校服装、徐母
  4005. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4006. 画面类型:普通画面
  4007. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4008. 分镜2
  4009. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4010. 场景:徐家老旧厨房
  4011. 构图设计:近景,徐母面部特写
  4012. 运镜调度:固定镜头
  4013. 配音角色:徐母
  4014. 出镜角色:徐母
  4015. 台词内容:问我夜不归宿死哪儿去了。
  4016. 画面类型:对口型
  4017. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4018. ##第2幕:徐家简陋客厅 黄昏 室内
  4019. 分镜3
  4020. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4021. 场景:徐家简陋客厅
  4022. 构图设计:全景,景深虚化
  4023. 运镜调度:固定镜头
  4024. 配音角色:旁白
  4025. 出镜角色:无
  4026. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4027. 画面类型:普通画面
  4028. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4029. 分镜4
  4030. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4031. 场景:徐家简陋客厅
  4032. 构图设计:特写,火车票
  4033. 运镜调度:固定镜头
  4034. 配音角色:旁白
  4035. 出镜角色:无
  4036. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4037. 画面类型:普通画面
  4038. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4039. "
  4040. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4041. 强制要求:\n
  4042. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4043. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4044. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4045. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4046. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4047. 普通要求:\n
  4048. 1.剧本名(必须生成)必须与文档内容高度相关
  4049. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4050. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4051. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4052. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4053. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4054. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4055. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4056. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4057. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4058. 4.$mappedArtStyle_prompt\n\n
  4059. 示例如下:\n
  4060. ###剧本名:西昆仑
  4061. ###故事梗概
  4062. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4063. ###剧本亮点
  4064. 亮点1:绝境奇药,生死一线
  4065. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4066. 亮点2:结拜兄妹,化解尴尬
  4067. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4068. 亮点3:纤发夺命,情愫暗涌
  4069. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4070. ###人物关系
  4071. 阿雪与梁萧之间存在兄妹之情。
  4072. ###核心矛盾
  4073. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4074. ###主体列表
  4075. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4076. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4077. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4078. 姿态:站立。}{{甜心小美}}
  4079. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4080. 全景,正面拍摄,青年女性,亚洲人。
  4081. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4082. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4083. 姿态:站立。}{{阳光青年}}
  4084. ###美术风格
  4085. 基础画风风格词:厚涂古风
  4086. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4087. ###场景列表
  4088. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4089. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4090. 无人物。}"];
  4091. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  4092. $episode_count = $this->extractEpisodeNumber($prompt);
  4093. if ((int)getProp($anime, 'is_multi') !== 1) {
  4094. yield [
  4095. 'type' => 'done',
  4096. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  4097. 'reasoning' => '',
  4098. 'usage' => []
  4099. ];
  4100. return;
  4101. }
  4102. if ($episode_count) {
  4103. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  4104. $system_message = [
  4105. 'role' => 'system',
  4106. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4107. 强制要求:\n
  4108. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4109. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4110. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4111. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4112. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4113. 普通要求:\n
  4114. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4115. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4116. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4117. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4118. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4119. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4120. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4121. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4122. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4123. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  4124. 示例如下:\n
  4125. ###剧本名:西昆仑
  4126. ###故事梗概
  4127. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4128. ###剧本亮点
  4129. 亮点1:绝境奇药,生死一线
  4130. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4131. 亮点2:结拜兄妹,化解尴尬
  4132. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4133. 亮点3:纤发夺命,情愫暗涌
  4134. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4135. ###人物关系
  4136. 阿雪与梁萧之间存在兄妹之情。
  4137. ###核心矛盾
  4138. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4139. ###主体列表
  4140. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4141. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4142. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4143. 姿态:站立。}{{甜心小美}}
  4144. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4145. 全景,正面拍摄,青年女性,亚洲人。
  4146. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4147. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4148. 姿态:站立。}{{阳光青年}}
  4149. ###美术风格
  4150. 基础画风风格词:厚涂古风
  4151. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4152. ###场景列表
  4153. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4154. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4155. 无人物。}
  4156. ###分集详细内容
  4157. ##第1章 重生
  4158. 我重生了。
  4159. 源于一个男人偏执的暗恋。
  4160. ##第2章 相救
  4161. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  4162. 我眼睛扫向站在锅炉后的卞大伟。"
  4163. ];
  4164. // 构建消息
  4165. $messages = [
  4166. $system_message,
  4167. [
  4168. 'role' => 'user',
  4169. 'content' => "以下是文档内容:
  4170. {$content}
  4171. 用户问题:
  4172. {$question}"
  4173. ]
  4174. ];
  4175. }else {
  4176. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  4177. // 构建消息
  4178. $messages = [
  4179. $system_message,
  4180. [
  4181. 'role' => 'user',
  4182. 'content' => "以下是文档内容:
  4183. {$content}
  4184. 用户问题:
  4185. {$question}"
  4186. ]
  4187. ];
  4188. }else {
  4189. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  4190. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  4191. return (array)$value;
  4192. })->toArray();
  4193. array_unshift($messages, $system_message);
  4194. $messages[] = [
  4195. 'role' => 'user',
  4196. 'content' => $prompt
  4197. ];
  4198. }
  4199. }
  4200. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4201. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4202. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4203. if ($model === 'deepseek-chat') {
  4204. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4205. $model = 'deepseek-v4-flash';
  4206. $thinkingMode = 'disabled';
  4207. } elseif ($model === 'deepseek-reasoner') {
  4208. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4209. $model = 'deepseek-v4-flash';
  4210. $thinkingMode = 'enabled';
  4211. }
  4212. $post_data = [
  4213. 'model' => $model,
  4214. 'messages' => $messages,
  4215. // 'max_tokens' => 8192,
  4216. 'temperature' => 0.7,
  4217. 'frequency_penalty' => 0,
  4218. 'presence_penalty' => 0,
  4219. 'response_format' => ['type' => 'text'],
  4220. 'thinking' => ['type' => $thinkingMode],
  4221. 'stream' => true // 启用流式输出
  4222. ];
  4223. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4224. // 根据模型类型选择调用方法
  4225. $fullContent = '';
  4226. $fullReasoningContent = '';
  4227. $usage = [];
  4228. // dd($post_data);
  4229. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  4230. try {
  4231. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4232. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4233. } else if (in_array($model, $this->gpt_text_models)) {
  4234. // GPT-5.4 模型使用 TokenRouter API
  4235. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4236. } else {
  4237. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4238. }
  4239. // 验证返回值类型
  4240. if (!is_iterable($streamGenerator)) {
  4241. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4242. dLog('deepseek')->error('方法名流式生成器无效', [
  4243. 'generator_type' => $errorType,
  4244. 'model' => $model,
  4245. // 添加其他上下文信息
  4246. ]);
  4247. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  4248. 'type' => $errorType,
  4249. 'model' => $model
  4250. ]);
  4251. yield [
  4252. 'type' => 'error',
  4253. // 根据方法返回相应的空数据结构
  4254. 'answer' => '',
  4255. 'reasoning' => '',
  4256. 'usage' => [],
  4257. 'error' => '接口返回数据异常,请重新请求'
  4258. ];
  4259. return;
  4260. }
  4261. // 处理流式输出
  4262. foreach ($streamGenerator as $chunk) {
  4263. if (isset($chunk['type'])) {
  4264. if ($chunk['type'] === 'done') {
  4265. $fullContent = $chunk['full_content'];
  4266. $fullReasoningContent = $chunk['full_reasoning'];
  4267. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4268. } else {
  4269. yield $chunk;
  4270. }
  4271. }
  4272. }
  4273. } catch (\Exception $e) {
  4274. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  4275. 'model' => $model,
  4276. 'trace' => $e->getTraceAsString()
  4277. ]);
  4278. logDB('deepseek', 'error', '方法名流式处理失败', [
  4279. 'error' => $e->getMessage(),
  4280. 'model' => $model
  4281. ]);
  4282. yield [
  4283. 'type' => 'error',
  4284. // 根据方法返回相应的空数据结构
  4285. 'answer' => '',
  4286. 'reasoning' => '',
  4287. 'usage' => [],
  4288. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4289. ];
  4290. return;
  4291. }
  4292. dLog('deepseek')->info('完整内容: '.$fullContent);
  4293. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4294. // 处理完整内容并返回最终结果
  4295. $script_arr = [];
  4296. if ($fullContent) {
  4297. $script_arr = handleScriptContent($fullContent);
  4298. dLog('deepseek')->info('解析内容', $script_arr);
  4299. logDB('deepseek', 'info', '解析内容', $script_arr);
  4300. }
  4301. if (empty($script_arr['roles'])) {
  4302. // 未生成剧本相关内容,保存对话记录并返回提示
  4303. dLog('deepseek')->info('未生成剧本相关的内容');
  4304. try {
  4305. $now = date('Y-m-d H:i:s');
  4306. // 保存对话记录
  4307. $records = [
  4308. [
  4309. 'uid' => $uid,
  4310. 'anime_id' => $anime_id,
  4311. 'sequence' => 0,
  4312. 'role' => 'user',
  4313. 'content' => $prompt,
  4314. 'created_at' => $now,
  4315. 'updated_at' => $now
  4316. ],
  4317. [
  4318. 'uid' => $uid,
  4319. 'anime_id' => $anime_id,
  4320. 'sequence' => 0,
  4321. 'role' => 'assistant',
  4322. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  4323. 'created_at' => $now,
  4324. 'updated_at' => $now
  4325. ]
  4326. ];
  4327. DB::table('mp_anime_records')->insert($records);
  4328. } catch (\Exception $e) {
  4329. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4330. }
  4331. yield [
  4332. 'type' => 'done',
  4333. 'script' => [],
  4334. 'episode' => [],
  4335. 'answer' => $fullContent,
  4336. 'reasoning' => $fullReasoningContent,
  4337. 'usage' => $usage,
  4338. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4339. ];
  4340. return;
  4341. }
  4342. // 替换美术风格
  4343. if ($mappedArtStyle !== '') {
  4344. $script_arr['art_style'] = $mappedArtStyle;
  4345. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4346. }
  4347. if ($user_anime_name != '新剧本策划') {
  4348. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  4349. // 确认对话名称唯一性
  4350. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4351. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  4352. }
  4353. }else {
  4354. $anime_name = $user_anime_name;
  4355. }
  4356. $table_data = [
  4357. 'user_id' => $uid,
  4358. 'model' => $model,
  4359. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4360. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4361. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4362. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4363. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4364. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4365. 'art_style_type' => $input_art_style,
  4366. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4367. 'status' => '解析完成',
  4368. 'generate_status' => '待执行',
  4369. 'updated_at' => date('Y-m-d H:i:s')
  4370. ];
  4371. if ($anime_name) $table_data['anime_name'] = $anime_name;
  4372. // 如果是修改集数,则将content内容更新(会改变原文)
  4373. if (isset($episode_count) && $episode_count > 0) {
  4374. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  4375. $table_data['start_episode_sequence'] = 1;
  4376. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  4377. }else {
  4378. // 如果需要生成原文内容,从script_arr中提取
  4379. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4380. $table_data['content'] = $script_arr['content'];
  4381. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  4382. if (!$table_data['content']) {
  4383. yield [
  4384. 'type' => 'done',
  4385. 'script' => [],
  4386. 'episode' => [],
  4387. 'answer' => $fullContent,
  4388. 'reasoning' => $fullReasoningContent,
  4389. 'usage' => $usage,
  4390. 'error' => '未生成剧本内容,请调整提示词再试'
  4391. ];
  4392. return;
  4393. }
  4394. }
  4395. if (isset($table_data['content']) && $table_data['content']) {
  4396. $chapters = splitContent($table_data['content']);
  4397. $chapter_count = count($chapters);
  4398. if ($chapter_count > 0) {
  4399. $table_data['start_episode_sequence'] = 1;
  4400. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4401. }
  4402. }
  4403. }
  4404. $single_episode = [];
  4405. try {
  4406. DB::beginTransaction();
  4407. $now = date('Y-m-d H:i:s');
  4408. // 更新动漫大纲
  4409. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4410. if (!$boolen) {
  4411. dLog('deepseek')->info('对话修改失败', $table_data);
  4412. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  4413. Utils::throwError('20003:对话修改失败');
  4414. }
  4415. // 保存对话记录
  4416. $records = [
  4417. [
  4418. 'uid' => $uid,
  4419. 'anime_id' => $anime_id,
  4420. 'sequence' => 0,
  4421. 'role' => 'user',
  4422. 'content' => $prompt,
  4423. 'created_at' => $now,
  4424. 'updated_at' => $now
  4425. ],
  4426. [
  4427. 'uid' => $uid,
  4428. 'anime_id' => $anime_id,
  4429. 'sequence' => 0,
  4430. 'role' => 'assistant',
  4431. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4432. 'content' => $fullContent,
  4433. 'created_at' => $now,
  4434. 'updated_at' => $now
  4435. ]
  4436. ];
  4437. // 保存对话记录
  4438. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4439. if (!$boolen3) {
  4440. Utils::throwError('20003:对话记录保存失败');
  4441. }
  4442. // 单剧集模式:生成并保存剧集信息
  4443. if ($is_single) {
  4444. $anime_name = getProp($anime, 'anime_name', '未命名');
  4445. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4446. if (empty($episode_arr['acts'])) {
  4447. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4448. }
  4449. $saveResult = $this->saveEpisodeVersionData(
  4450. $anime_id,
  4451. 1,
  4452. $episode_arr,
  4453. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4454. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4455. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  4456. null,
  4457. null,
  4458. false,
  4459. $content,
  4460. $now
  4461. );
  4462. $single_episode = $saveResult['episode'];
  4463. $episode_id = $saveResult['episode_id'];
  4464. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4465. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4466. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4467. 'props' => json_encode($saveResult['merged_props'], 256),
  4468. 'updated_at' => $now
  4469. ]);
  4470. if ($boolen5 === false) {
  4471. Utils::throwError('20003:单剧集主表资源同步失败');
  4472. }
  4473. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4474. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4475. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  4476. $episode_record_content = '确认分镜大纲';
  4477. if ($content !== '') {
  4478. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4479. }
  4480. $episode_records = [
  4481. [
  4482. 'uid' => $uid,
  4483. 'anime_id' => $anime_id,
  4484. 'role' => 'user',
  4485. 'content' => $episode_record_content,
  4486. 'sequence' => 1,
  4487. 'episode_id' => $episode_id,
  4488. 'created_at' => $now,
  4489. 'updated_at' => $now
  4490. ],
  4491. [
  4492. 'uid' => $uid,
  4493. 'anime_id' => $anime_id,
  4494. 'role' => 'assistant',
  4495. 'content' => $fullContent,
  4496. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4497. 'sequence' => 1,
  4498. 'episode_id' => $episode_id,
  4499. 'created_at' => $now,
  4500. 'updated_at' => $now
  4501. ]
  4502. ];
  4503. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4504. if (!$boolen4) {
  4505. Utils::throwError('20003:单剧集分镜记录保存失败');
  4506. }
  4507. }
  4508. }catch (\Exception $e) {
  4509. DB::rollBack();
  4510. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  4511. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  4512. yield [
  4513. 'type' => 'done',
  4514. 'answer' => $fullContent,
  4515. 'reasoning' => $fullReasoningContent,
  4516. 'usage' => $usage,
  4517. 'error' => $e->getMessage(),
  4518. ];
  4519. return;
  4520. }
  4521. DB::commit();
  4522. dLog('deepseek')->info('保存完毕');
  4523. if ($is_single && !empty($single_episode)) {
  4524. // $this->batchSetGlobalRoleImg([
  4525. // 'anime_id' => $anime_id,
  4526. // ]);
  4527. // $this->batchSetGlobalSceneImg([
  4528. // 'anime_id' => $anime_id,
  4529. // ]);
  4530. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4531. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4532. }
  4533. $table_data['anime_id'] = $anime_id;
  4534. $table_data['roles'] = json_decode($table_data['roles'], true);
  4535. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4536. unset($table_data['updated_at']);
  4537. unset($table_data['status']);
  4538. yield [
  4539. 'type' => 'done',
  4540. 'script' => $table_data,
  4541. 'episode' => $single_episode,
  4542. 'answer' => $fullContent,
  4543. 'reasoning' => $fullReasoningContent,
  4544. 'usage' => $usage
  4545. ];
  4546. }
  4547. public function chat($data) {
  4548. $uid = Site::getUid();
  4549. $anime_id = getProp($data, 'anime_id');
  4550. $file = getProp($data, 'file');
  4551. $content = getProp($data, 'content', '');
  4552. $bid = getProp($data, 'bid', 0);
  4553. $script_id = getProp($data, 'script_id', 0);
  4554. $episode_number = getProp($data, 'episode_number', 1);
  4555. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4556. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4557. if (!$anime) Utils::throwError('20003:该对话不存在!');
  4558. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  4559. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  4560. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  4561. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  4562. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  4563. $roles = is_array($roles) ? $roles : [];
  4564. $scenes = is_array($scenes) ? $scenes : [];
  4565. // 获取最后一集序号
  4566. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  4567. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  4568. // 转换主体列表和场景列表的格式
  4569. // 获取参考主体或场景
  4570. if ((int)$episode_number === 1) {
  4571. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  4572. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  4573. }else {
  4574. $prev_episode_number = $episode_number - 1;
  4575. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  4576. }
  4577. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  4578. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  4579. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  4580. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  4581. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4582. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4583. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4584. 中年女:邻居阿姨
  4585. 老年男:幽默大爷
  4586. 老年女:婆婆
  4587. 萌娃:奶气萌娃";
  4588. if ($roles_content) {
  4589. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  4590. 主体范围:\n {$roles_content}\n
  4591. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  4592. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4593. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4594. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4595. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4596. }else {
  4597. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4598. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4599. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4600. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4601. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4602. }
  4603. if ($scenes_content) {
  4604. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  4605. 场景范围:\n {$scenes_content}\n
  4606. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  4607. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4608. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4609. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4610. }else {
  4611. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4612. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4613. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4614. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4615. }
  4616. // 提取文件内容
  4617. if ($file) {
  4618. $uploaded_content = $this->extractFileContent($file);
  4619. if (!$uploaded_content) {
  4620. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4621. }
  4622. } elseif ($script_id) {
  4623. $uploaded_content = $this->getContentByScriptId($script_id);
  4624. if (!$uploaded_content) {
  4625. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4626. }
  4627. } elseif ($bid) {
  4628. $uploaded_content = $this->getContentByBid($bid);
  4629. if (!$uploaded_content) {
  4630. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4631. }
  4632. } elseif ($content) {
  4633. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  4634. }
  4635. // elseif ($prompt) {
  4636. // $uploaded_content = filterContent($prompt);
  4637. // }
  4638. else {
  4639. $uploaded_content = '';
  4640. }
  4641. $input_art_style = getProp($anime, 'art_style');
  4642. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4643. // 美术风格
  4644. if (!$mappedArtStyle) {
  4645. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4646. }else {
  4647. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4648. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4649. }else {
  4650. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4651. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4652. }
  4653. }
  4654. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4655. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4656. // 强制要求:
  4657. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4658. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4659. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4660. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4661. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  4662. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  4663. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  4664. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  4665. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  4666. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  4667. // - 分镜要和场景列表、人物主体保持一致\n
  4668. // 普通要求:
  4669. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4670. // {$role_demo}
  4671. // {$scene_demo}
  4672. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4673. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4674. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4675. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4676. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4677. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4678. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4679. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4680. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4681. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4682. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4683. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4684. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4685. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4686. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4687. // 5.$mappedArtStyle_prompt\n\n
  4688. // 示例格式:\n
  4689. // 第1集:隐形的守护者
  4690. // ###故事梗概
  4691. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4692. // ###美术风格
  4693. // 基础画风风格词:韩漫二次元
  4694. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4695. // ###主体列表
  4696. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4697. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4698. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4699. // ###场景列表
  4700. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4701. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4702. // 无人物。}
  4703. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4704. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4705. // 无人物。}
  4706. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4707. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4708. // 无人物。}
  4709. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4710. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4711. // 无人物。}
  4712. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4713. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4714. // 无人物。}
  4715. // ###分镜剧本
  4716. // ##第1幕:徐家老旧厨房 白天 室内
  4717. // 分镜1
  4718. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4719. // 场景:徐家老旧厨房
  4720. // 构图设计:全景,低角度仰视
  4721. // 运镜调度:手持拍摄
  4722. // 配音角色:旁白
  4723. // 出镜角色:许芸-校服装、徐母
  4724. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4725. // 画面类型:普通画面
  4726. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4727. // 分镜2
  4728. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4729. // 场景:徐家老旧厨房
  4730. // 构图设计:近景,徐母面部特写
  4731. // 运镜调度:固定镜头
  4732. // 配音角色:徐母
  4733. // 出镜角色:徐母
  4734. // 台词内容:问我夜不归宿死哪儿去了。
  4735. // 画面类型:对口型
  4736. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4737. // ##第2幕:徐家简陋客厅 黄昏 室内
  4738. // 分镜3
  4739. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4740. // 场景:徐家简陋客厅
  4741. // 构图设计:全景,景深虚化
  4742. // 运镜调度:固定镜头
  4743. // 配音角色:旁白
  4744. // 出镜角色:无
  4745. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4746. // 画面类型:普通画面
  4747. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4748. // 分镜4
  4749. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4750. // 场景:徐家简陋客厅
  4751. // 构图设计:特写,火车票
  4752. // 运镜调度:固定镜头
  4753. // 配音角色:旁白
  4754. // 出镜角色:无
  4755. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4756. // 画面类型:普通画面
  4757. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4758. // \n\n";
  4759. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  4760. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  4761. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  4762. 普通要求:
  4763. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4764. {$role_demo}
  4765. {$scene_demo}
  4766. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4767. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4768. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4769. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  4770. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4771. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4772. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4773. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4774. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4775. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4776. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4777. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4778. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4779. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4780. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4781. 5.$mappedArtStyle_prompt
  4782. 6.《情绪-视听语言映射表》:
  4783. 6.1 场景空间与时间心理学 (Scene & Temporality)
  4784. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4785. -----|---------|------------|----------------
  4786. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  4787. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  4788. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  4789. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  4790. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  4791. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4792. -----|---------|------------|----------------
  4793. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  4794. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  4795. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  4796. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  4797. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  4798. --------|---------|--------------|-------------
  4799. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  4800. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  4801. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  4802. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  4803. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  4804. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  4805. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  4806. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  4807. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  4808. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  4809. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  4810. -----|---------|------------|------------
  4811. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  4812. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  4813. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  4814. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  4815. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  4816. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  4817. --------|---------|--------------|----------
  4818. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  4819. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  4820. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  4821. 6.6 声音设计与潜意识影响 (Soundscape)
  4822. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  4823. -----|---------|------------|------------------
  4824. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  4825. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  4826. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  4827. 理论基石:
  4828. - The Five C's of Cinematography by Joseph V. Mascelli
  4829. - Film Art: An Introduction by David Bordwell
  4830. - Sight, Sound, Motion by Herbert Zettl
  4831. - Notes on the Cinematograph by Robert Bresson
  4832. \n\n
  4833. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  4834. 示例格式:\n
  4835. 第1集:隐形的守护者
  4836. ###故事梗概
  4837. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4838. ###美术风格
  4839. 基础画风风格词:韩漫二次元
  4840. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4841. ###主体列表
  4842. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4843. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4844. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4845. ###场景列表
  4846. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4847. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4848. 无人物。}
  4849. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4850. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4851. 无人物。}
  4852. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4853. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4854. 无人物。}
  4855. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4856. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4857. 无人物。}
  4858. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4859. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4860. 无人物。}
  4861. ###分镜剧本
  4862. ##第1幕:徐家老旧厨房 白天 室内
  4863. 分镜1
  4864. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4865. 场景:徐家老旧厨房
  4866. 构图设计:全景,低角度仰视
  4867. 运镜调度:手持拍摄
  4868. 配音角色:旁白
  4869. 出镜角色:许芸-校服装、徐母
  4870. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4871. 画面类型:普通画面
  4872. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4873. 分镜2
  4874. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4875. 场景:徐家老旧厨房
  4876. 构图设计:近景,徐母面部特写
  4877. 运镜调度:固定镜头
  4878. 配音角色:徐母
  4879. 出镜角色:徐母
  4880. 台词内容:问我夜不归宿死哪儿去了。
  4881. 画面类型:对口型
  4882. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4883. ##第2幕:徐家简陋客厅 黄昏 室内
  4884. 分镜3
  4885. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4886. 场景:徐家简陋客厅
  4887. 构图设计:全景,景深虚化
  4888. 运镜调度:固定镜头
  4889. 配音角色:旁白
  4890. 出镜角色:无
  4891. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4892. 画面类型:普通画面
  4893. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4894. 分镜4
  4895. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4896. 场景:徐家简陋客厅
  4897. 构图设计:特写,火车票
  4898. 运镜调度:固定镜头
  4899. 配音角色:旁白
  4900. 出镜角色:无
  4901. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4902. 画面类型:普通画面
  4903. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4904. \n\n";
  4905. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4906. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  4907. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  4908. $prompt = $origin_prompt;
  4909. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  4910. // 获取章节内容
  4911. $full_content = getProp($anime, 'content');
  4912. if ($uploaded_content) {
  4913. $full_content = $uploaded_content;
  4914. }
  4915. // 根据章节内容拆分章节
  4916. $chapters = splitContent($full_content);
  4917. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  4918. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  4919. $messages = [];
  4920. if ($prompt == '确认分镜大纲') {
  4921. // 暂时保留
  4922. $content = $chapter_content;
  4923. if ($is_single) $content = $full_content; // 单剧集使用全文
  4924. if (!$content) {
  4925. Utils::throwError('20003:章节内容无法获取,请确认');
  4926. }
  4927. $question = $is_single
  4928. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  4929. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  4930. // 构建消息
  4931. $messages[] =
  4932. [
  4933. 'role' => 'user',
  4934. 'content' => $question
  4935. ];
  4936. }else if ($prompt == '继续策划下一集') {
  4937. if ($is_single) {
  4938. Utils::throwError('20003:单剧集不支持继续策划下一集');
  4939. }
  4940. $content = $chapter_content;
  4941. if (!$content) {
  4942. Utils::throwError('20003:章节内容无法获取,请确认');
  4943. }
  4944. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  4945. // 获取上一集最后记录
  4946. $prev_sequence = $episode_number - 1;
  4947. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  4948. // 构建消息
  4949. $messages[] =
  4950. [
  4951. 'role' => 'user',
  4952. 'content' => $question
  4953. ];
  4954. }else {
  4955. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  4956. if (!$content) {
  4957. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  4958. }
  4959. if (!$content) {
  4960. Utils::throwError('20003:章节内容无法获取,请确认');
  4961. }
  4962. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  4963. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  4964. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  4965. if ($origin_prompt) {
  4966. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  4967. }
  4968. $messages[] =
  4969. [
  4970. 'role' => 'user',
  4971. 'content' => $question
  4972. ];
  4973. }
  4974. // 处理文本模型
  4975. $model = getProp($data, 'model');
  4976. if (!$model) {
  4977. // 用户没有输入,从anime表获取
  4978. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4979. $model = getProp($anime, 'model');
  4980. if (!$model) {
  4981. // anime表也没有,使用默认值
  4982. $model = 'doubao-seed-2-0-mini-260215';
  4983. }
  4984. }
  4985. // 验证模型是否在可用模型表中
  4986. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4987. $model = 'doubao-seed-2-0-mini-260215';
  4988. }
  4989. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4990. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4991. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4992. if ($model === 'deepseek-chat') {
  4993. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4994. $model = 'deepseek-v4-flash';
  4995. $thinkingMode = 'disabled';
  4996. } elseif ($model === 'deepseek-reasoner') {
  4997. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4998. $model = 'deepseek-v4-flash';
  4999. $thinkingMode = 'enabled';
  5000. }
  5001. $post_data = [
  5002. 'model' => $model,
  5003. 'messages' => $messages,
  5004. // 'max_tokens' => 8192,
  5005. 'temperature' => 0.2,
  5006. 'frequency_penalty' => 0,
  5007. 'presence_penalty' => 0,
  5008. 'response_format' => ['type' => 'text'],
  5009. 'thinking' => ['type' => $thinkingMode],
  5010. 'stream' => true // 启用流式输出
  5011. ];
  5012. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5013. // 根据模型类型选择调用方法
  5014. $fullContent = '';
  5015. $fullReasoningContent = '';
  5016. $usage = [];
  5017. try {
  5018. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5019. // DeepSeek 官方模型使用 DeepSeek API
  5020. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5021. } else if (in_array($model, $this->gpt_text_models)) {
  5022. // GPT-5.4 模型使用 TokenRouter API
  5023. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5024. } else {
  5025. // 其他模型使用火山引擎API
  5026. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5027. }
  5028. // 验证返回值类型
  5029. if (!is_iterable($streamGenerator)) {
  5030. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5031. dLog('deepseek')->error('chat流式生成器无效', [
  5032. 'generator_type' => $errorType,
  5033. 'model' => $model,
  5034. 'anime_id' => $anime_id,
  5035. 'episode_number' => $episode_number
  5036. ]);
  5037. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  5038. 'type' => $errorType,
  5039. 'model' => $model
  5040. ]);
  5041. yield [
  5042. 'type' => 'error',
  5043. 'episode' => [],
  5044. 'answer' => '',
  5045. 'reasoning' => '',
  5046. 'usage' => [],
  5047. 'error' => '接口返回数据异常,请重新请求'
  5048. ];
  5049. return;
  5050. }
  5051. // 处理流式输出
  5052. foreach ($streamGenerator as $chunk) {
  5053. if (isset($chunk['type'])) {
  5054. if ($chunk['type'] === 'done') {
  5055. // 最终结果
  5056. $fullContent = $chunk['full_content'];
  5057. $fullReasoningContent = $chunk['full_reasoning'];
  5058. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5059. } else {
  5060. // 逐块yield数据
  5061. yield $chunk;
  5062. }
  5063. }
  5064. }
  5065. } catch (\Exception $e) {
  5066. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  5067. 'model' => $model,
  5068. 'anime_id' => $anime_id,
  5069. 'episode_number' => $episode_number,
  5070. 'trace' => $e->getTraceAsString()
  5071. ]);
  5072. logDB('deepseek', 'error', 'chat流式处理失败', [
  5073. 'error' => $e->getMessage(),
  5074. 'model' => $model
  5075. ]);
  5076. yield [
  5077. 'type' => 'error',
  5078. 'episode' => [],
  5079. 'answer' => '',
  5080. 'reasoning' => '',
  5081. 'usage' => [],
  5082. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5083. ];
  5084. return;
  5085. }
  5086. dLog('deepseek')->info('完整内容: '.$fullContent);
  5087. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5088. // 处理完整内容并返回最终结果
  5089. $episode_arr = handleEpisodeContent($fullContent);
  5090. logDB('deepseek', 'info', '解析内容', $episode_arr);
  5091. if (empty($episode_arr['acts'])) {
  5092. // 未生成剧本相关内容,保存对话记录并返回提示
  5093. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  5094. try {
  5095. $now = date('Y-m-d H:i:s');
  5096. // 保存对话记录
  5097. $records = [
  5098. [
  5099. 'uid' => $uid,
  5100. 'anime_id' => $anime_id,
  5101. 'sequence' => $episode_number,
  5102. 'role' => 'user',
  5103. 'content' => $prompt,
  5104. 'created_at' => $now,
  5105. 'updated_at' => $now
  5106. ],
  5107. [
  5108. 'uid' => $uid,
  5109. 'anime_id' => $anime_id,
  5110. 'sequence' => $episode_number,
  5111. 'role' => 'assistant',
  5112. 'content' => $fullContent,
  5113. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5114. 'created_at' => $now,
  5115. 'updated_at' => $now
  5116. ]
  5117. ];
  5118. DB::table('mp_anime_records')->insert($records);
  5119. } catch (\Exception $e) {
  5120. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5121. }
  5122. yield [
  5123. 'type' => 'done',
  5124. 'episode' => [],
  5125. 'answer' => $fullContent,
  5126. 'reasoning' => $fullReasoningContent,
  5127. 'usage' => $usage,
  5128. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  5129. ];
  5130. return;
  5131. }
  5132. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  5133. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  5134. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  5135. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  5136. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  5137. $existing_props = is_array($existing_props) ? $existing_props : [];
  5138. $now = date('Y-m-d H:i:s');
  5139. try {
  5140. DB::beginTransaction();
  5141. $saveResult = $this->saveEpisodeVersionData(
  5142. $anime_id,
  5143. $episode_number,
  5144. $episode_arr,
  5145. $existing_roles,
  5146. $existing_scenes,
  5147. $existing_props,
  5148. $current_episode,
  5149. $base_episode,
  5150. $is_regenerate_version,
  5151. $content,
  5152. $now
  5153. );
  5154. $episode = $saveResult['episode'];
  5155. $episode_id = $saveResult['episode_id'];
  5156. $merged_roles = $saveResult['merged_roles'];
  5157. $merged_scenes = $saveResult['merged_scenes'];
  5158. $merged_props = $saveResult['merged_props'];
  5159. $record_content = $origin_prompt;
  5160. if ($uploaded_content !== '') {
  5161. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  5162. }
  5163. $records = [
  5164. [
  5165. 'uid' => $uid,
  5166. 'anime_id' => $anime_id,
  5167. 'role' => 'user',
  5168. 'content' => $record_content,
  5169. 'sequence' => $episode_number,
  5170. 'episode_id' => $episode_id,
  5171. 'created_at' => $now,
  5172. 'updated_at' => $now
  5173. ],
  5174. [
  5175. 'uid' => $uid,
  5176. 'anime_id' => $anime_id,
  5177. 'role' => 'assistant',
  5178. 'content' => $fullContent,
  5179. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5180. 'sequence' => $episode_number,
  5181. 'episode_id' => $episode_id,
  5182. 'created_at' => $now,
  5183. 'updated_at' => $now
  5184. ]
  5185. ];
  5186. $boolen4 = DB::table('mp_anime_records')->insert($records);
  5187. if (!$boolen4) {
  5188. Utils::throwError('20003:对话记录保存失败');
  5189. }
  5190. // 保存模型和内容到anime表
  5191. $update_anime_data = [
  5192. 'model' => $model,
  5193. 'updated_at' => $now
  5194. ];
  5195. if ($uploaded_content) {
  5196. $update_anime_data['content'] = $uploaded_content;
  5197. }
  5198. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  5199. }catch (\Exception $e) {
  5200. DB::rollBack();
  5201. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5202. yield [
  5203. 'type' => 'done',
  5204. 'answer' => $fullContent,
  5205. 'reasoning' => $fullReasoningContent,
  5206. 'usage' => $usage,
  5207. 'error' => $e->getMessage(),
  5208. ];
  5209. return;
  5210. }
  5211. DB::commit();
  5212. if ($is_global_generate_pics) {
  5213. // // 批量生成全局角色图片
  5214. // $this->batchSetGlobalRoleImg([
  5215. // 'anime_id' => $anime_id,
  5216. // ], true);
  5217. // // 批量生成全局场景图片
  5218. // $this->batchSetGlobalSceneImg([
  5219. // 'anime_id' => $anime_id,
  5220. // ], true);
  5221. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5222. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5223. }
  5224. $episode['episode_id'] = $episode_id;
  5225. $episode['roles'] = $merged_roles;
  5226. $episode['scenes'] = $merged_scenes;
  5227. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  5228. yield [
  5229. 'type' => 'done',
  5230. 'episode' => $episode,
  5231. 'answer' => $fullContent,
  5232. 'reasoning' => $fullReasoningContent,
  5233. 'usage' => $usage
  5234. ];
  5235. }
  5236. public function addChatForAce($data) {
  5237. $uid = Site::getUid();
  5238. $anime_id = getProp($data, 'anime_id');
  5239. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5240. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5241. if (!$anime) Utils::throwError('20003:对话不存在');
  5242. $file = getProp($data, 'file');
  5243. $content = getProp($data, 'content', '');
  5244. $bid = getProp($data, 'bid', 0);
  5245. $script_id = getProp($data, 'script_id', 0);
  5246. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5247. $prompt = getProp($data, 'prompt');
  5248. $is_multi = getProp($anime, 'is_multi');
  5249. $is_single = (int)$is_multi !== 1;
  5250. // 积分余额预检(仅单剧集模式收费)
  5251. if ($is_single) {
  5252. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  5253. }
  5254. $extra_products = getProp($data, 'products', []);
  5255. if (!$extra_products) {
  5256. $extra_products = getProp($anime, 'extra_products');
  5257. if ($extra_products) {
  5258. $extra_products = json_decode($extra_products, true);
  5259. }else {
  5260. $extra_products = [];
  5261. }
  5262. }else {
  5263. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  5264. }
  5265. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  5266. $anime_script_id = getProp($anime, 'script_id');
  5267. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  5268. $cpid = Site::getCpid();
  5269. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  5270. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  5271. ->where('mapping.script_id', $anime_script_id)
  5272. ->where('product.cpid', $cpid)
  5273. ->where('product.is_deleted', 0);
  5274. $mappings = $script_products_mappings->select(
  5275. 'mapping.product_id',
  5276. 'mapping.episode_number',
  5277. 'product.product_name',
  5278. 'product.type',
  5279. 'product.product',
  5280. 'product.pic_prompt',
  5281. 'product.url',
  5282. 'product.pic_task_id',
  5283. 'product.pic_task_status',
  5284. 'product.three_view_image_url'
  5285. )
  5286. ->get();
  5287. // 按 product_id 分组,合并 episode_number
  5288. $productMap = [];
  5289. foreach ($mappings as $item) {
  5290. $product_id = $item->product_id;
  5291. $product_name = $item->product_name;
  5292. // 处理product_name两边的符号
  5293. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5294. if (!isset($productMap[$product_id])) {
  5295. $productMap[$product_id] = [
  5296. 'product_id' => $product_id,
  5297. 'product_name' => $product_name,
  5298. 'type' => (int)$item->type,
  5299. 'product' => (int)$item->product,
  5300. 'pic_prompt' => $item->pic_prompt,
  5301. 'url' => $item->url,
  5302. 'pic_task_id' => $item->pic_task_id,
  5303. 'pic_task_status' => $item->pic_task_status,
  5304. 'episode_numbers' => [],
  5305. ];
  5306. }
  5307. // 添加 episode_number(去重)
  5308. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  5309. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  5310. }
  5311. }
  5312. // 将查询到的剧本资产合并到extra_products中
  5313. // 先构建extra_products的索引(以product_id为key,用于去重)
  5314. $extraProductsMap = [];
  5315. foreach ($extra_products as $item) {
  5316. $key = getProp($item, 'product_id');
  5317. if ($key) {
  5318. $extraProductsMap[$key] = $item;
  5319. }
  5320. }
  5321. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  5322. foreach ($productMap as $product) {
  5323. $product_id = $product['product_id'];
  5324. // 如果不存在则添加(不带episode_number信息)
  5325. if (!isset($extraProductsMap[$product_id])) {
  5326. $extraProductsMap[$product_id] = [
  5327. 'product_id' => $product['product_id'],
  5328. 'product_name' => $product['product_name'],
  5329. 'type' => $product['type'],
  5330. 'product' => $product['product'],
  5331. 'pic_prompt' => $product['pic_prompt'],
  5332. 'url' => $product['url'],
  5333. 'pic_task_id' => $product['pic_task_id'],
  5334. 'pic_task_status' => $product['pic_task_status'],
  5335. ];
  5336. }
  5337. }
  5338. // 重新赋值给extra_products
  5339. $extra_products = array_values($extraProductsMap);
  5340. }
  5341. $user_anime_name = getProp($anime, 'anime_name');
  5342. // 处理提示词
  5343. if ($prompt && $extra_products) {
  5344. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  5345. foreach($extra_products as $item) {
  5346. $product_name = getProp($item, 'product_name');
  5347. if ($product_name) {
  5348. // 替换 {product_name} 为 product_name
  5349. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  5350. }
  5351. }
  5352. }
  5353. // 处理文本模型
  5354. $model = getProp($data, 'model');
  5355. if (!$model) {
  5356. // 用户没有输入,从anime表获取
  5357. $model = getProp($anime, 'model');
  5358. if (!$model) {
  5359. // anime表也没有,使用默认值
  5360. $model = 'deepseek-v4-pro';
  5361. }
  5362. }
  5363. // 验证模型是否在可用模型表中
  5364. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5365. $model = 'deepseek-v4-pro';
  5366. }
  5367. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  5368. if ($prompt) {
  5369. $question .= "本次修改要求如下:\n{$prompt}";
  5370. }
  5371. // if (!$file && !$content && !$bid) {
  5372. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5373. // }
  5374. // 提取文件内容
  5375. if ($file) {
  5376. $content = $this->extractFileContent($file);
  5377. if (!$content) {
  5378. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5379. }
  5380. } elseif ($script_id) {
  5381. $content = $this->getContentByScriptId($script_id);
  5382. if (!$content) {
  5383. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5384. }
  5385. } elseif ($bid) {
  5386. $content = $this->getContentByBid($bid);
  5387. if (!$content) {
  5388. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5389. }
  5390. } elseif ($content) {
  5391. $content = filterContent($content);
  5392. } else {
  5393. $content = getProp($anime, 'content');
  5394. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5395. $need_generate_content = true;
  5396. }
  5397. }
  5398. // 美术风格
  5399. $input_art_style = getProp($data, 'art_style');
  5400. if (!$input_art_style) {
  5401. $mappedArtStyle = getProp($anime, 'art_style');
  5402. }else {
  5403. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5404. }
  5405. // 判断是否需要生成原文内容
  5406. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5407. // 如果需要生成原文内容,添加额外的要求
  5408. $content_generation_requirement = $need_generate_content
  5409. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5410. : "";
  5411. // 美术风格
  5412. if (!$mappedArtStyle) {
  5413. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5414. }else {
  5415. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5416. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5417. }else {
  5418. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5419. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5420. }
  5421. }
  5422. // 构建主体、场景和道具提示词
  5423. $extra_role_prompt = "\n";
  5424. $extra_scene_prompt = "\n";
  5425. $extra_prop_prompt = "\n";
  5426. $ref_products = []; // 参考资产
  5427. if ($extra_products) {
  5428. foreach($extra_products as $item) {
  5429. $product = getProp($item, 'product');
  5430. $product_name = getProp($item, 'product_name');
  5431. if ($product_name == '旁白') continue;
  5432. $ref_products[$product_name] = $item;
  5433. $pic_prompt = getProp($item, 'pic_prompt');
  5434. if ((int)$product === 1) {
  5435. // 拼接角色信息
  5436. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5437. } elseif ((int)$product === 2) {
  5438. // 拼接场景信息
  5439. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5440. } elseif ((int)$product === 3) {
  5441. // 拼接道具信息
  5442. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5443. }
  5444. }
  5445. // 优化提示词,融入剧本
  5446. if (!empty(trim($extra_role_prompt))) {
  5447. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  5448. }
  5449. if (!empty(trim($extra_scene_prompt))) {
  5450. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  5451. }
  5452. if (!empty(trim($extra_prop_prompt))) {
  5453. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  5454. }
  5455. }
  5456. if ($anime_script_id && $is_single) {
  5457. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  5458. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  5459. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  5460. }else {
  5461. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5462. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5463. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5464. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5465. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5466. {$extra_role_prompt}";
  5467. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5468. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5469. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5470. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5471. {$extra_scene_prompt}";
  5472. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5473. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5474. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5475. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5476. {$extra_prop_prompt}";
  5477. }
  5478. $systemPrompt = $is_single
  5479. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5480. 强制要求:
  5481. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5482. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5483. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5484. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5485. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5486. 普通要求:
  5487. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5488. $role_demo
  5489. $scene_demo
  5490. $prop_demo
  5491. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  5492. 5.1片段分割逻辑(优先级从高到低):
  5493. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  5494. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  5495. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  5496. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  5497. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  5498. - 片段数量格式为: 片段数量:8
  5499. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5500. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  5501. 5.3分镜结构:每个分镜包含以下字段:
  5502. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  5503. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5504. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5505. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5506. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  5507. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5508. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5509. - 运镜:场景+画面描述+运镜
  5510. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  5511. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  5512. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  5513. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  5514. 6.{$mappedArtStyle_prompt}\n\n
  5515. 示例如下:\n
  5516. ###剧本名:西昆仑
  5517. ###故事梗概
  5518. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5519. ###剧本亮点
  5520. 亮点1:绝境奇药,生死一线
  5521. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5522. 亮点2:结拜兄妹,化解尴尬
  5523. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5524. 亮点3:纤发夺命,情愫暗涌
  5525. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5526. ###人物关系
  5527. 阿雪与梁萧之间存在兄妹之情。
  5528. ###核心矛盾
  5529. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5530. ###主体列表
  5531. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5532. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5533. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5534. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5535. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5536. 全景,正面拍摄,青年女性,亚洲人。
  5537. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5538. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5539. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5540. ###美术风格
  5541. 基础画风风格词:厚涂古风
  5542. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5543. ###场景列表
  5544. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5545. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5546. 无人物。}
  5547. ###分段剧本
  5548. 片段数量:8
  5549. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  5550. ##片段1
  5551. 时长:12s
  5552. 分镜1
  5553. 出场角色:刀疤脸
  5554. 场景:边境小镇街道
  5555. 出场道具:酒杯-高脚杯
  5556. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  5557. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  5558. 配音台词:
  5559. 背景音效:
  5560. 分镜2
  5561. 出场角色:刀疤脸
  5562. 场景:悦来酒馆
  5563. 出场道具:酒杯-高脚杯
  5564. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  5565. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  5566. 配音台词:
  5567. 背景音效:
  5568. 分镜3
  5569. 出场角色:刀疤脸
  5570. 场景:悦来酒馆
  5571. 出场道具:酒杯-高脚杯
  5572. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  5573. 运镜:从中景推向令牌特写。
  5574. 配音台词:
  5575. 背景音效:
  5576. 分镜4
  5577. 出场角色:刀疤脸
  5578. 场景:悦来酒馆
  5579. 出场道具:酒杯-高脚杯
  5580. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  5581. 运镜:极速推向酒水溅起的瞬间。
  5582. 配音台词:
  5583. 背景音效:
  5584. 分镜5
  5585. 出场角色:刀疤脸
  5586. 场景:悦来酒馆
  5587. 出场道具:酒杯-高脚杯
  5588. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  5589. 运镜:固定机位,利用倾斜构图制造压迫感。
  5590. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  5591. 背景音效:
  5592. \n\n"
  5593. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5594. 强制要求:\n
  5595. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5596. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5597. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5598. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5599. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5600. 普通要求:\n
  5601. 1.剧本名(必须生成)必须与文档内容高度相关
  5602. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5603. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5604. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5605. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5606. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5607. {$extra_role_prompt}
  5608. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5609. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5610. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5611. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5612. {$extra_scene_prompt}
  5613. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5614. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5615. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5616. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5617. {$extra_prop_prompt}
  5618. 5.{$mappedArtStyle_prompt}\n\n
  5619. 示例如下:\n
  5620. ###剧本名:西昆仑
  5621. ###故事梗概
  5622. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5623. ###剧本亮点
  5624. 亮点1:绝境奇药,生死一线
  5625. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5626. 亮点2:结拜兄妹,化解尴尬
  5627. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5628. 亮点3:纤发夺命,情愫暗涌
  5629. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5630. ###人物关系
  5631. 阿雪与梁萧之间存在兄妹之情。
  5632. ###核心矛盾
  5633. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5634. ###主体列表
  5635. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5636. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5637. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5638. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5639. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5640. 全景,正面拍摄,青年女性,亚洲人。
  5641. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5642. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5643. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5644. ###美术风格
  5645. 基础画风风格词:厚涂古风
  5646. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5647. ###场景列表
  5648. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5649. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5650. 无人物。}
  5651. ###道具列表
  5652. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  5653. // 构建消息
  5654. $messages = [
  5655. [
  5656. 'role' => 'system',
  5657. 'content' => $systemPrompt
  5658. ],
  5659. [
  5660. 'role' => 'user',
  5661. 'content' => "以下是文档内容:
  5662. {$content}
  5663. 用户问题:
  5664. {$question}"
  5665. ]
  5666. ];
  5667. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5668. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5669. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5670. if ($model === 'deepseek-chat') {
  5671. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5672. $model = 'deepseek-v4-flash';
  5673. $thinkingMode = 'disabled';
  5674. } elseif ($model === 'deepseek-reasoner') {
  5675. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5676. $model = 'deepseek-v4-flash';
  5677. $thinkingMode = 'enabled';
  5678. }
  5679. $post_data = [
  5680. 'model' => $model,
  5681. 'messages' => $messages,
  5682. // 'max_tokens' => 8192,
  5683. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  5684. 'frequency_penalty' => 0,
  5685. 'presence_penalty' => 0,
  5686. 'response_format' => ['type' => 'text'],
  5687. 'thinking' => ['type'=>$thinkingMode],
  5688. 'stream' => true // 启用流式输出
  5689. ];
  5690. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5691. // 根据模型类型选择调用方法
  5692. $fullContent = '';
  5693. $fullReasoningContent = '';
  5694. $usage = [];
  5695. try {
  5696. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5697. // DeepSeek 官方模型使用 DeepSeek API
  5698. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5699. } else if (in_array($model, $this->gpt_text_models)) {
  5700. // GPT-5.4 模型使用 TokenRouter API
  5701. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5702. } else {
  5703. // 其他模型使用火山引擎API
  5704. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5705. }
  5706. // 验证返回值类型
  5707. if (!is_iterable($streamGenerator)) {
  5708. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5709. dLog('deepseek')->error('addChat流式生成器无效', [
  5710. 'generator_type' => $errorType,
  5711. 'model' => $model,
  5712. 'anime_id' => $anime_id
  5713. ]);
  5714. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5715. 'type' => $errorType,
  5716. 'model' => $model
  5717. ]);
  5718. yield [
  5719. 'type' => 'error',
  5720. 'script' => [],
  5721. 'episode' => [],
  5722. 'answer' => '',
  5723. 'reasoning' => '',
  5724. 'usage' => [],
  5725. 'error' => '接口返回数据异常,请重新请求'
  5726. ];
  5727. return;
  5728. }
  5729. // 处理流式输出
  5730. foreach ($streamGenerator as $chunk) {
  5731. if (isset($chunk['type'])) {
  5732. if ($chunk['type'] === 'done') {
  5733. // 最终结果
  5734. $fullContent = $chunk['full_content'];
  5735. $fullReasoningContent = $chunk['full_reasoning'];
  5736. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5737. } else {
  5738. // 逐块yield数据
  5739. yield $chunk;
  5740. }
  5741. }
  5742. }
  5743. } catch (\Exception $e) {
  5744. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5745. 'model' => $model,
  5746. 'anime_id' => $anime_id,
  5747. 'trace' => $e->getTraceAsString()
  5748. ]);
  5749. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5750. 'error' => $e->getMessage(),
  5751. 'model' => $model
  5752. ]);
  5753. yield [
  5754. 'type' => 'error',
  5755. 'script' => [],
  5756. 'episode' => [],
  5757. 'answer' => '',
  5758. 'reasoning' => '',
  5759. 'usage' => [],
  5760. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5761. ];
  5762. return;
  5763. }
  5764. dLog('deepseek')->info('完整内容: '.$fullContent);
  5765. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5766. // 处理完整内容并返回最终结果
  5767. $script_arr = [];
  5768. if ($fullContent) {
  5769. $script_arr = handleScriptContentForAce($fullContent);
  5770. dLog('deepseek')->info('解析内容', $script_arr);
  5771. logDB('deepseek', 'info', '解析内容', $script_arr);
  5772. }
  5773. if (empty($script_arr['roles'])) {
  5774. // 未生成剧本相关内容,保存对话记录并返回提示
  5775. dLog('deepseek')->info('未生成剧本相关的内容');
  5776. try {
  5777. DB::beginTransaction();
  5778. $now = date('Y-m-d H:i:s');
  5779. // 保存对话记录
  5780. $records = [
  5781. [
  5782. 'uid' => $uid,
  5783. 'anime_id' => $anime_id,
  5784. 'sequence' => 0,
  5785. 'role' => 'user',
  5786. 'content' => $prompt,
  5787. 'created_at' => $now,
  5788. 'updated_at' => $now
  5789. ],
  5790. [
  5791. 'uid' => $uid,
  5792. 'anime_id' => $anime_id,
  5793. 'sequence' => 0,
  5794. 'role' => 'assistant',
  5795. // 'content' => $fullContent,
  5796. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5797. 'created_at' => $now,
  5798. 'updated_at' => $now
  5799. ]
  5800. ];
  5801. DB::table('mp_anime_records')->insert($records);
  5802. DB::commit();
  5803. } catch (\Exception $e) {
  5804. DB::rollBack();
  5805. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5806. }
  5807. yield [
  5808. 'type' => 'done',
  5809. 'script' => [],
  5810. 'episode' => [],
  5811. 'answer' => $fullContent,
  5812. 'reasoning' => $fullReasoningContent,
  5813. 'usage' => $usage,
  5814. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5815. ];
  5816. return;
  5817. }
  5818. // 如果需要生成原文内容,从script_arr中提取
  5819. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5820. $content = $script_arr['content'];
  5821. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5822. if (!$content) {
  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. }
  5835. // 替换美术风格
  5836. if ($mappedArtStyle !== '') {
  5837. $script_arr['art_style'] = $mappedArtStyle;
  5838. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5839. }
  5840. // 新建动漫
  5841. if ($user_anime_name == '新剧本策划') {
  5842. $anime_name = getProp($script_arr, 'script_name');
  5843. // if (!$anime_name) {
  5844. // // 未识别到剧本名,保存对话记录并返回提示
  5845. // dLog('deepseek')->info('未能识别到剧本名称');
  5846. // try {
  5847. // DB::beginTransaction();
  5848. // $now = date('Y-m-d H:i:s');
  5849. // // 保存对话记录
  5850. // $records = [
  5851. // [
  5852. // 'uid' => $uid,
  5853. // 'anime_id' => $anime_id,
  5854. // 'sequence' => 0,
  5855. // 'role' => 'user',
  5856. // 'content' => $prompt,
  5857. // 'created_at' => $now,
  5858. // 'updated_at' => $now
  5859. // ],
  5860. // [
  5861. // 'uid' => $uid,
  5862. // 'anime_id' => $anime_id,
  5863. // 'sequence' => 0,
  5864. // 'role' => 'assistant',
  5865. // 'content' => '未能生成剧本名称,请重试',
  5866. // 'created_at' => $now,
  5867. // 'updated_at' => $now
  5868. // ]
  5869. // ];
  5870. // DB::table('mp_anime_records')->insert($records);
  5871. // DB::commit();
  5872. // } catch (\Exception $e) {
  5873. // DB::rollBack();
  5874. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5875. // }
  5876. // yield [
  5877. // 'type' => 'done',
  5878. // 'script' => [],
  5879. // 'episode' => [],
  5880. // 'answer' => $fullContent,
  5881. // 'reasoning' => $fullReasoningContent,
  5882. // 'usage' => $usage,
  5883. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  5884. // ];
  5885. // return;
  5886. // }
  5887. // 确认对话名称唯一性
  5888. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5889. $anime_name = $anime_name . '_' . date('YmdHis');
  5890. }
  5891. }else {
  5892. $anime_name = $user_anime_name;
  5893. }
  5894. $table_data = [
  5895. 'user_id' => $uid,
  5896. 'anime_name' => $anime_name,
  5897. 'model' => $model,
  5898. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5899. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5900. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5901. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5902. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5903. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5904. 'art_style_type' => $input_art_style,
  5905. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5906. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  5907. 'status' => '解析完成',
  5908. 'content' => $content,
  5909. 'is_multi' => $is_multi,
  5910. 'ace_mode' => $ace_mode,
  5911. 'generate_status' => '待执行',
  5912. 'updated_at' => date('Y-m-d H:i:s')
  5913. ];
  5914. if ($table_data['content']) {
  5915. $chapters = splitContent($table_data['content']);
  5916. $chapter_count = count($chapters);
  5917. if ($chapter_count > 0) {
  5918. $table_data['start_episode_sequence'] = 1;
  5919. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5920. }
  5921. }
  5922. if ($extra_products) {
  5923. $table_data['extra_products'] = json_encode($extra_products, 256);
  5924. }
  5925. // 如果有剧本ID则进行绑定
  5926. if ($script_id) {
  5927. $table_data['script_id'] = $script_id;
  5928. }
  5929. $single_episode = [];
  5930. try {
  5931. DB::beginTransaction();
  5932. $now = date('Y-m-d H:i:s');
  5933. // 更新动漫大纲
  5934. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5935. if (!$boolen) {
  5936. dLog('deepseek')->info('动漫保存失败', $table_data);
  5937. Utils::throwError('20003:动漫保存失败');
  5938. }
  5939. // 保存对话记录
  5940. $records = [
  5941. [
  5942. 'uid' => $uid,
  5943. 'anime_id' => $anime_id,
  5944. 'sequence' => 0,
  5945. 'role' => 'user',
  5946. 'content' => $prompt,
  5947. 'created_at' => date('Y-m-d H:i:s'),
  5948. 'updated_at' => date('Y-m-d H:i:s')
  5949. ],
  5950. [
  5951. 'uid' => $uid,
  5952. 'anime_id' => $anime_id,
  5953. 'sequence' => 0,
  5954. 'role' => 'assistant',
  5955. 'content' => $fullContent,
  5956. 'created_at' => date('Y-m-d H:i:s'),
  5957. 'updated_at' => date('Y-m-d H:i:s')
  5958. ]
  5959. ];
  5960. // 保存对话记录
  5961. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5962. if (!$boolen3) {
  5963. Utils::throwError('20003:对话记录保存失败');
  5964. }
  5965. if ($is_single) {
  5966. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5967. if (empty($episode_arr['acts'])) {
  5968. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5969. }
  5970. $saveResult = $this->saveEpisodeVersionData(
  5971. $anime_id,
  5972. 1,
  5973. $episode_arr,
  5974. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5975. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5976. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5977. null,
  5978. null,
  5979. false,
  5980. $content,
  5981. $now,
  5982. $ref_products
  5983. );
  5984. $single_episode = $saveResult['episode'];
  5985. $episode_id = $saveResult['episode_id'];
  5986. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5987. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5988. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5989. 'props' => json_encode($saveResult['merged_props'], 256),
  5990. 'updated_at' => $now
  5991. ]);
  5992. if ($boolen5 === false) {
  5993. Utils::throwError('20003:单剧集主表资源同步失败');
  5994. }
  5995. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5996. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5997. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5998. $episode_record_content = '确认分镜大纲';
  5999. if ($content !== '') {
  6000. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6001. }
  6002. $episode_records = [
  6003. [
  6004. 'uid' => $uid,
  6005. 'anime_id' => $anime_id,
  6006. 'role' => 'user',
  6007. 'content' => $episode_record_content,
  6008. 'sequence' => 1,
  6009. 'episode_id' => $episode_id,
  6010. 'created_at' => $now,
  6011. 'updated_at' => $now
  6012. ],
  6013. [
  6014. 'uid' => $uid,
  6015. 'anime_id' => $anime_id,
  6016. 'role' => 'assistant',
  6017. 'content' => $fullContent,
  6018. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6019. 'sequence' => 1,
  6020. 'episode_id' => $episode_id,
  6021. 'created_at' => $now,
  6022. 'updated_at' => $now
  6023. ]
  6024. ];
  6025. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6026. if (!$boolen4) {
  6027. Utils::throwError('20003:单剧集分镜记录保存失败');
  6028. }
  6029. }
  6030. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6031. if ($is_single && !empty($single_episode)) {
  6032. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6033. 'anime_id' => $anime_id,
  6034. 'episode_id' => $episode_id ?? 0,
  6035. ]);
  6036. }
  6037. }catch (\Exception $e) {
  6038. DB::rollBack();
  6039. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6040. yield [
  6041. 'type' => 'done',
  6042. 'answer' => $fullContent,
  6043. 'reasoning' => $fullReasoningContent,
  6044. 'usage' => $usage,
  6045. 'error' => $e->getMessage(),
  6046. ];
  6047. return;
  6048. }
  6049. DB::commit();
  6050. dLog('deepseek')->info('保存完毕');
  6051. if ($is_single && !empty($single_episode)) {
  6052. // $this->batchSetGlobalRoleImg([
  6053. // 'anime_id' => $anime_id,
  6054. // ]);
  6055. // $this->batchSetGlobalSceneImg([
  6056. // 'anime_id' => $anime_id,
  6057. // ]);
  6058. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6059. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6060. }
  6061. $table_data['anime_id'] = $anime_id;
  6062. $table_data['roles'] = json_decode($table_data['roles'], true);
  6063. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6064. // $table_data['episodes'] = $script_arr['episodes'];
  6065. unset($table_data['created_at']);
  6066. unset($table_data['updated_at']);
  6067. unset($table_data['status']);
  6068. dLog('deepseek')->info('开始返回');
  6069. yield [
  6070. 'type' => 'done',
  6071. 'script' => $table_data,
  6072. 'episode' => $single_episode,
  6073. 'answer' => $fullContent,
  6074. 'reasoning' => $fullReasoningContent,
  6075. 'usage' => $usage
  6076. ];
  6077. }
  6078. public function reGenerateAnimeForAce($data) {
  6079. $uid = Site::getUid();
  6080. $file = getProp($data, 'file');
  6081. $content = getProp($data, 'content', '');
  6082. $bid = getProp($data, 'bid', 0);
  6083. $script_id = getProp($data, 'script_id', 0);
  6084. $anime_id = getProp($data, 'anime_id');
  6085. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6086. if (!$anime) {
  6087. Utils::throwError('20003:该对话不存在');
  6088. }
  6089. $is_multi = getProp($anime, 'is_multi', 1);
  6090. $is_single = (int)$is_multi !== 1;
  6091. // 积分余额预检(仅单剧集模式收费)
  6092. if ($is_single) {
  6093. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  6094. }
  6095. $extra_products = getProp($data, 'products', []);
  6096. if (!$extra_products) {
  6097. $extra_products = getProp($anime, 'extra_products');
  6098. if ($extra_products) {
  6099. $extra_products = json_decode($extra_products, true);
  6100. }else {
  6101. $extra_products = [];
  6102. }
  6103. }else {
  6104. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6105. }
  6106. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6107. $anime_script_id = getProp($anime, 'script_id');
  6108. if ($anime_script_id && $is_single) {
  6109. $cpid = Site::getCpid();
  6110. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6111. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6112. ->where('mapping.script_id', $anime_script_id)
  6113. ->where('product.cpid', $cpid)
  6114. ->where('product.is_deleted', 0);
  6115. $mappings = $script_products_mappings->select(
  6116. 'mapping.product_id',
  6117. 'mapping.episode_number',
  6118. 'product.product_name',
  6119. 'product.type',
  6120. 'product.product',
  6121. 'product.pic_prompt',
  6122. 'product.url',
  6123. 'product.pic_task_id',
  6124. 'product.pic_task_status',
  6125. 'product.three_view_image_url'
  6126. )
  6127. ->get();
  6128. // 按 product_id 分组,合并 episode_number
  6129. $productMap = [];
  6130. foreach ($mappings as $item) {
  6131. $product_id = $item->product_id;
  6132. $product_name = $item->product_name;
  6133. // 处理product_name两边的符号
  6134. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6135. if (!isset($productMap[$product_id])) {
  6136. $productMap[$product_id] = [
  6137. 'product_id' => $product_id,
  6138. 'product_name' => $product_name,
  6139. 'type' => (int)$item->type,
  6140. 'product' => (int)$item->product,
  6141. 'pic_prompt' => $item->pic_prompt,
  6142. 'url' => $item->url,
  6143. 'pic_task_id' => $item->pic_task_id,
  6144. 'pic_task_status' => $item->pic_task_status,
  6145. 'episode_numbers' => [],
  6146. ];
  6147. }
  6148. // 添加 episode_number(去重)
  6149. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6150. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6151. }
  6152. }
  6153. // 将查询到的剧本资产合并到extra_products中
  6154. // 先构建extra_products的索引(以product_id为key,用于去重)
  6155. $extraProductsMap = [];
  6156. foreach ($extra_products as $item) {
  6157. $key = getProp($item, 'product_id');
  6158. if ($key) {
  6159. $extraProductsMap[$key] = $item;
  6160. }
  6161. }
  6162. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6163. foreach ($productMap as $product) {
  6164. $product_id = $product['product_id'];
  6165. // 如果不存在则添加(不带episode_number信息)
  6166. if (!isset($extraProductsMap[$product_id])) {
  6167. $extraProductsMap[$product_id] = [
  6168. 'product_id' => $product['product_id'],
  6169. 'product_name' => $product['product_name'],
  6170. 'type' => $product['type'],
  6171. 'product' => $product['product'],
  6172. 'pic_prompt' => $product['pic_prompt'],
  6173. 'url' => $product['url'],
  6174. 'pic_task_id' => $product['pic_task_id'],
  6175. 'pic_task_status' => $product['pic_task_status'],
  6176. ];
  6177. }
  6178. }
  6179. // 重新赋值给extra_products
  6180. $extra_products = array_values($extraProductsMap);
  6181. }
  6182. $user_anime_name = getProp($anime, 'anime_name');
  6183. $prompt = getProp($data, 'prompt');
  6184. // 处理提示词
  6185. if ($prompt && $extra_products) {
  6186. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6187. foreach($extra_products as $item) {
  6188. $product_name = getProp($item, 'product_name');
  6189. if ($product_name) {
  6190. // 替换 {product_name} 为 product_name
  6191. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6192. }
  6193. }
  6194. }
  6195. // 处理文本模型
  6196. $model = getProp($data, 'model');
  6197. if (!$model) {
  6198. // 用户没有输入,从anime表获取
  6199. $model = getProp($anime, 'model');
  6200. if (!$model) {
  6201. // anime表也没有,使用默认值
  6202. $model = 'deepseek-v4-pro';
  6203. }
  6204. }
  6205. // 验证模型是否在可用模型表中
  6206. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6207. $model = 'deepseek-v4-pro';
  6208. }
  6209. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  6210. if ($is_single) {
  6211. $episode_exists = DB::table('mp_anime_episodes')
  6212. ->where('anime_id', $anime_id)
  6213. ->where('sequence', 1)
  6214. ->exists();
  6215. if ($episode_exists) {
  6216. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  6217. }
  6218. }
  6219. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6220. if ($prompt) {
  6221. $question .= "本次修改要求如下:\n{$prompt}";
  6222. }
  6223. // 提取文件内容
  6224. if ($file) {
  6225. $content = $this->extractFileContent($file);
  6226. if (!$content) {
  6227. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6228. }
  6229. } elseif ($script_id) {
  6230. $content = $this->getContentByScriptId($script_id);
  6231. if (!$content) {
  6232. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6233. }
  6234. } elseif ($bid) {
  6235. $content = $this->getContentByBid($bid);
  6236. if (!$content) {
  6237. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6238. }
  6239. } elseif ($content) {
  6240. $content = filterContent($content);
  6241. }else {
  6242. $content = filterContent(getProp($anime, 'content'));
  6243. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6244. $need_generate_content = true;
  6245. }
  6246. }
  6247. // 判断是否需要生成原文内容
  6248. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6249. // 如果需要生成原文内容,添加额外的要求
  6250. $content_generation_requirement = $need_generate_content
  6251. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6252. : "";
  6253. // 美术风格
  6254. $input_art_style = getProp($data, 'art_style');
  6255. if (!$input_art_style) {
  6256. $mappedArtStyle = getProp($anime, 'art_style');
  6257. }else {
  6258. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6259. }
  6260. if (!$mappedArtStyle) {
  6261. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6262. }else {
  6263. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6264. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6265. }else {
  6266. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6267. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6268. }
  6269. }
  6270. // 构建主体、场景和道具提示词
  6271. $extra_role_prompt = "\n";
  6272. $extra_scene_prompt = "\n";
  6273. $extra_prop_prompt = "\n";
  6274. $ref_products = []; // 参考资产
  6275. if ($extra_products) {
  6276. foreach($extra_products as $item) {
  6277. $product = getProp($item, 'product');
  6278. $product_name = getProp($item, 'product_name');
  6279. if ($product_name == '旁白') continue;
  6280. $ref_products[$product_name] = $item;
  6281. $pic_prompt = getProp($item, 'pic_prompt');
  6282. if ((int)$product === 1) {
  6283. // 拼接角色信息
  6284. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6285. } elseif ((int)$product === 2) {
  6286. // 拼接场景信息
  6287. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6288. } elseif ((int)$product === 3) {
  6289. // 拼接道具信息
  6290. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6291. }
  6292. }
  6293. // 优化提示词,融入剧本
  6294. if (!empty(trim($extra_role_prompt))) {
  6295. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6296. }
  6297. if (!empty(trim($extra_scene_prompt))) {
  6298. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6299. }
  6300. if (!empty(trim($extra_prop_prompt))) {
  6301. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6302. }
  6303. }
  6304. if ($anime_script_id && $is_single) {
  6305. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6306. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6307. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6308. }else {
  6309. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6310. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6311. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6312. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6313. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6314. {$extra_role_prompt}";
  6315. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6316. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6317. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6318. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6319. {$extra_scene_prompt}";
  6320. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6321. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6322. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6323. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6324. {$extra_prop_prompt}";
  6325. }
  6326. $system_message = ['role'=>'system', 'content'=>$is_single
  6327. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6328. 强制要求:
  6329. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6330. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6331. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6332. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6333. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6334. 普通要求:
  6335. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6336. $role_demo
  6337. $scene_demo
  6338. $prop_demo
  6339. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6340. 5.1片段分割逻辑(优先级从高到低):
  6341. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6342. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6343. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6344. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6345. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6346. - 片段数量格式为: 片段数量:8
  6347. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6348. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6349. 5.3分镜结构:每个分镜包含以下字段:
  6350. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6351. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6352. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6353. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6354. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6355. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6356. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6357. - 运镜:场景+画面描述+运镜
  6358. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  6359. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  6360. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6361. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6362. 6.{$mappedArtStyle_prompt}\n\n
  6363. 示例如下:\n
  6364. ###剧本名:西昆仑
  6365. ###故事梗概
  6366. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6367. ###剧本亮点
  6368. 亮点1:绝境奇药,生死一线
  6369. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6370. 亮点2:结拜兄妹,化解尴尬
  6371. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6372. 亮点3:纤发夺命,情愫暗涌
  6373. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6374. ###人物关系
  6375. 阿雪与梁萧之间存在兄妹之情。
  6376. ###核心矛盾
  6377. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6378. ###主体列表
  6379. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6380. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6381. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6382. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6383. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6384. 全景,正面拍摄,青年女性,亚洲人。
  6385. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6386. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6387. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6388. ###美术风格
  6389. 基础画风风格词:厚涂古风
  6390. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6391. ###场景列表
  6392. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6393. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6394. 无人物。}
  6395. ###分段剧本
  6396. 片段数量:8
  6397. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6398. ##片段1
  6399. 时长:12s
  6400. 分镜1
  6401. 出场角色:刀疤脸
  6402. 场景:边境小镇街道
  6403. 出场道具:酒杯-高脚杯
  6404. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6405. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6406. 配音台词:
  6407. 背景音效:
  6408. 分镜2
  6409. 出场角色:刀疤脸
  6410. 场景:悦来酒馆
  6411. 出场道具:酒杯-高脚杯
  6412. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6413. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6414. 配音台词:
  6415. 背景音效:
  6416. 分镜3
  6417. 出场角色:刀疤脸
  6418. 场景:悦来酒馆
  6419. 出场道具:酒杯-高脚杯
  6420. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6421. 运镜:从中景推向令牌特写。
  6422. 配音台词:
  6423. 背景音效:
  6424. 分镜4
  6425. 出场角色:刀疤脸
  6426. 场景:悦来酒馆
  6427. 出场道具:酒杯-高脚杯
  6428. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6429. 运镜:极速推向酒水溅起的瞬间。
  6430. 配音台词:
  6431. 背景音效:
  6432. 分镜5
  6433. 出场角色:刀疤脸
  6434. 场景:悦来酒馆
  6435. 出场道具:酒杯-高脚杯
  6436. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6437. 运镜:固定机位,利用倾斜构图制造压迫感。
  6438. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6439. 背景音效:
  6440. \n\n"
  6441. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6442. 强制要求:\n
  6443. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6444. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6445. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6446. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6447. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6448. 普通要求:\n
  6449. 1.剧本名(必须生成)必须与文档内容高度相关
  6450. $role_demo
  6451. $scene_demo
  6452. $prop_demo
  6453. 5.{$mappedArtStyle_prompt}\n\n
  6454. 示例如下:\n
  6455. ###剧本名:西昆仑
  6456. ###故事梗概
  6457. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6458. ###剧本亮点
  6459. 亮点1:绝境奇药,生死一线
  6460. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6461. 亮点2:结拜兄妹,化解尴尬
  6462. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6463. 亮点3:纤发夺命,情愫暗涌
  6464. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6465. ###人物关系
  6466. 阿雪与梁萧之间存在兄妹之情。
  6467. ###核心矛盾
  6468. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6469. ###主体列表
  6470. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6471. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6472. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6473. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6474. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6475. 全景,正面拍摄,青年女性,亚洲人。
  6476. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6477. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6478. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6479. ###美术风格
  6480. 基础画风风格词:厚涂古风
  6481. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6482. ###场景列表
  6483. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6484. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6485. 无人物。}
  6486. ###道具列表
  6487. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  6488. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6489. $episode_count = $this->extractEpisodeNumber($prompt);
  6490. if ((int)getProp($anime, 'is_multi') !== 1) {
  6491. yield [
  6492. 'type' => 'done',
  6493. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6494. 'reasoning' => '',
  6495. 'usage' => []
  6496. ];
  6497. return;
  6498. }
  6499. if ($episode_count) {
  6500. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6501. $system_message = [
  6502. 'role' => 'system',
  6503. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6504. 强制要求:\n
  6505. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6506. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6507. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6508. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6509. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6510. 普通要求:\n
  6511. 1.<故事梗概>控制在200-300字左右
  6512. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6513. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6514. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6515. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6516. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6517. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6518. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6519. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6520. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6521. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6522. 示例如下:\n
  6523. ###剧本名:西昆仑
  6524. ###故事梗概
  6525. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6526. ###剧本亮点
  6527. 亮点1:绝境奇药,生死一线
  6528. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6529. 亮点2:结拜兄妹,化解尴尬
  6530. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6531. 亮点3:纤发夺命,情愫暗涌
  6532. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6533. ###人物关系
  6534. 阿雪与梁萧之间存在兄妹之情。
  6535. ###核心矛盾
  6536. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6537. ###主体列表
  6538. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6539. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6540. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6541. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6542. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6543. 全景,正面拍摄,青年女性,亚洲人。
  6544. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6545. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6546. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6547. ###美术风格
  6548. 基础画风风格词:厚涂古风
  6549. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6550. ###场景列表
  6551. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6552. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6553. 无人物。}
  6554. ###分集详细内容
  6555. ##第1章 重生
  6556. 我重生了。
  6557. 源于一个男人偏执的暗恋。
  6558. ##第2章 相救
  6559. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6560. 我眼睛扫向站在锅炉后的卞大伟。"
  6561. ];
  6562. // 构建消息
  6563. $messages = [
  6564. $system_message,
  6565. [
  6566. 'role' => 'user',
  6567. 'content' => "以下是文档内容:
  6568. {$content}
  6569. 用户问题:
  6570. {$question}"
  6571. ]
  6572. ];
  6573. }else {
  6574. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6575. // 构建消息
  6576. $messages = [
  6577. $system_message,
  6578. [
  6579. 'role' => 'user',
  6580. 'content' => "以下是文档内容:
  6581. {$content}
  6582. 用户问题:
  6583. {$question}"
  6584. ]
  6585. ];
  6586. }else {
  6587. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6588. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6589. return (array)$value;
  6590. })->toArray();
  6591. array_unshift($messages, $system_message);
  6592. $messages[] = [
  6593. 'role' => 'user',
  6594. 'content' => $prompt
  6595. ];
  6596. }
  6597. }
  6598. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6599. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6600. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6601. if ($model === 'deepseek-chat') {
  6602. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6603. $model = 'deepseek-v4-flash';
  6604. $thinkingMode = 'disabled';
  6605. } elseif ($model === 'deepseek-reasoner') {
  6606. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6607. $model = 'deepseek-v4-flash';
  6608. $thinkingMode = 'enabled';
  6609. }
  6610. $post_data = [
  6611. 'model' => $model,
  6612. 'messages' => $messages,
  6613. // 'max_tokens' => 8192,
  6614. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  6615. 'frequency_penalty' => 0,
  6616. 'presence_penalty' => 0,
  6617. 'response_format' => ['type' => 'text'],
  6618. 'thinking' => ['type' => $thinkingMode],
  6619. 'stream' => true // 启用流式输出
  6620. ];
  6621. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6622. // 根据模型类型选择调用方法
  6623. $fullContent = '';
  6624. $fullReasoningContent = '';
  6625. $usage = [];
  6626. // dd($post_data);
  6627. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6628. try {
  6629. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6630. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6631. } else if (in_array($model, $this->gpt_text_models)) {
  6632. // GPT-5.4 模型使用 TokenRouter API
  6633. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6634. } else {
  6635. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6636. }
  6637. // 验证返回值类型
  6638. if (!is_iterable($streamGenerator)) {
  6639. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6640. dLog('deepseek')->error('方法名流式生成器无效', [
  6641. 'generator_type' => $errorType,
  6642. 'model' => $model,
  6643. // 添加其他上下文信息
  6644. ]);
  6645. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6646. 'type' => $errorType,
  6647. 'model' => $model
  6648. ]);
  6649. yield [
  6650. 'type' => 'error',
  6651. // 根据方法返回相应的空数据结构
  6652. 'answer' => '',
  6653. 'reasoning' => '',
  6654. 'usage' => [],
  6655. 'error' => '接口返回数据异常,请重新请求'
  6656. ];
  6657. return;
  6658. }
  6659. // 处理流式输出
  6660. foreach ($streamGenerator as $chunk) {
  6661. if (isset($chunk['type'])) {
  6662. if ($chunk['type'] === 'done') {
  6663. $fullContent = $chunk['full_content'];
  6664. $fullReasoningContent = $chunk['full_reasoning'];
  6665. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6666. } else {
  6667. yield $chunk;
  6668. }
  6669. }
  6670. }
  6671. } catch (\Exception $e) {
  6672. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6673. 'model' => $model,
  6674. 'trace' => $e->getTraceAsString()
  6675. ]);
  6676. logDB('deepseek', 'error', '方法名流式处理失败', [
  6677. 'error' => $e->getMessage(),
  6678. 'model' => $model
  6679. ]);
  6680. yield [
  6681. 'type' => 'error',
  6682. // 根据方法返回相应的空数据结构
  6683. 'answer' => '',
  6684. 'reasoning' => '',
  6685. 'usage' => [],
  6686. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6687. ];
  6688. return;
  6689. }
  6690. dLog('deepseek')->info('完整内容: '.$fullContent);
  6691. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6692. // 处理完整内容并返回最终结果
  6693. $script_arr = [];
  6694. if ($fullContent) {
  6695. $script_arr = handleScriptContentForAce($fullContent);
  6696. dLog('deepseek')->info('解析内容', $script_arr);
  6697. logDB('deepseek', 'info', '解析内容', $script_arr);
  6698. }
  6699. if (empty($script_arr['roles'])) {
  6700. // 未生成剧本相关内容,保存对话记录并返回提示
  6701. dLog('deepseek')->info('未生成剧本相关的内容');
  6702. try {
  6703. $now = date('Y-m-d H:i:s');
  6704. // 保存对话记录
  6705. $records = [
  6706. [
  6707. 'uid' => $uid,
  6708. 'anime_id' => $anime_id,
  6709. 'sequence' => 0,
  6710. 'role' => 'user',
  6711. 'content' => $prompt,
  6712. 'created_at' => $now,
  6713. 'updated_at' => $now
  6714. ],
  6715. [
  6716. 'uid' => $uid,
  6717. 'anime_id' => $anime_id,
  6718. 'sequence' => 0,
  6719. 'role' => 'assistant',
  6720. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6721. 'created_at' => $now,
  6722. 'updated_at' => $now
  6723. ]
  6724. ];
  6725. DB::table('mp_anime_records')->insert($records);
  6726. } catch (\Exception $e) {
  6727. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6728. }
  6729. yield [
  6730. 'type' => 'done',
  6731. 'script' => [],
  6732. 'episode' => [],
  6733. 'answer' => $fullContent,
  6734. 'reasoning' => $fullReasoningContent,
  6735. 'usage' => $usage,
  6736. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6737. ];
  6738. return;
  6739. }
  6740. // 替换美术风格
  6741. if ($mappedArtStyle !== '') {
  6742. $script_arr['art_style'] = $mappedArtStyle;
  6743. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6744. }
  6745. if ($user_anime_name != '新剧本策划') {
  6746. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  6747. // 确认对话名称唯一性
  6748. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6749. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6750. }
  6751. }else {
  6752. $anime_name = $user_anime_name;
  6753. }
  6754. $table_data = [
  6755. 'user_id' => $uid,
  6756. 'model' => $model,
  6757. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6758. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6759. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6760. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6761. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6762. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6763. 'art_style_type' => $input_art_style,
  6764. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6765. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6766. 'status' => '解析完成',
  6767. 'generate_status' => '待执行',
  6768. 'updated_at' => date('Y-m-d H:i:s')
  6769. ];
  6770. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6771. // 如果是修改集数,则将content内容更新(会改变原文)
  6772. if (isset($episode_count) && $episode_count > 0) {
  6773. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6774. $table_data['start_episode_sequence'] = 1;
  6775. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6776. }else {
  6777. // 如果需要生成原文内容,从script_arr中提取
  6778. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6779. $table_data['content'] = $script_arr['content'];
  6780. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6781. if (!$table_data['content']) {
  6782. yield [
  6783. 'type' => 'done',
  6784. 'script' => [],
  6785. 'episode' => [],
  6786. 'answer' => $fullContent,
  6787. 'reasoning' => $fullReasoningContent,
  6788. 'usage' => $usage,
  6789. 'error' => '未生成剧本内容,请调整提示词再试'
  6790. ];
  6791. return;
  6792. }
  6793. }
  6794. if (isset($table_data['content']) && $table_data['content']) {
  6795. $chapters = splitContent($table_data['content']);
  6796. $chapter_count = count($chapters);
  6797. if ($chapter_count > 0) {
  6798. $table_data['start_episode_sequence'] = 1;
  6799. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6800. }
  6801. }
  6802. }
  6803. if ($extra_products) {
  6804. $table_data['extra_products'] = json_encode($extra_products, 256);
  6805. }
  6806. $single_episode = [];
  6807. try {
  6808. DB::beginTransaction();
  6809. $now = date('Y-m-d H:i:s');
  6810. // 更新动漫大纲
  6811. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6812. if (!$boolen) {
  6813. dLog('deepseek')->info('对话修改失败', $table_data);
  6814. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6815. Utils::throwError('20003:对话修改失败');
  6816. }
  6817. // 保存对话记录
  6818. $records = [
  6819. [
  6820. 'uid' => $uid,
  6821. 'anime_id' => $anime_id,
  6822. 'sequence' => 0,
  6823. 'role' => 'user',
  6824. 'content' => $prompt,
  6825. 'created_at' => $now,
  6826. 'updated_at' => $now
  6827. ],
  6828. [
  6829. 'uid' => $uid,
  6830. 'anime_id' => $anime_id,
  6831. 'sequence' => 0,
  6832. 'role' => 'assistant',
  6833. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6834. 'content' => $fullContent,
  6835. 'created_at' => $now,
  6836. 'updated_at' => $now
  6837. ]
  6838. ];
  6839. // 保存对话记录
  6840. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6841. if (!$boolen3) {
  6842. Utils::throwError('20003:对话记录保存失败');
  6843. }
  6844. // 单剧集模式:生成并保存剧集信息
  6845. if ($is_single) {
  6846. $anime_name = getProp($anime, 'anime_name', '未命名');
  6847. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6848. if (empty($episode_arr['acts'])) {
  6849. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6850. }
  6851. $saveResult = $this->saveEpisodeVersionData(
  6852. $anime_id,
  6853. 1,
  6854. $episode_arr,
  6855. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6856. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6857. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6858. null,
  6859. null,
  6860. false,
  6861. $content,
  6862. $now,
  6863. $ref_products
  6864. );
  6865. $single_episode = $saveResult['episode'];
  6866. $episode_id = $saveResult['episode_id'];
  6867. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6868. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6869. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6870. 'props' => json_encode($saveResult['merged_props'], 256),
  6871. 'updated_at' => $now
  6872. ]);
  6873. if ($boolen5 === false) {
  6874. Utils::throwError('20003:单剧集主表资源同步失败');
  6875. }
  6876. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6877. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6878. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6879. $episode_record_content = '确认分镜大纲';
  6880. if ($content !== '') {
  6881. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6882. }
  6883. $episode_records = [
  6884. [
  6885. 'uid' => $uid,
  6886. 'anime_id' => $anime_id,
  6887. 'role' => 'user',
  6888. 'content' => $episode_record_content,
  6889. 'sequence' => 1,
  6890. 'episode_id' => $episode_id,
  6891. 'created_at' => $now,
  6892. 'updated_at' => $now
  6893. ],
  6894. [
  6895. 'uid' => $uid,
  6896. 'anime_id' => $anime_id,
  6897. 'role' => 'assistant',
  6898. 'content' => $fullContent,
  6899. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6900. 'sequence' => 1,
  6901. 'episode_id' => $episode_id,
  6902. 'created_at' => $now,
  6903. 'updated_at' => $now
  6904. ]
  6905. ];
  6906. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6907. if (!$boolen4) {
  6908. Utils::throwError('20003:单剧集分镜记录保存失败');
  6909. }
  6910. }
  6911. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6912. if ($is_single && !empty($single_episode)) {
  6913. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6914. 'anime_id' => $anime_id,
  6915. 'episode_id' => $episode_id ?? 0,
  6916. ]);
  6917. }
  6918. }catch (\Exception $e) {
  6919. DB::rollBack();
  6920. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  6921. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  6922. yield [
  6923. 'type' => 'done',
  6924. 'answer' => $fullContent,
  6925. 'reasoning' => $fullReasoningContent,
  6926. 'usage' => $usage,
  6927. 'error' => $e->getMessage(),
  6928. ];
  6929. return;
  6930. }
  6931. DB::commit();
  6932. dLog('deepseek')->info('保存完毕');
  6933. if ($is_single && !empty($single_episode)) {
  6934. // $this->batchSetGlobalRoleImg([
  6935. // 'anime_id' => $anime_id,
  6936. // ]);
  6937. // $this->batchSetGlobalSceneImg([
  6938. // 'anime_id' => $anime_id,
  6939. // ]);
  6940. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6941. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6942. }
  6943. $table_data['anime_id'] = $anime_id;
  6944. $table_data['roles'] = json_decode($table_data['roles'], true);
  6945. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6946. $table_data['props'] = json_decode($table_data['props'], true);
  6947. unset($table_data['updated_at']);
  6948. unset($table_data['status']);
  6949. yield [
  6950. 'type' => 'done',
  6951. 'script' => $table_data,
  6952. 'episode' => $single_episode,
  6953. 'answer' => $fullContent,
  6954. 'reasoning' => $fullReasoningContent,
  6955. 'usage' => $usage
  6956. ];
  6957. }
  6958. public function chatForAce($data) {
  6959. $uid = Site::getUid();
  6960. // 积分余额预检(不足直接报错)
  6961. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  6962. $anime_id = getProp($data, 'anime_id');
  6963. $file = getProp($data, 'file');
  6964. $content = getProp($data, 'content', '');
  6965. $bid = getProp($data, 'bid', 0);
  6966. $script_id = getProp($data, 'script_id', 0);
  6967. $episode_number = getProp($data, 'episode_number', 1);
  6968. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6969. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6970. if (!$anime) Utils::throwError('20003:该对话不存在!');
  6971. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  6972. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  6973. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  6974. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  6975. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  6976. $roles = is_array($roles) ? $roles : [];
  6977. $scenes = is_array($scenes) ? $scenes : [];
  6978. $extra_products = getProp($data, 'products', []);
  6979. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6980. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6981. $anime_script_id = getProp($anime, 'script_id');
  6982. if ($anime_script_id) {
  6983. $cpid = Site::getCpid();
  6984. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6985. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6986. ->where('mapping.script_id', $anime_script_id)
  6987. ->where('product.cpid', $cpid)
  6988. ->where('product.is_deleted', 0);
  6989. // 如果提供了 episode_number,则过滤指定集数
  6990. if ($episode_number !== null && $episode_number !== '') {
  6991. $script_products_mappings->where('mapping.episode_number', $episode_number);
  6992. }
  6993. $mappings = $script_products_mappings->select(
  6994. 'mapping.product_id',
  6995. 'mapping.episode_number',
  6996. 'product.product_name',
  6997. 'product.type',
  6998. 'product.product',
  6999. 'product.pic_prompt',
  7000. 'product.url',
  7001. 'product.pic_task_id',
  7002. 'product.pic_task_status',
  7003. 'product.three_view_image_url'
  7004. )
  7005. ->get();
  7006. // 按 product_id 分组,合并 episode_number
  7007. $productMap = [];
  7008. foreach ($mappings as $item) {
  7009. $product_id = $item->product_id;
  7010. $product_name = $item->product_name;
  7011. // 处理product_name两边的符号
  7012. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7013. if (!isset($productMap[$product_id])) {
  7014. $productMap[$product_id] = [
  7015. 'product_id' => $product_id,
  7016. 'product_name' => $product_name,
  7017. 'type' => (int)$item->type,
  7018. 'product' => (int)$item->product,
  7019. 'pic_prompt' => $item->pic_prompt,
  7020. 'url' => $item->url,
  7021. 'pic_task_id' => $item->pic_task_id,
  7022. 'pic_task_status' => $item->pic_task_status,
  7023. 'episode_numbers' => [],
  7024. ];
  7025. }
  7026. // 添加 episode_number(去重)
  7027. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7028. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7029. }
  7030. }
  7031. // 将查询到的剧本资产合并到extra_products中
  7032. // 先构建extra_products的索引(以product_id+episode_number为key)
  7033. $extraProductsMap = [];
  7034. foreach ($extra_products as $item) {
  7035. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  7036. $extraProductsMap[$key] = $item;
  7037. }
  7038. // 合并剧本资产(去重:product_id+episode_number)
  7039. foreach ($productMap as $product) {
  7040. foreach ($product['episode_numbers'] as $ep_num) {
  7041. $key = $product['product_id'] . '_' . $ep_num;
  7042. // 如果不存在则添加
  7043. if (!isset($extraProductsMap[$key])) {
  7044. $extraProductsMap[$key] = [
  7045. 'product_id' => $product['product_id'],
  7046. 'product_name' => $product['product_name'],
  7047. 'type' => $product['type'],
  7048. 'product' => $product['product'],
  7049. 'pic_prompt' => $product['pic_prompt'],
  7050. 'url' => $product['url'],
  7051. 'pic_task_id' => $product['pic_task_id'],
  7052. 'pic_task_status' => $product['pic_task_status'],
  7053. 'episode_number' => $ep_num,
  7054. ];
  7055. }
  7056. }
  7057. }
  7058. // 重新赋值给extra_products
  7059. $extra_products = array_values($extraProductsMap);
  7060. }
  7061. // 处理提示词
  7062. if ($prompt && $extra_products) {
  7063. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7064. foreach($extra_products as $item) {
  7065. $product_name = getProp($item, 'product_name');
  7066. if ($product_name) {
  7067. // 替换 {product_name} 为 product_name
  7068. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7069. }
  7070. }
  7071. }
  7072. // 获取最后一集序号
  7073. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  7074. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  7075. // 转换主体列表和场景列表的格式
  7076. // 获取参考主体或场景
  7077. if ((int)$episode_number === 1) {
  7078. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  7079. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  7080. }else {
  7081. $prev_episode_number = $episode_number - 1;
  7082. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  7083. }
  7084. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  7085. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  7086. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  7087. // 合并anime_products和extra_products(extra_products优先,去重)
  7088. $anime_products = getProp($anime, 'extra_products');
  7089. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  7090. $ref_products = [];
  7091. foreach($anime_products as $item) {
  7092. $product_name = getProp($item, 'product_name');
  7093. $ref_products[$product_name] = $item;
  7094. }
  7095. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  7096. $extra_roles = []; // 从extra_products中提取的角色
  7097. $extra_scenes = []; // 从extra_products中提取的场景
  7098. $extra_props = []; // 从extra_products中提取的道具
  7099. if ($extra_products && is_array($extra_products)) {
  7100. foreach($extra_products as $item) {
  7101. $product = (int)getProp($item, 'product');
  7102. $product_name = getProp($item, 'product_name');
  7103. if ($product_name == '旁白') continue;
  7104. $pic_prompt = getProp($item, 'pic_prompt');
  7105. $ref_products[$product_name] = $item;
  7106. if ($product === 1) {
  7107. // 角色
  7108. $extra_roles[$product_name] = [
  7109. 'role' => $product_name,
  7110. 'pic_prompt' => $pic_prompt,
  7111. 'url' => getProp($item, 'url', ''),
  7112. ];
  7113. } elseif ($product === 2) {
  7114. // 场景
  7115. $extra_scenes[$product_name] = [
  7116. 'scene' => $product_name,
  7117. 'pic_prompt' => $pic_prompt,
  7118. 'url' => getProp($item, 'url', ''),
  7119. ];
  7120. } elseif ($product === 3) {
  7121. // 道具
  7122. $extra_props[$product_name] = [
  7123. 'prop' => $product_name,
  7124. 'pic_prompt' => $pic_prompt,
  7125. 'url' => getProp($item, 'url', ''),
  7126. ];
  7127. }
  7128. }
  7129. }
  7130. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  7131. $merged_roles = [];
  7132. foreach($ref_roles as $role) {
  7133. $role_name = getProp($role, 'role');
  7134. if (!isset($extra_roles[$role_name])) {
  7135. $merged_roles[$role_name] = $role;
  7136. }
  7137. }
  7138. // 添加extra_roles
  7139. foreach($extra_roles as $role_name => $role) {
  7140. $merged_roles[$role_name] = $role;
  7141. }
  7142. $ref_roles = array_values($merged_roles);
  7143. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  7144. $merged_scenes = [];
  7145. foreach($ref_scenes as $scene) {
  7146. $scene_name = getProp($scene, 'scene');
  7147. if (!isset($extra_scenes[$scene_name])) {
  7148. $merged_scenes[$scene_name] = $scene;
  7149. }
  7150. }
  7151. // 添加extra_scenes
  7152. foreach($extra_scenes as $scene_name => $scene) {
  7153. $merged_scenes[$scene_name] = $scene;
  7154. }
  7155. $ref_scenes = array_values($merged_scenes);
  7156. // 合并ref_props和extra_props(extra_props优先,去重)
  7157. $merged_props = [];
  7158. foreach($ref_props as $prop) {
  7159. $prop_name = getProp($prop, 'prop');
  7160. if (!isset($extra_props[$prop_name])) {
  7161. $merged_props[$prop_name] = $prop;
  7162. }
  7163. }
  7164. // 添加extra_props
  7165. foreach($extra_props as $prop_name => $prop) {
  7166. $merged_props[$prop_name] = $prop;
  7167. }
  7168. $ref_props = array_values($merged_props);
  7169. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  7170. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  7171. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  7172. // 构建强制主体、场景和道具提示词
  7173. $forced_roles_prompt = "";
  7174. $forced_scenes_prompt = "";
  7175. $forced_props_prompt = "";
  7176. if (!empty($extra_roles)) {
  7177. $forced_roles_list = "";
  7178. foreach($extra_roles as $role_name => $role) {
  7179. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  7180. }
  7181. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7182. }
  7183. if (!empty($extra_scenes)) {
  7184. $forced_scenes_list = "";
  7185. foreach($extra_scenes as $scene_name => $scene) {
  7186. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  7187. }
  7188. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7189. }
  7190. if (!empty($extra_props)) {
  7191. $forced_props_list = "";
  7192. foreach($extra_props as $prop_name => $prop) {
  7193. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  7194. }
  7195. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7196. }
  7197. if ($anime_script_id) {
  7198. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  7199. }else if ($roles_content) {
  7200. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  7201. 主体范围:\n {$roles_content}\n
  7202. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  7203. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7204. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7205. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7206. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7207. }else {
  7208. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7209. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7210. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7211. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7212. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7213. }
  7214. if ($anime_script_id) {
  7215. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  7216. }else if ($scenes_content) {
  7217. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7218. 场景范围:\n {$scenes_content}\n
  7219. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  7220. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  7221. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7222. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7223. }else {
  7224. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7225. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7226. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7227. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7228. }
  7229. if ($anime_script_id) {
  7230. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  7231. }else if ($props_content) {
  7232. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7233. 道具范围:\n {$props_content}\n
  7234. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  7235. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  7236. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7237. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7238. }else {
  7239. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7240. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  7241. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7242. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7243. }
  7244. // 提取文件内容
  7245. if ($file) {
  7246. $uploaded_content = $this->extractFileContent($file);
  7247. if (!$uploaded_content) {
  7248. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7249. }
  7250. } elseif ($script_id) {
  7251. $uploaded_content = $this->getContentByScriptId($script_id);
  7252. if (!$uploaded_content) {
  7253. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7254. }
  7255. } elseif ($bid) {
  7256. $uploaded_content = $this->getContentByBid($bid);
  7257. if (!$uploaded_content) {
  7258. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7259. }
  7260. } elseif ($content) {
  7261. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  7262. }
  7263. // elseif ($prompt) {
  7264. // $uploaded_content = filterContent($prompt);
  7265. // }
  7266. else {
  7267. $uploaded_content = '';
  7268. }
  7269. // 美术风格
  7270. $input_art_style = getProp($data, 'art_style');
  7271. if (!$input_art_style) {
  7272. $mappedArtStyle = getProp($anime, 'art_style');
  7273. }else {
  7274. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7275. }
  7276. if (!$mappedArtStyle) {
  7277. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7278. }else {
  7279. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7280. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7281. }else {
  7282. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7283. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7284. }
  7285. }
  7286. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7287. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7288. // 强制要求:
  7289. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7290. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7291. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7292. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  7293. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  7294. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  7295. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  7296. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  7297. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  7298. // 10.分镜要和场景列表、人物主体保持一致\n
  7299. // 普通要求:
  7300. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7301. // {$role_demo}
  7302. // {$scene_demo}
  7303. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7304. // 4.1片段分割逻辑(优先级从高到低):
  7305. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7306. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7307. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7308. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7309. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7310. // - 片段数量格式为: 片段数量:8
  7311. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7312. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7313. // 4.3分镜结构:每个分镜包含以下字段:
  7314. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  7315. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  7316. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7317. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  7318. // - 运镜:场景+画面描述+运镜
  7319. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  7320. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7321. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7322. // 5.$mappedArtStyle_prompt\n\n
  7323. // 示例格式:\n
  7324. // 第1集:隐形的守护者
  7325. // ###故事梗概
  7326. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7327. // ###美术风格
  7328. // 基础画风风格词:胡金铨武侠
  7329. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7330. // ###主体列表
  7331. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7332. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7333. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7334. // ###场景列表
  7335. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7336. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7337. // ###分段剧本
  7338. // 片段数量:8
  7339. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7340. // ##片段1
  7341. // 时长:12s
  7342. // 分镜1
  7343. // 场景:边境小镇街道
  7344. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7345. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7346. // 配音台词:
  7347. // 背景音效:
  7348. // 分镜2
  7349. // 场景:悦来酒馆
  7350. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7351. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7352. // 配音台词:
  7353. // 背景音效:
  7354. // 分镜3
  7355. // 场景:悦来酒馆
  7356. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7357. // 运镜:从中景推向令牌特写。
  7358. // 配音台词:
  7359. // 背景音效:
  7360. // 分镜4
  7361. // 场景:悦来酒馆
  7362. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7363. // 运镜:极速推向酒水溅起的瞬间。
  7364. // 配音台词:
  7365. // 背景音效:
  7366. // 分镜5
  7367. // 镜头描述
  7368. // 场景:悦来酒馆
  7369. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7370. // 运镜:固定机位,利用倾斜构图制造压迫感。
  7371. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7372. // 背景音效:
  7373. // \n\n";
  7374. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7375. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7376. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  7377. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  7378. 普通要求:
  7379. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7380. {$role_demo}
  7381. {$scene_demo}
  7382. {$prop_demo}
  7383. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7384. 5.1片段分割逻辑(优先级从高到低):
  7385. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7386. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7387. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7388. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7389. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7390. - 片段数量格式为: 片段数量:8
  7391. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7392. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7393. 5.3分镜结构:每个分镜包含以下字段:
  7394. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7395. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7396. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7397. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7398. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7399. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7400. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7401. - 运镜:场景+画面描述+运镜
  7402. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7403. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7404. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7405. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7406. 6.《情绪-视听语言映射表》:
  7407. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7408. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7409. -----|---------|------------|----------------
  7410. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7411. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7412. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7413. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7414. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7415. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7416. -----|---------|------------|----------------
  7417. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7418. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7419. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7420. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7421. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7422. --------|---------|--------------|-------------
  7423. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7424. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7425. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7426. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7427. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7428. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7429. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7430. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7431. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7432. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7433. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7434. -----|---------|------------|------------
  7435. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7436. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7437. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7438. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7439. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7440. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7441. --------|---------|--------------|----------
  7442. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7443. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7444. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7445. 6.6 声音设计与潜意识影响 (Soundscape)
  7446. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7447. -----|---------|------------|------------------
  7448. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7449. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7450. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7451. 理论基石:
  7452. - The Five C's of Cinematography by Joseph V. Mascelli
  7453. - Film Art: An Introduction by David Bordwell
  7454. - Sight, Sound, Motion by Herbert Zettl
  7455. - Notes on the Cinematograph by Robert Bresson
  7456. \n\n
  7457. 7.{$mappedArtStyle_prompt}
  7458. 示例格式:\n
  7459. 第1集:隐形的守护者
  7460. ###故事梗概
  7461. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7462. ###美术风格
  7463. 基础画风风格词:胡金铨武侠
  7464. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7465. ###主体列表
  7466. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7467. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7468. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7469. ###场景列表
  7470. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7471. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7472. ###道具列表
  7473. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  7474. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  7475. ###分段剧本
  7476. 片段数量:8
  7477. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7478. ##片段1
  7479. 时长:12s
  7480. 分镜1
  7481. 出场角色:刀疤脸
  7482. 场景:边境小镇街道
  7483. 出场道具:酒杯-高脚杯
  7484. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7485. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7486. 配音台词:
  7487. 背景音效:
  7488. 分镜2
  7489. 出场角色:刀疤脸
  7490. 场景:悦来酒馆
  7491. 出场道具:酒杯-高脚杯
  7492. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7493. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7494. 配音台词:
  7495. 背景音效:
  7496. 分镜3
  7497. 出场角色:刀疤脸
  7498. 场景:悦来酒馆
  7499. 出场道具:酒杯-高脚杯
  7500. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7501. 运镜:从中景推向令牌特写。
  7502. 配音台词:
  7503. 背景音效:
  7504. 分镜4
  7505. 出场角色:刀疤脸
  7506. 场景:悦来酒馆
  7507. 出场道具:酒杯-高脚杯
  7508. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7509. 运镜:极速推向酒水溅起的瞬间。
  7510. 配音台词:
  7511. 背景音效:
  7512. 分镜5
  7513. 出场角色:刀疤脸
  7514. 场景:悦来酒馆
  7515. 出场道具:酒杯-高脚杯
  7516. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7517. 运镜:固定机位,利用倾斜构图制造压迫感。
  7518. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7519. 背景音效:
  7520. \n\n";
  7521. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7522. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  7523. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7524. $prompt = $origin_prompt;
  7525. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7526. // 获取章节内容
  7527. $full_content = getProp($anime, 'content');
  7528. if ($uploaded_content) {
  7529. $full_content = $uploaded_content;
  7530. }
  7531. // 根据章节内容拆分章节
  7532. $chapters = splitContent($full_content);
  7533. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7534. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7535. $messages = [];
  7536. if ($prompt == '确认分镜大纲') {
  7537. // 暂时保留
  7538. $content = $chapter_content;
  7539. if ($is_single) $content = $full_content; // 单剧集使用全文
  7540. if (!$content) {
  7541. Utils::throwError('20003:章节内容无法获取,请确认');
  7542. }
  7543. $question = $is_single
  7544. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7545. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7546. // 构建消息
  7547. $messages[] =
  7548. [
  7549. 'role' => 'user',
  7550. 'content' => $question
  7551. ];
  7552. }else if ($prompt == '继续策划下一集') {
  7553. if ($is_single) {
  7554. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7555. }
  7556. $content = $chapter_content;
  7557. if (!$content) {
  7558. Utils::throwError('20003:章节内容无法获取,请确认');
  7559. }
  7560. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7561. // 获取上一集最后记录
  7562. $prev_sequence = $episode_number - 1;
  7563. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7564. // 构建消息
  7565. $messages[] =
  7566. [
  7567. 'role' => 'user',
  7568. 'content' => $question
  7569. ];
  7570. // dd($messages);
  7571. }else {
  7572. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7573. if (!$content) {
  7574. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7575. }
  7576. if (!$content) {
  7577. Utils::throwError('20003:章节内容无法获取,请确认');
  7578. }
  7579. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7580. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7581. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7582. if ($origin_prompt) {
  7583. $question .= "本次修改要求如下:\n{$origin_prompt}";
  7584. }
  7585. $messages[] =
  7586. [
  7587. 'role' => 'user',
  7588. 'content' => $question
  7589. ];
  7590. }
  7591. // 处理文本模型
  7592. $model = getProp($data, 'model');
  7593. if (!$model) {
  7594. // 用户没有输入,从anime表获取
  7595. $model = getProp($anime, 'model');
  7596. if (!$model) {
  7597. // anime表也没有,使用默认值
  7598. $model = 'deepseek-v4-pro';
  7599. }
  7600. }
  7601. // 验证模型是否在可用模型表中
  7602. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7603. $model = 'deepseek-v4-pro';
  7604. }
  7605. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7606. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7607. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7608. if ($model === 'deepseek-chat') {
  7609. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7610. $model = 'deepseek-v4-flash';
  7611. $thinkingMode = 'disabled';
  7612. } elseif ($model === 'deepseek-reasoner') {
  7613. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7614. $model = 'deepseek-v4-flash';
  7615. $thinkingMode = 'enabled';
  7616. }
  7617. $post_data = [
  7618. 'model' => $model,
  7619. 'messages' => $messages,
  7620. // 'max_tokens' => 8192,
  7621. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7622. 'frequency_penalty' => 0,
  7623. 'presence_penalty' => 0,
  7624. 'response_format' => ['type' => 'text'],
  7625. 'thinking' => ['type' => $thinkingMode],
  7626. 'stream' => true // 启用流式输出
  7627. ];
  7628. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7629. // 根据模型类型选择调用方法
  7630. $fullContent = '';
  7631. $fullReasoningContent = '';
  7632. $usage = [];
  7633. try {
  7634. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7635. // DeepSeek 官方模型使用 DeepSeek API
  7636. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7637. } else if (in_array($model, $this->gpt_text_models)) {
  7638. // GPT-5.4 模型使用 TokenRouter API
  7639. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7640. } else {
  7641. // 其他模型使用火山引擎API
  7642. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7643. }
  7644. // 验证返回值类型
  7645. if (!is_iterable($streamGenerator)) {
  7646. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7647. dLog('deepseek')->error('chat流式生成器无效', [
  7648. 'generator_type' => $errorType,
  7649. 'model' => $model,
  7650. 'anime_id' => $anime_id,
  7651. 'episode_number' => $episode_number
  7652. ]);
  7653. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7654. 'type' => $errorType,
  7655. 'model' => $model
  7656. ]);
  7657. yield [
  7658. 'type' => 'error',
  7659. 'episode' => [],
  7660. 'answer' => '',
  7661. 'reasoning' => '',
  7662. 'usage' => [],
  7663. 'error' => '接口返回数据异常,请重新请求'
  7664. ];
  7665. return;
  7666. }
  7667. // 处理流式输出
  7668. foreach ($streamGenerator as $chunk) {
  7669. if (isset($chunk['type'])) {
  7670. if ($chunk['type'] === 'done') {
  7671. // 最终结果
  7672. $fullContent = $chunk['full_content'];
  7673. $fullReasoningContent = $chunk['full_reasoning'];
  7674. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7675. } else {
  7676. // 逐块yield数据
  7677. yield $chunk;
  7678. }
  7679. }
  7680. }
  7681. } catch (\Exception $e) {
  7682. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7683. 'model' => $model,
  7684. 'anime_id' => $anime_id,
  7685. 'episode_number' => $episode_number,
  7686. 'trace' => $e->getTraceAsString()
  7687. ]);
  7688. logDB('deepseek', 'error', 'chat流式处理失败', [
  7689. 'error' => $e->getMessage(),
  7690. 'model' => $model
  7691. ]);
  7692. yield [
  7693. 'type' => 'error',
  7694. 'episode' => [],
  7695. 'answer' => '',
  7696. 'reasoning' => '',
  7697. 'usage' => [],
  7698. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7699. ];
  7700. return;
  7701. }
  7702. dLog('deepseek')->info('完整内容: '.$fullContent);
  7703. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7704. // 处理完整内容并返回最终结果
  7705. $episode_arr = handleEpisodeContentForAce($fullContent);
  7706. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7707. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  7708. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7709. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7710. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  7711. // }
  7712. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  7713. $max_retries = 3;
  7714. $retry_count = 0;
  7715. $validation_failed = false;
  7716. $validation_error_msg = '';
  7717. // 验证生成的内容
  7718. if ($anime_script_id) {
  7719. // 检查是否有acts数据
  7720. if (empty($episode_arr['acts'])) {
  7721. $validation_failed = true;
  7722. $validation_error_msg = '未生成分镜剧本相关的内容';
  7723. } else {
  7724. // 检查主体列表是否匹配 - 只验证生成的主体名是否都在预期列表中
  7725. $generated_roles = array_column($episode_arr['roles'], 'role');
  7726. // 过滤掉"旁白"角色
  7727. $generated_roles = array_filter($generated_roles, function($role) {
  7728. return $role !== '旁白';
  7729. });
  7730. $expected_roles = array_keys($extra_roles);
  7731. // 找出生成的主体中不在预期列表中的主体
  7732. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7733. if (!empty($invalid_roles)) {
  7734. $validation_failed = true;
  7735. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7736. }
  7737. // 检查场景列表是否匹配 - 只验证生成的场景名是否都在预期列表中
  7738. if (!$validation_failed) {
  7739. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7740. $expected_scenes = array_keys($extra_scenes);
  7741. // 找出生成的场景中不在预期列表中的场景
  7742. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7743. if (!empty($invalid_scenes)) {
  7744. $validation_failed = true;
  7745. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7746. }
  7747. }
  7748. }
  7749. } else {
  7750. // 如果没有anime_script_id,只检查是否有acts数据
  7751. if (empty($episode_arr['acts'])) {
  7752. $validation_failed = true;
  7753. $validation_error_msg = '未生成分镜剧本相关的内容';
  7754. }
  7755. }
  7756. // 重试逻辑
  7757. while ($validation_failed && $retry_count < $max_retries) {
  7758. $retry_count++;
  7759. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  7760. 'reason' => $validation_error_msg,
  7761. 'anime_id' => $anime_id,
  7762. 'episode_number' => $episode_number
  7763. ]);
  7764. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  7765. 'reason' => $validation_error_msg,
  7766. 'anime_id' => $anime_id
  7767. ]);
  7768. // 发送流式重试提示
  7769. yield [
  7770. 'type' => 'retry',
  7771. 'retry_count' => $retry_count,
  7772. 'reason' => $validation_error_msg
  7773. ];
  7774. // 构建重试提示词
  7775. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  7776. if ($anime_script_id) {
  7777. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  7778. $retry_prompt .= "2. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  7779. $retry_prompt .= "3. 必须包含完整的分镜剧本内容\n";
  7780. } else {
  7781. $retry_prompt .= "1. 必须包含完整的分镜剧本内容\n";
  7782. }
  7783. // 添加重试消息到messages
  7784. $messages[] = [
  7785. 'role' => 'assistant',
  7786. 'content' => $fullContent
  7787. ];
  7788. $messages[] = [
  7789. 'role' => 'user',
  7790. 'content' => $retry_prompt
  7791. ];
  7792. // 更新post_data的messages
  7793. $post_data['messages'] = $messages;
  7794. // 重新调用API
  7795. try {
  7796. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7797. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7798. } else if (in_array($model, $this->gpt_text_models)) {
  7799. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7800. } else {
  7801. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7802. }
  7803. // 处理流式输出
  7804. $fullContent = '';
  7805. $fullReasoningContent = '';
  7806. foreach ($streamGenerator as $chunk) {
  7807. if (isset($chunk['type'])) {
  7808. if ($chunk['type'] === 'done') {
  7809. $fullContent = $chunk['full_content'];
  7810. $fullReasoningContent = $chunk['full_reasoning'];
  7811. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7812. } else {
  7813. yield $chunk;
  7814. }
  7815. }
  7816. }
  7817. // 重新解析内容
  7818. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  7819. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  7820. $episode_arr = handleEpisodeContentForAce($fullContent);
  7821. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  7822. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7823. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7824. // }
  7825. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  7826. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  7827. // 重新验证
  7828. $validation_failed = false;
  7829. $validation_error_msg = '';
  7830. if ($anime_script_id) {
  7831. if (empty($episode_arr['acts'])) {
  7832. $validation_failed = true;
  7833. $validation_error_msg = '未生成分镜剧本相关的内容';
  7834. } else {
  7835. // 检查主体列表 - 只验证生成的主体名是否都在预期列表中
  7836. $generated_roles = array_column($episode_arr['roles'], 'role');
  7837. // 过滤掉"旁白"角色
  7838. $generated_roles = array_filter($generated_roles, function($role) {
  7839. return $role !== '旁白';
  7840. });
  7841. $expected_roles = array_keys($extra_roles);
  7842. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7843. if (!empty($invalid_roles)) {
  7844. $validation_failed = true;
  7845. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7846. }
  7847. // 检查场景列表 - 只验证生成的场景名是否都在预期列表中
  7848. if (!$validation_failed) {
  7849. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7850. $expected_scenes = array_keys($extra_scenes);
  7851. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7852. if (!empty($invalid_scenes)) {
  7853. $validation_failed = true;
  7854. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7855. }
  7856. }
  7857. }
  7858. } else {
  7859. if (empty($episode_arr['acts'])) {
  7860. $validation_failed = true;
  7861. $validation_error_msg = '未生成分镜剧本相关的内容';
  7862. }
  7863. }
  7864. } catch (\Exception $e) {
  7865. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  7866. 'trace' => $e->getTraceAsString()
  7867. ]);
  7868. break;
  7869. }
  7870. }
  7871. // 如果重试后仍然失败
  7872. if ($validation_failed) {
  7873. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  7874. 'retry_count' => $retry_count,
  7875. 'last_error' => $validation_error_msg
  7876. ]);
  7877. try {
  7878. $now = date('Y-m-d H:i:s');
  7879. $records = [
  7880. [
  7881. 'uid' => $uid,
  7882. 'anime_id' => $anime_id,
  7883. 'sequence' => $episode_number,
  7884. 'role' => 'user',
  7885. 'content' => $prompt,
  7886. 'created_at' => $now,
  7887. 'updated_at' => $now
  7888. ],
  7889. [
  7890. 'uid' => $uid,
  7891. 'anime_id' => $anime_id,
  7892. 'sequence' => $episode_number,
  7893. 'role' => 'assistant',
  7894. 'content' => $fullContent,
  7895. 'created_at' => $now,
  7896. 'updated_at' => $now
  7897. ]
  7898. ];
  7899. DB::table('mp_anime_records')->insert($records);
  7900. } catch (\Exception $e) {
  7901. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7902. }
  7903. yield [
  7904. 'type' => 'done',
  7905. 'episode' => [],
  7906. 'answer' => $fullContent,
  7907. 'reasoning' => $fullReasoningContent,
  7908. 'usage' => $usage,
  7909. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  7910. ];
  7911. return;
  7912. }
  7913. // 验证成功,记录日志
  7914. if ($retry_count > 0) {
  7915. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  7916. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  7917. }
  7918. // 老逻辑
  7919. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  7920. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  7921. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  7922. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  7923. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  7924. $existing_props = is_array($existing_props) ? $existing_props : [];
  7925. $now = date('Y-m-d H:i:s');
  7926. try {
  7927. DB::beginTransaction();
  7928. $saveResult = $this->saveEpisodeVersionData(
  7929. $anime_id,
  7930. $episode_number,
  7931. $episode_arr,
  7932. $existing_roles,
  7933. $existing_scenes,
  7934. $existing_props,
  7935. $current_episode,
  7936. $base_episode,
  7937. $is_regenerate_version,
  7938. $content,
  7939. $now,
  7940. $ref_products
  7941. );
  7942. $episode = $saveResult['episode'];
  7943. $episode_id = $saveResult['episode_id'];
  7944. $merged_roles = $saveResult['merged_roles'];
  7945. $merged_scenes = $saveResult['merged_scenes'];
  7946. $merged_props = $saveResult['merged_props'];
  7947. $record_content = $origin_prompt;
  7948. if ($uploaded_content !== '') {
  7949. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  7950. }
  7951. $records = [
  7952. [
  7953. 'uid' => $uid,
  7954. 'anime_id' => $anime_id,
  7955. 'role' => 'user',
  7956. 'content' => $record_content,
  7957. 'sequence' => $episode_number,
  7958. 'episode_id' => $episode_id,
  7959. 'created_at' => $now,
  7960. 'updated_at' => $now
  7961. ],
  7962. [
  7963. 'uid' => $uid,
  7964. 'anime_id' => $anime_id,
  7965. 'role' => 'assistant',
  7966. 'content' => $fullContent,
  7967. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7968. 'sequence' => $episode_number,
  7969. 'episode_id' => $episode_id,
  7970. 'created_at' => $now,
  7971. 'updated_at' => $now
  7972. ]
  7973. ];
  7974. $boolen4 = DB::table('mp_anime_records')->insert($records);
  7975. if (!$boolen4) {
  7976. Utils::throwError('20003:对话记录保存失败');
  7977. }
  7978. // 保存模型到anime表
  7979. $update_anime_data = [
  7980. 'model' => $model,
  7981. 'updated_at' => $now
  7982. ];
  7983. if ($uploaded_content) {
  7984. $update_anime_data['content'] = $uploaded_content;
  7985. }
  7986. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  7987. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7988. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7989. 'anime_id' => $anime_id,
  7990. 'episode_number' => $episode_number,
  7991. 'model' => $model,
  7992. ]);
  7993. }catch (\Exception $e) {
  7994. DB::rollBack();
  7995. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7996. yield [
  7997. 'type' => 'done',
  7998. 'answer' => $fullContent,
  7999. 'reasoning' => $fullReasoningContent,
  8000. 'usage' => $usage,
  8001. 'error' => $e->getMessage(),
  8002. ];
  8003. return;
  8004. }
  8005. DB::commit();
  8006. if ($is_global_generate_pics) {
  8007. // // 批量生成全局角色图片
  8008. // $this->batchSetGlobalRoleImg([
  8009. // 'anime_id' => $anime_id,
  8010. // ], true);
  8011. // // 批量生成全局场景图片
  8012. // $this->batchSetGlobalSceneImg([
  8013. // 'anime_id' => $anime_id,
  8014. // ], true);
  8015. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8016. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8017. }
  8018. $episode['episode_id'] = $episode_id;
  8019. $episode['roles'] = $merged_roles;
  8020. $episode['scenes'] = $merged_scenes;
  8021. $episode['props'] = $merged_props;
  8022. $episode['end_episode_sequence'] = $end_episode_sequence;
  8023. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  8024. yield [
  8025. 'type' => 'done',
  8026. 'episode' => $episode,
  8027. 'answer' => $fullContent,
  8028. 'reasoning' => $fullReasoningContent,
  8029. 'usage' => $usage
  8030. ];
  8031. }
  8032. /**
  8033. * chatForAce的非流式版本 - 用于定时任务
  8034. * 只获取最终 type=done 的数据,并验证必要字段
  8035. *
  8036. * @param array $data 请求数据
  8037. * @return array 生成结果
  8038. */
  8039. public function chatForAceNonStream($data) {
  8040. $finalResult = null;
  8041. // 调用流式方法,只保存 type=done 的数据
  8042. foreach ($this->chatForAce($data) as $chunk) {
  8043. // 只关注最终结果
  8044. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  8045. $finalResult = $chunk;
  8046. break; // 找到 done 就退出循环
  8047. }
  8048. }
  8049. // 验证最终结果
  8050. if (!$finalResult) {
  8051. return ['error' => '生成失败:未获取到最终结果'];
  8052. }
  8053. // 检查是否有错误
  8054. if (isset($finalResult['error']) && $finalResult['error']) {
  8055. return $finalResult;
  8056. }
  8057. // 验证必要字段
  8058. $episode = $finalResult['episode'] ?? [];
  8059. // 验证 roles
  8060. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  8061. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  8062. }
  8063. // 验证 scenes
  8064. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  8065. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  8066. }
  8067. // 验证 props(道具可以为空,但必须存在且为数组)
  8068. if (!isset($episode['props']) || !is_array($episode['props'])) {
  8069. $episode['props'] = [];
  8070. }
  8071. // 验证 acts(分镜剧本)
  8072. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  8073. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  8074. }
  8075. // 更新验证后的 episode 数据
  8076. $finalResult['episode'] = $episode;
  8077. // 记录验证成功日志
  8078. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  8079. 'roles_count' => count($episode['roles']),
  8080. 'scenes_count' => count($episode['scenes']),
  8081. 'props_count' => count($episode['props']),
  8082. 'acts_count' => count($episode['acts'])
  8083. ]);
  8084. return $finalResult;
  8085. }
  8086. /**
  8087. * 批量生成多个分集
  8088. *
  8089. * @param array $data 请求数据
  8090. * @return array 任务信息
  8091. */
  8092. public function batchGenerateEpisodes($data) {
  8093. $uid = Site::getUid();
  8094. $cpid = Site::getCpid();
  8095. $anime_id = getProp($data, 'anime_id');
  8096. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  8097. if (!$anime_id) {
  8098. Utils::throwError('20003:anime_id参数缺失');
  8099. }
  8100. if ($generate_episode_number < 1) {
  8101. Utils::throwError('20003:生成集数必须大于0');
  8102. }
  8103. // 获取动漫信息
  8104. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8105. if (!$anime) {
  8106. Utils::throwError('20003:该剧集不存在');
  8107. }
  8108. // 检查是否是全能模式
  8109. if ((int)getProp($anime, 'ace_mode') !== 1) {
  8110. Utils::throwError('20003:只有全能模式才支持批量生成');
  8111. }
  8112. // 检查是否是多剧集模式
  8113. if ((int)getProp($anime, 'is_multi') !== 1) {
  8114. Utils::throwError('20003:单剧集不支持批量生成');
  8115. }
  8116. // 获取当前已生成的最大集数
  8117. $currentMaxEpisode = DB::table('mp_anime_episodes')
  8118. ->where('anime_id', $anime_id)
  8119. ->where('is_default', 1)
  8120. ->max('episode_number');
  8121. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  8122. // 确定起始集数
  8123. $startEpisodeNumber = $currentMaxEpisode + 1;
  8124. // 计算结束集数
  8125. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  8126. // 检查是否超过总集数限制
  8127. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  8128. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  8129. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  8130. }
  8131. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  8132. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  8133. ->where('anime_id', $anime_id)
  8134. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  8135. ->whereIn('status', ['pending', 'processing', 'completed'])
  8136. ->count();
  8137. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  8138. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  8139. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  8140. if ($needEpisodeCount > 0) {
  8141. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS * $needEpisodeCount, $uid);
  8142. }
  8143. $now = date('Y-m-d H:i:s');
  8144. $createdTasks = [];
  8145. $skippedTasks = [];
  8146. // 为每一集创建详情记录
  8147. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  8148. // 检查是否已有该集的任务记录
  8149. $existingTask = DB::table('mp_batch_episode_generation_details')
  8150. ->where('anime_id', $anime_id)
  8151. ->where('episode_number', $episodeNumber)
  8152. ->first();
  8153. if ($existingTask) {
  8154. // 如果已存在且未完成,跳过
  8155. if (in_array($existingTask->status, ['pending', 'processing'])) {
  8156. $skippedTasks[] = $episodeNumber;
  8157. continue;
  8158. }
  8159. // 如果是失败状态,可以重新创建(删除旧记录)
  8160. if ($existingTask->status === 'failed') {
  8161. DB::table('mp_batch_episode_generation_details')
  8162. ->where('id', $existingTask->id)
  8163. ->delete();
  8164. }
  8165. // 如果是已完成状态,也跳过
  8166. if ($existingTask->status === 'completed') {
  8167. $skippedTasks[] = $episodeNumber;
  8168. continue;
  8169. }
  8170. }
  8171. // 准备任务数据
  8172. $taskData = [
  8173. 'anime_id' => $anime_id,
  8174. 'uid' => $uid,
  8175. 'cpid' => $cpid,
  8176. 'episode_number' => $episodeNumber,
  8177. 'status' => 'pending',
  8178. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  8179. 'retry_count' => 0,
  8180. 'created_at' => $now,
  8181. 'updated_at' => $now
  8182. ];
  8183. // 创建任务记录
  8184. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  8185. if ($taskId) {
  8186. $createdTasks[] = $episodeNumber;
  8187. }
  8188. }
  8189. if (empty($createdTasks)) {
  8190. if (!empty($skippedTasks)) {
  8191. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  8192. } else {
  8193. Utils::throwError('20003:创建批量生成任务失败');
  8194. }
  8195. }
  8196. return [
  8197. 'anime_id' => $anime_id,
  8198. 'start_episode' => $startEpisodeNumber,
  8199. 'end_episode' => $endEpisodeNumber,
  8200. 'total_episodes' => $generate_episode_number,
  8201. 'created_episodes' => $createdTasks,
  8202. 'skipped_episodes' => $skippedTasks,
  8203. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集。" .
  8204. "已创建: " . implode(',', $createdTasks) .
  8205. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : "")
  8206. ];
  8207. }
  8208. /**
  8209. * 获取批量生成任务状态
  8210. *
  8211. * @param array $data 请求数据
  8212. * @return array 任务状态信息
  8213. */
  8214. public function getBatchGenerationTaskStatus($data) {
  8215. $anime_id = getProp($data, 'anime_id');
  8216. if (!$anime_id) {
  8217. Utils::throwError('20003:anime_id参数缺失');
  8218. }
  8219. // 获取该anime的所有任务
  8220. $tasks = DB::table('mp_batch_episode_generation_details')
  8221. ->where('anime_id', $anime_id)
  8222. ->orderBy('episode_number')
  8223. ->get()
  8224. ->map(function($item) {
  8225. return [
  8226. 'id' => $item->id,
  8227. 'episode_number' => $item->episode_number,
  8228. 'status' => $item->status,
  8229. 'error_message' => $item->error_message,
  8230. 'retry_count' => $item->retry_count,
  8231. 'created_at' => $item->created_at,
  8232. 'updated_at' => $item->updated_at,
  8233. 'completed_at' => $item->completed_at
  8234. ];
  8235. })
  8236. ->toArray();
  8237. if (empty($tasks)) {
  8238. Utils::throwError('20003:该剧集没有批量生成任务');
  8239. }
  8240. // 统计各状态数量
  8241. $totalCount = count($tasks);
  8242. $pendingCount = 0;
  8243. $processingCount = 0;
  8244. $completedCount = 0;
  8245. $failedCount = 0;
  8246. foreach ($tasks as $task) {
  8247. switch ($task['status']) {
  8248. case 'pending':
  8249. $pendingCount++;
  8250. break;
  8251. case 'processing':
  8252. $processingCount++;
  8253. break;
  8254. case 'completed':
  8255. $completedCount++;
  8256. break;
  8257. case 'failed':
  8258. $failedCount++;
  8259. break;
  8260. }
  8261. }
  8262. // 计算进度百分比
  8263. $progress = 0;
  8264. if ($totalCount > 0) {
  8265. $progress = round(($completedCount / $totalCount) * 100, 2);
  8266. }
  8267. // 判断整体状态
  8268. $overallStatus = 'processing';
  8269. if ($completedCount === $totalCount) {
  8270. $overallStatus = 'completed';
  8271. } elseif ($pendingCount === $totalCount) {
  8272. $overallStatus = 'pending';
  8273. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  8274. $overallStatus = 'failed';
  8275. }
  8276. return [
  8277. 'anime_id' => $anime_id,
  8278. 'total_episodes' => $totalCount,
  8279. 'pending_count' => $pendingCount,
  8280. 'processing_count' => $processingCount,
  8281. 'completed_count' => $completedCount,
  8282. 'failed_count' => $failedCount,
  8283. 'progress' => $progress,
  8284. 'overall_status' => $overallStatus,
  8285. 'tasks' => $tasks
  8286. ];
  8287. }
  8288. /**
  8289. * 智能匹配并替换主体和场景名称
  8290. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  8291. *
  8292. * @param array $episode_arr 解析后的剧集数据
  8293. * @param array $extra_roles 强制主体设定(key为主体名称)
  8294. * @param array $extra_scenes 强制场景设定(key为场景名称)
  8295. * @return array 替换后的剧集数据
  8296. */
  8297. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  8298. $replaced_count = 0;
  8299. // 1. 处理主体列表
  8300. if (!empty($episode_arr['roles'])) {
  8301. foreach ($episode_arr['roles'] as &$role) {
  8302. $generated_role_name = $role['role'] ?? '';
  8303. // 跳过旁白
  8304. if ($generated_role_name === '旁白') {
  8305. continue;
  8306. }
  8307. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  8308. if (!isset($extra_roles[$generated_role_name])) {
  8309. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  8310. if ($matched_role) {
  8311. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  8312. $role['role'] = $matched_role;
  8313. $replaced_count++;
  8314. }
  8315. }
  8316. }
  8317. }
  8318. // 2. 处理场景列表
  8319. if (!empty($episode_arr['scenes'])) {
  8320. foreach ($episode_arr['scenes'] as &$scene) {
  8321. $generated_scene_name = $scene['scene'] ?? '';
  8322. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  8323. if (!isset($extra_scenes[$generated_scene_name])) {
  8324. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  8325. if ($matched_scene) {
  8326. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  8327. $scene['scene'] = $matched_scene;
  8328. $replaced_count++;
  8329. }
  8330. }
  8331. }
  8332. }
  8333. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  8334. if (!empty($episode_arr['acts'])) {
  8335. foreach ($episode_arr['acts'] as &$act) {
  8336. if (!empty($act['segments'])) {
  8337. foreach ($act['segments'] as &$segment) {
  8338. if (!empty($segment['segment_content'])) {
  8339. $original_content = $segment['segment_content'];
  8340. $replaced_content = $original_content;
  8341. // 替换场景名 - 在文本中查找并替换
  8342. foreach (array_keys($extra_scenes) as $full_scene_name) {
  8343. // 尝试找到可能的短名称
  8344. $potential_short_names = [];
  8345. // 提取场景名的主要部分(冒号之前)
  8346. if (mb_strpos($full_scene_name, ':') !== false) {
  8347. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8348. $potential_short_names[] = $short_name;
  8349. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  8350. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8351. $potential_short_names[] = $short_name;
  8352. }
  8353. // 替换场景字段中的短名称
  8354. foreach ($potential_short_names as $short_name) {
  8355. if ($short_name !== $full_scene_name) {
  8356. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  8357. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  8358. if ($new_content !== $replaced_content) {
  8359. $replaced_content = $new_content;
  8360. $replaced_count++;
  8361. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  8362. }
  8363. }
  8364. }
  8365. }
  8366. // 替换配音角色名(跳过旁白)
  8367. foreach (array_keys($extra_roles) as $full_role_name) {
  8368. if ($full_role_name === '旁白') {
  8369. continue;
  8370. }
  8371. // 尝试找到可能的短名称
  8372. $potential_short_names = [];
  8373. // 提取角色名的主要部分(短横线之前)
  8374. if (mb_strpos($full_role_name, '-') !== false) {
  8375. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  8376. $potential_short_names[] = $short_name;
  8377. }
  8378. // 替换配音台词中的短名称
  8379. foreach ($potential_short_names as $short_name) {
  8380. if ($short_name !== $full_role_name) {
  8381. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  8382. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  8383. if ($new_content !== $replaced_content) {
  8384. $replaced_content = $new_content;
  8385. $replaced_count++;
  8386. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  8387. }
  8388. }
  8389. }
  8390. }
  8391. // 如果有替换,更新segment_content
  8392. if ($replaced_content !== $original_content) {
  8393. $segment['segment_content'] = $replaced_content;
  8394. }
  8395. }
  8396. }
  8397. }
  8398. }
  8399. }
  8400. if ($replaced_count > 0) {
  8401. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  8402. 'replaced_count' => $replaced_count
  8403. ]);
  8404. }
  8405. return $episode_arr;
  8406. }
  8407. /**
  8408. * 查找匹配的名称
  8409. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  8410. *
  8411. * @param string $generated_name 生成的名称
  8412. * @param array $expected_names 预期的名称列表
  8413. * @return string|null 匹配到的名称,如果没有匹配则返回null
  8414. */
  8415. private function findMatchingName($generated_name, $expected_names) {
  8416. if (empty($generated_name)) {
  8417. return null;
  8418. }
  8419. // 尝试精确匹配
  8420. if (in_array($generated_name, $expected_names)) {
  8421. return $generated_name;
  8422. }
  8423. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  8424. foreach ($expected_names as $expected_name) {
  8425. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  8426. if (mb_strpos($expected_name, $generated_name) === 0) {
  8427. return $expected_name;
  8428. }
  8429. }
  8430. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  8431. // 这样可以处理一些变体,但优先级较低
  8432. foreach ($expected_names as $expected_name) {
  8433. if (mb_strpos($expected_name, $generated_name) !== false) {
  8434. return $expected_name;
  8435. }
  8436. }
  8437. return null;
  8438. }
  8439. /**
  8440. * 重新生成分段剧本
  8441. * @param array $data 包含以下字段:
  8442. * - prompt: string|null 用户修改要求(可选)
  8443. * - template_id: int|null 提示词模板ID(可选)
  8444. * - act_id: int|null 单个片段ID(与episode_id二选一)
  8445. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  8446. * @return array 返回生成结果
  8447. */
  8448. public function regenerateSegmentScript($data) {
  8449. $uid = Site::getUid();
  8450. $prompt = trim((string)getProp($data, 'prompt', ''));
  8451. $template_id = getProp($data, 'template_id', 0);
  8452. $act_id = getProp($data, 'act_id', 0);
  8453. $episode_id = getProp($data, 'episode_id', 0);
  8454. // 验证:prompt和template_id至少提供一个
  8455. if (empty($prompt) && empty($template_id)) {
  8456. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  8457. }
  8458. // 验证:act_id和episode_id二选一
  8459. if (empty($act_id) && empty($episode_id)) {
  8460. Utils::throwError('20003:请提供片段ID或剧集ID');
  8461. }
  8462. if (!empty($act_id) && !empty($episode_id)) {
  8463. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  8464. }
  8465. // 积分余额预检(仅剧集ID模式收费)
  8466. if (!empty($episode_id)) {
  8467. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  8468. }
  8469. // 如果提供了template_id,获取模板提示词
  8470. $template_prompt = '';
  8471. if ($template_id > 0) {
  8472. $template = DB::table('mp_prompt_templates')
  8473. ->where('id', $template_id)
  8474. ->where('is_deleted', 0)
  8475. ->first();
  8476. if (!$template) {
  8477. Utils::throwError('20003:提示词模板不存在或已删除');
  8478. }
  8479. $template_prompt = $template->template_prompt ?? '';
  8480. }
  8481. // 合并用户提示词和模板提示词
  8482. $final_prompt = '';
  8483. if (!empty($template_prompt)) {
  8484. $final_prompt = $template_prompt;
  8485. if (!empty($prompt)) {
  8486. $final_prompt .= "\n\n补充要求:" . $prompt;
  8487. }
  8488. } else {
  8489. $final_prompt = $prompt;
  8490. }
  8491. // 获取需要重新生成的内容参考
  8492. $reference_content = '';
  8493. $target_episode_id = 0;
  8494. $target_anime_id = 0;
  8495. $target_episode_number = 0;
  8496. if ($act_id > 0) {
  8497. // 单个片段模式:获取该片段的内容
  8498. $segment = DB::table('mp_episode_segments')
  8499. ->where('id', $act_id)
  8500. ->first();
  8501. if (!$segment) {
  8502. Utils::throwError('20003:片段不存在');
  8503. }
  8504. $target_episode_id = $segment->episode_id;
  8505. $target_anime_id = $segment->anime_id;
  8506. $target_episode_number = $segment->episode_number;
  8507. $reference_content = $segment->act_content ?? '';
  8508. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8509. } else {
  8510. // 整个剧集模式:获取所有片段的内容
  8511. $segments = DB::table('mp_episode_segments')
  8512. ->where('episode_id', $episode_id)
  8513. ->orderBy('act_number')
  8514. ->get();
  8515. if ($segments->isEmpty()) {
  8516. Utils::throwError('20003:该剧集没有片段数据');
  8517. }
  8518. $target_episode_id = $episode_id;
  8519. $target_anime_id = $segments[0]->anime_id;
  8520. $target_episode_number = $segments[0]->episode_number;
  8521. // 拼接所有片段内容,保留格式用于AI理解
  8522. $act_contents = [];
  8523. foreach ($segments as $seg) {
  8524. $act_number = $seg->act_number;
  8525. $act_content = $seg->act_content ?? '';
  8526. if (!empty($act_content)) {
  8527. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  8528. }
  8529. }
  8530. $reference_content = implode("\n\n", $act_contents);
  8531. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  8532. if ($episode_content) {
  8533. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  8534. }else {
  8535. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8536. }
  8537. }
  8538. if (empty($reference_content)) {
  8539. Utils::throwError('20003:没有可参考的片段内容');
  8540. }
  8541. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  8542. $episode = DB::table('mp_anime_episodes')
  8543. ->where('id', $target_episode_id)
  8544. ->first();
  8545. if (!$episode) {
  8546. Utils::throwError('20003:剧集不存在');
  8547. }
  8548. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  8549. $anime_script_id = getProp($anime, 'script_id');
  8550. $intro = $episode->intro ?? '';
  8551. $art_style = $episode->art_style ?? '';
  8552. $roles = json_decode($episode->roles ?? '[]', true);
  8553. $scenes = json_decode($episode->scenes ?? '[]', true);
  8554. $props = json_decode($episode->props ?? '[]', true);
  8555. // 构建提示词中的主体列表和场景列表参考
  8556. $roles_ref = '';
  8557. if (!empty($roles) && is_array($roles)) {
  8558. $roles_list = [];
  8559. foreach ($roles as $role) {
  8560. $role_name = getProp($role, 'role', '');
  8561. $role_desc = getProp($role, 'description', '');
  8562. $pic_prompt = getProp($role, 'pic_prompt', '');
  8563. $voice_prompt = getProp($role, 'voice_prompt', '');
  8564. if (!empty($role_name)) {
  8565. $role_line = $role_name;
  8566. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  8567. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  8568. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  8569. $roles_list[] = $role_line;
  8570. }
  8571. }
  8572. if (!empty($roles_list)) {
  8573. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  8574. }
  8575. }
  8576. $scenes_ref = '';
  8577. if (!empty($scenes) && is_array($scenes)) {
  8578. $scenes_list = [];
  8579. foreach ($scenes as $scene) {
  8580. $scene_name = getProp($scene, 'scene', '');
  8581. $scene_desc = getProp($scene, 'description', '');
  8582. $pic_prompt = getProp($scene, 'pic_prompt', '');
  8583. if (!empty($scene_name)) {
  8584. $scene_line = $scene_name;
  8585. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  8586. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  8587. $scenes_list[] = $scene_line;
  8588. }
  8589. }
  8590. if (!empty($scenes_list)) {
  8591. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  8592. }
  8593. }
  8594. $props_ref = '';
  8595. if (!empty($props) && is_array($props)) {
  8596. $props_list = [];
  8597. foreach ($props as $prop) {
  8598. $prop_name = getProp($prop, 'prop', '');
  8599. $prop_desc = getProp($prop, 'description', '');
  8600. $pic_prompt = getProp($prop, 'pic_prompt', '');
  8601. if (!empty($prop_name)) {
  8602. $prop_line = $prop_name;
  8603. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  8604. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  8605. $props_list[] = $prop_line;
  8606. }
  8607. }
  8608. if (!empty($props_list)) {
  8609. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  8610. }
  8611. }
  8612. // 构建美术风格参考
  8613. $art_style_ref = '';
  8614. if (!empty($art_style)) {
  8615. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  8616. }
  8617. // 构建内容简介参考
  8618. $intro_ref = '';
  8619. if (!empty($intro)) {
  8620. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  8621. }
  8622. // 构建完整的AI提示词
  8623. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  8624. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  8625. $user_prompt .= $intro_ref;
  8626. $user_prompt .= $art_style_ref;
  8627. $user_prompt .= $reference_content;
  8628. // $user_prompt .= $roles_ref;
  8629. // $user_prompt .= $scenes_ref;
  8630. $system_prompt = "\n\n【强制要求】\n";
  8631. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  8632. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  8633. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  8634. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  8635. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  8636. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  8637. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  8638. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  8639. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  8640. ###分段剧本
  8641. 片段数量:8
  8642. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8643. ##片段1
  8644. 时长:12s
  8645. 分镜1
  8646. 出场角色:刀疤脸
  8647. 场景:边境小镇街道
  8648. 出场道具:酒杯-高脚杯
  8649. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8650. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8651. 配音台词:
  8652. 背景音效:
  8653. 分镜2
  8654. 出场角色:刀疤脸
  8655. 场景:悦来酒馆
  8656. 出场道具:酒杯-高脚杯
  8657. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8658. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8659. 配音台词:
  8660. 背景音效:
  8661. 分镜3
  8662. 出场角色:刀疤脸
  8663. 场景:悦来酒馆
  8664. 出场道具:酒杯-高脚杯
  8665. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8666. 运镜:从中景推向令牌特写。
  8667. 配音台词:
  8668. 背景音效:
  8669. 分镜4
  8670. 出场角色:刀疤脸
  8671. 场景:悦来酒馆
  8672. 出场道具:酒杯-高脚杯
  8673. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8674. 运镜:极速推向酒水溅起的瞬间。
  8675. 配音台词:
  8676. 背景音效:
  8677. 分镜5
  8678. 出场角色:刀疤脸
  8679. 场景:悦来酒馆
  8680. 出场道具:酒杯-高脚杯
  8681. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8682. 运镜:固定机位,利用倾斜构图制造压迫感。
  8683. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8684. 背景音效:";
  8685. // 获取模型配置
  8686. $model = getProp($data, 'model');
  8687. if (!$model) {
  8688. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  8689. }
  8690. // 验证模型是否在可用模型表中
  8691. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8692. $model = 'deepseek-v4-pro';
  8693. }
  8694. // 模型兼容性处理
  8695. $thinkingMode = 'disabled';
  8696. $reasoningEffort = 'high';
  8697. if ($model === 'deepseek-chat') {
  8698. $model = 'deepseek-v4-flash';
  8699. $thinkingMode = 'disabled';
  8700. } elseif ($model === 'deepseek-reasoner') {
  8701. $model = 'deepseek-v4-flash';
  8702. $thinkingMode = 'enabled';
  8703. }
  8704. // 构建消息
  8705. $messages = [
  8706. [
  8707. 'role' => 'system',
  8708. 'content' => $system_prompt
  8709. ],
  8710. [
  8711. 'role' => 'user',
  8712. 'content' => $user_prompt
  8713. ]
  8714. ];
  8715. // dd($messages);
  8716. // 构建请求参数
  8717. $post_data = [
  8718. 'model' => $model,
  8719. 'messages' => $messages,
  8720. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8721. 'frequency_penalty' => 0,
  8722. 'presence_penalty' => 0,
  8723. 'response_format' => ['type' => 'text'],
  8724. 'thinking' => ['type' => $thinkingMode],
  8725. 'stream' => false // 非流式输出
  8726. ];
  8727. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8728. // 调用AI生成新的分段剧本
  8729. try {
  8730. $fullContent = '';
  8731. $usage = [];
  8732. // 根据模型类型选择调用方法
  8733. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8734. // DeepSeek 官方模型使用 DeepSeek API
  8735. $chatResult = $this->chatOnly($post_data);
  8736. } else if (in_array($model, $this->gpt_text_models)) {
  8737. // GPT 模型使用 TokenRouter API
  8738. $chatResult = $this->gpt54ChatOnly($post_data);
  8739. } else {
  8740. // 其他模型使用火山引擎API
  8741. $chatResult = $this->volcEngineChatCompletion($post_data);
  8742. }
  8743. if (is_array($chatResult)) {
  8744. $fullContent = $chatResult['fullContent'] ?? '';
  8745. $usage = $chatResult['usage'] ?? [];
  8746. }
  8747. $generated_content = $fullContent;
  8748. if (empty($generated_content)) {
  8749. Utils::throwError('20003:AI生成内容为空,请重试');
  8750. }
  8751. // 解析生成的内容 - 按片段分割
  8752. $parsed_segments = [];
  8753. // 先在开头添加换行符,确保第1片段也能被正确分割
  8754. $normalizedText = "\n" . $generated_content;
  8755. $parts = preg_split('/\n\s*##/', $normalizedText);
  8756. foreach ($parts as $part) {
  8757. $part = trim($part);
  8758. if (empty($part)) continue;
  8759. // 匹配"片段X"格式
  8760. if (!preg_match('/^片段\d+/', $part)) {
  8761. continue;
  8762. }
  8763. // 分离标题和内容
  8764. $lines = explode("\n", $part, 2);
  8765. $actTitle = trim($lines[0]);
  8766. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  8767. // 解析标题,提取序号
  8768. $actNumber = 0;
  8769. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  8770. $actNumber = intval($segmentTitleMatch[1]);
  8771. } else {
  8772. $actNumber = count($parsed_segments) + 1;
  8773. }
  8774. // 提取时长(仅保留数字)
  8775. $actDuration = 0;
  8776. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  8777. $actDurationStr = trim($actDurationMatch[1]);
  8778. // 提取数字部分(支持整数和小数)
  8779. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  8780. $actDuration = (float)$numMatch[1];
  8781. }
  8782. }
  8783. // 清理act_content:去除时长、旁白音色等非分镜内容行
  8784. // 只保留分镜内容,并确保分镜标记使用【】格式
  8785. $cleaned_content = '';
  8786. $content_lines = explode("\n", $actContent);
  8787. $is_capturing = false; // 标记是否开始捕获分镜内容
  8788. $count = 0;
  8789. foreach ($content_lines as $line) {
  8790. $trimmed_line = trim($line);
  8791. // 跳过时长和旁白音色行
  8792. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  8793. continue;
  8794. }
  8795. // 检测是否是分镜开始
  8796. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  8797. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  8798. $count++;
  8799. $is_capturing = true;
  8800. // 如果没有【】,则添加
  8801. if (!preg_match('/^【/u', $trimmed_line)) {
  8802. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  8803. }
  8804. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  8805. }
  8806. // 如果已经开始捕获,则添加该行
  8807. if ($is_capturing && !empty($trimmed_line)) {
  8808. $cleaned_content .= $trimmed_line."\n";
  8809. }
  8810. }
  8811. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  8812. $parsed_segments[] = [
  8813. 'act_number' => $actNumber,
  8814. 'act_title' => $actTitle,
  8815. 'act_duration' => $actDuration,
  8816. 'act_content' => $cleaned_content,
  8817. ];
  8818. }
  8819. if (empty($parsed_segments)) {
  8820. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  8821. }
  8822. // 收集所有资产名称(角色、场景、道具)
  8823. $product_names = [];
  8824. // 收集角色名称
  8825. if (!empty($roles) && is_array($roles)) {
  8826. foreach ($roles as $role) {
  8827. $role_name = getProp($role, 'role', '');
  8828. if (!empty($role_name)) {
  8829. $product_names[] = $role_name;
  8830. }
  8831. }
  8832. }
  8833. // 收集场景名称
  8834. if (!empty($scenes) && is_array($scenes)) {
  8835. foreach ($scenes as $scene) {
  8836. $scene_name = getProp($scene, 'scene', '');
  8837. if (!empty($scene_name)) {
  8838. $product_names[] = $scene_name;
  8839. }
  8840. }
  8841. }
  8842. // 收集道具名称
  8843. if (!empty($props) && is_array($props)) {
  8844. foreach ($props as $prop) {
  8845. $prop_name = getProp($prop, 'prop', '');
  8846. if (!empty($prop_name)) {
  8847. $product_names[] = $prop_name;
  8848. }
  8849. }
  8850. }
  8851. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  8852. $product_names = array_unique($product_names);
  8853. usort($product_names, function($a, $b) {
  8854. return mb_strlen($b) - mb_strlen($a);
  8855. });
  8856. // 处理每个片段的 act_show_content
  8857. foreach ($parsed_segments as &$segment) {
  8858. $act_content = getProp($segment, 'act_content', '');
  8859. if (empty($act_content)) {
  8860. $segment['act_show_content'] = '';
  8861. continue;
  8862. }
  8863. $processed_content = $act_content;
  8864. // 统一替换所有资产名称为 {资产名} 格式
  8865. // 使用占位符避免嵌套替换问题
  8866. $placeholder_map = [];
  8867. $placeholder_index = 0;
  8868. foreach ($product_names as $product_name) {
  8869. // 转义特殊字符
  8870. $escaped_product = preg_quote($product_name, '/');
  8871. // 检查是否匹配且未被 {} 包裹
  8872. $processed_content = preg_replace_callback(
  8873. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  8874. function($matches) use (&$placeholder_map, &$placeholder_index) {
  8875. // 使用唯一占位符
  8876. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  8877. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  8878. $placeholder_index++;
  8879. return $placeholder;
  8880. },
  8881. $processed_content
  8882. );
  8883. }
  8884. // 将所有占位符替换回实际内容
  8885. foreach ($placeholder_map as $placeholder => $replacement) {
  8886. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  8887. }
  8888. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  8889. $shot_counter = 0;
  8890. $processed_content = preg_replace_callback(
  8891. '/【(?:镜头|分镜)(\d+)】/u',
  8892. function($matches) use (&$shot_counter) {
  8893. $shot_counter++;
  8894. return '【镜头' . $shot_counter . '】';
  8895. },
  8896. $processed_content
  8897. );
  8898. $segment['act_show_content'] = $processed_content;
  8899. }
  8900. unset($segment); // 解除引用
  8901. // 保存到数据库
  8902. $now = date('Y-m-d H:i:s');
  8903. $saved_acts = []; // 用于记录保存后的片段信息
  8904. if ($act_id > 0) {
  8905. // 单个片段模式:更新单条记录
  8906. if (count($parsed_segments) > 0) {
  8907. $new_segment = $parsed_segments[0];
  8908. $update_data = [
  8909. 'act_content' => getProp($new_segment, 'act_content', ''),
  8910. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  8911. 'act_title' => getProp($new_segment, 'act_title', ''),
  8912. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  8913. 'updated_at' => $now,
  8914. ];
  8915. DB::table('mp_episode_segments')
  8916. ->where('id', $act_id)
  8917. ->update($update_data);
  8918. // 获取更新后的记录
  8919. $updated_act = DB::table('mp_episode_segments')
  8920. ->where('id', $act_id)
  8921. ->first();
  8922. if ($updated_act) {
  8923. $saved_acts[] = [
  8924. 'act_id' => $updated_act->id,
  8925. 'act_number' => $updated_act->act_number,
  8926. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  8927. 'act_content' => $updated_act->act_content,
  8928. 'act_show_content' => $updated_act->act_show_content,
  8929. 'video_url' => $updated_act->video_url ?? '',
  8930. 'video_duration' => $updated_act->video_duration ?? 0,
  8931. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  8932. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  8933. ];
  8934. }
  8935. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  8936. }
  8937. } else {
  8938. // 整个剧集模式:删除原有记录并批量保存新记录
  8939. DB::beginTransaction();
  8940. try {
  8941. // 删除原有的所有片段记录
  8942. DB::table('mp_episode_segments')
  8943. ->where('episode_id', $target_episode_id)
  8944. ->delete();
  8945. // 批量插入新的片段记录
  8946. $segments_to_insert = [];
  8947. foreach ($parsed_segments as $index => $segment) {
  8948. $act_number = $index + 1;
  8949. $segments_to_insert[] = [
  8950. 'anime_id' => $target_anime_id,
  8951. 'episode_id' => $target_episode_id,
  8952. 'episode_number' => $target_episode_number,
  8953. 'act_number' => $act_number,
  8954. 'act_title' => getProp($segment, 'act_title', ''),
  8955. 'act_duration' => getProp($segment, 'act_duration', 0),
  8956. 'act_content' => getProp($segment, 'act_content', ''),
  8957. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  8958. 'created_at' => $now,
  8959. 'updated_at' => $now,
  8960. ];
  8961. }
  8962. if (!empty($segments_to_insert)) {
  8963. DB::table('mp_episode_segments')->insert($segments_to_insert);
  8964. }
  8965. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8966. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8967. 'anime_id' => $target_anime_id,
  8968. 'episode_id' => $target_episode_id,
  8969. ]);
  8970. DB::commit();
  8971. // 查询保存后的所有片段记录
  8972. $saved_segments = DB::table('mp_episode_segments')
  8973. ->where('episode_id', $target_episode_id)
  8974. ->orderBy('act_number')
  8975. ->get();
  8976. foreach ($saved_segments as $saved_segment) {
  8977. $saved_acts[] = [
  8978. 'act_id' => $saved_segment->id,
  8979. 'act_number' => $saved_segment->act_number,
  8980. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  8981. 'act_content' => $saved_segment->act_content,
  8982. 'act_show_content' => $saved_segment->act_show_content,
  8983. 'video_url' => $saved_segment->video_url ?? '',
  8984. 'video_duration' => $saved_segment->video_duration ?? 0,
  8985. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  8986. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  8987. ];
  8988. }
  8989. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  8990. 'episode_id' => $target_episode_id,
  8991. 'segments_count' => count($segments_to_insert)
  8992. ]);
  8993. } catch (\Exception $e) {
  8994. DB::rollBack();
  8995. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  8996. Utils::throwError('20003:保存失败,请重试');
  8997. }
  8998. }
  8999. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  9000. return [
  9001. 'anime_id' => $target_anime_id,
  9002. 'episode_id' => $target_episode_id,
  9003. 'title' => getProp($episode, 'title', ''),
  9004. 'episode_number' => $target_episode_number,
  9005. 'is_generated' => getProp($episode, 'is_generated', 0),
  9006. 'acts' => $saved_acts,
  9007. ];
  9008. } catch (\Exception $e) {
  9009. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  9010. throw $e;
  9011. }
  9012. }
  9013. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  9014. {
  9015. $episode_arr = [
  9016. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  9017. 'intro' => getProp($script_arr, 'intro'),
  9018. 'art_style' => getProp($script_arr, 'art_style'),
  9019. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  9020. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  9021. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  9022. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  9023. ];
  9024. if (empty($episode_arr['acts'])) {
  9025. $fallback_episode_arr = handleEpisodeContent($fullContent);
  9026. if (!empty($fallback_episode_arr['acts'])) {
  9027. $episode_arr = array_merge($fallback_episode_arr, [
  9028. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  9029. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  9030. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  9031. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  9032. ]);
  9033. }
  9034. }
  9035. // if (!getProp($episode_arr, 'episode_title')) {
  9036. // $episode_title = '';
  9037. // $episodes = getProp($script_arr, 'episodes', []);
  9038. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  9039. // $episode_title = '第1集:' . $episodes[0]['title'];
  9040. // }
  9041. // if (!$episode_title) {
  9042. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  9043. // }
  9044. // $episode_arr['episode_title'] = $episode_title;
  9045. // }
  9046. return $episode_arr;
  9047. }
  9048. private function saveEpisodeVersionData(
  9049. int $anime_id,
  9050. int $episode_number,
  9051. array $episode_arr,
  9052. array $existing_roles,
  9053. array $existing_scenes,
  9054. array $existing_props,
  9055. $current_episode,
  9056. $base_episode,
  9057. bool $is_regenerate_version,
  9058. string $content,
  9059. string $now,
  9060. array $ref_products = []
  9061. ): array {
  9062. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  9063. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  9064. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  9065. // 过滤掉关键字段为空的条目
  9066. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  9067. return !empty($item['role'] ?? null);
  9068. }));
  9069. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  9070. return !empty($item['scene'] ?? null);
  9071. }));
  9072. $merged_props = array_values(array_filter($generated_props, function ($item) {
  9073. return !empty($item['prop'] ?? null);
  9074. }));
  9075. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  9076. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  9077. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  9078. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9079. $ace_mode = getProp($anime, 'ace_mode');
  9080. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  9081. $global_roles = json_decode(getProp($anime, 'roles'), true);
  9082. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  9083. $global_roles = is_array($global_roles) ? $global_roles : [];
  9084. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  9085. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  9086. $art_style_type = getProp($anime, 'art_style_type');
  9087. // 检查并创建 roles 的图片生成任务
  9088. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  9089. // 检查并创建 scenes 的图片生成任务
  9090. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  9091. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  9092. if ($arr && is_array($arr)) {
  9093. $merged_roles = $arr['roles'];
  9094. $merged_scenes = $arr['scenes'];
  9095. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  9096. }
  9097. // 确保数据是数组类型
  9098. if (!is_array($merged_roles)) {
  9099. dLog('deepseek')->error('merged_roles不是数组类型', [
  9100. 'type' => gettype($merged_roles),
  9101. 'value' => $merged_roles
  9102. ]);
  9103. $merged_roles = [];
  9104. }
  9105. if (!is_array($merged_scenes)) {
  9106. dLog('deepseek')->error('merged_scenes不是数组类型', [
  9107. 'type' => gettype($merged_scenes),
  9108. 'value' => $merged_scenes
  9109. ]);
  9110. $merged_scenes = [];
  9111. }
  9112. if (!is_array($merged_props)) {
  9113. dLog('deepseek')->error('merged_props不是数组类型', [
  9114. 'type' => gettype($merged_props),
  9115. 'value' => $merged_props
  9116. ]);
  9117. $merged_props = [];
  9118. }
  9119. // 同步新出现的主体和场景到全局
  9120. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  9121. $role_arr = [];
  9122. foreach ($merged_roles as $item) {
  9123. $role_arr[$item['role']] = $item;
  9124. }
  9125. $version_count = DB::table('mp_anime_episodes')
  9126. ->where('anime_id', $anime_id)
  9127. ->where('episode_number', $episode_number)
  9128. ->count('id');
  9129. $episode = [
  9130. 'anime_id' => $anime_id,
  9131. 'episode_number' => $episode_number,
  9132. 'title' => getProp($episode_arr, 'episode_title'),
  9133. 'content' => $content,
  9134. 'intro' => getProp($episode_arr, 'intro'),
  9135. 'art_style' => getProp($episode_arr, 'art_style'),
  9136. 'roles' => json_encode($merged_roles, 256),
  9137. 'scenes' => json_encode($merged_scenes, 256),
  9138. 'props' => json_encode($merged_props, 256),
  9139. 'generate_status' => '待执行',
  9140. 'generate_at' => $now,
  9141. 'is_default' => 1,
  9142. 'updated_at' => $now,
  9143. ];
  9144. $del_flag = false;
  9145. if ($is_regenerate_version) {
  9146. DB::table('mp_anime_episodes')
  9147. ->where('anime_id', $anime_id)
  9148. ->where('episode_number', $episode_number)
  9149. ->update(['is_default' => 0, 'updated_at' => $now]);
  9150. $episode['sequence'] = $version_count + 1;
  9151. $episode['created_at'] = $now;
  9152. $episode['cpid'] = Site::getCpid();
  9153. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9154. if (!$episode_id) {
  9155. Utils::throwError('20003:创建剧集版本失败');
  9156. }
  9157. } else {
  9158. $target_episode = $current_episode ?: $base_episode;
  9159. if ($target_episode) {
  9160. $episode_id = getProp($target_episode, 'id');
  9161. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  9162. DB::table('mp_anime_episodes')
  9163. ->where('anime_id', $anime_id)
  9164. ->where('episode_number', $episode_number)
  9165. ->where('id', '<>', $episode_id)
  9166. ->update(['is_default' => 0, 'updated_at' => $now]);
  9167. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  9168. if ($boolen === false) {
  9169. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  9170. Utils::throwError('20003:分集内容保存失败');
  9171. }
  9172. $del_flag = true;
  9173. } else {
  9174. DB::table('mp_anime_episodes')
  9175. ->where('anime_id', $anime_id)
  9176. ->where('episode_number', $episode_number)
  9177. ->update(['is_default' => 0, 'updated_at' => $now]);
  9178. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  9179. $episode['created_at'] = $now;
  9180. $episode['cpid'] = Site::getCpid();
  9181. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9182. if (!$episode_id) {
  9183. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  9184. Utils::throwError('20003:分集内容保存失败');
  9185. }
  9186. }
  9187. }
  9188. $segments = [];
  9189. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9190. // 如果是第2集及以后,获取上一集的主体音色数据
  9191. $previous_roles_voice = [];
  9192. if ($episode_number >= 2) {
  9193. $previous_episode = DB::table('mp_anime_episodes')
  9194. ->where('anime_id', $anime_id)
  9195. ->where('episode_number', $episode_number - 1)
  9196. ->where('is_default', 1)
  9197. ->first();
  9198. if ($previous_episode) {
  9199. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  9200. if (is_array($previous_roles)) {
  9201. foreach ($previous_roles as $prev_role) {
  9202. $role_name = getProp($prev_role, 'role');
  9203. if ($role_name) {
  9204. $previous_roles_voice[$role_name] = [
  9205. 'voice_name' => getProp($prev_role, 'voice_name'),
  9206. 'voice_type' => getProp($prev_role, 'voice_type'),
  9207. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  9208. ];
  9209. $voice_prompt = getProp($prev_role, 'voice_prompt');
  9210. if ($voice_prompt) {
  9211. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  9212. }
  9213. }
  9214. }
  9215. }
  9216. }
  9217. }
  9218. // 将继承的音色数据同步到当前集的主体列表
  9219. if (!empty($previous_roles_voice)) {
  9220. foreach ($merged_roles as &$role) {
  9221. $role_name = getProp($role, 'role');
  9222. if ($role_name && isset($previous_roles_voice[$role_name])) {
  9223. // 强制继承上一集的音色数据
  9224. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  9225. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  9226. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  9227. // 如果上一集有 voice_prompt 则继承,否则跳过
  9228. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  9229. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  9230. }
  9231. }
  9232. }
  9233. unset($role); // 解除引用
  9234. // 更新 role_arr 以便后续使用
  9235. $role_arr = [];
  9236. foreach ($merged_roles as $item) {
  9237. $role_arr[$item['role']] = $item;
  9238. }
  9239. }
  9240. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  9241. $emotion_list = array_flip($emotion_list);
  9242. foreach ($acts as $act) {
  9243. $act_segments = getProp($act, 'segments', []);
  9244. if (!is_array($act_segments)) {
  9245. continue;
  9246. }
  9247. if ((int)$ace_mode === 1) {
  9248. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  9249. $merged_parts = [];
  9250. foreach ($act_segments as $seg) {
  9251. $seg_num = getProp($seg, 'segment_number');
  9252. $seg_content = getProp($seg, 'segment_content');
  9253. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  9254. }
  9255. $act_content = implode("\n", $merged_parts);
  9256. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9257. $segments[] = [
  9258. 'anime_id' => $anime_id,
  9259. 'episode_id' => $episode_id,
  9260. 'episode_number' => $episode_number,
  9261. 'act_number' => getProp($act, 'act_number'),
  9262. 'act_title' => getProp($act, 'act_title'),
  9263. 'act_duration' => getProp($act, 'act_duration'),
  9264. 'act_content' => $act_content,
  9265. 'created_at' => $now,
  9266. 'updated_at' => $now
  9267. ];
  9268. } else {
  9269. foreach ($act_segments as $segment) {
  9270. $voice_actor = getProp($segment, 'voice_actor');
  9271. // 优先从上一集继承音色数据
  9272. $timbre_info = [];
  9273. if (isset($previous_roles_voice[$voice_actor])) {
  9274. // 从上一集继承音色数据
  9275. $timbre_info = $previous_roles_voice[$voice_actor];
  9276. } elseif (isset($role_arr[$voice_actor])) {
  9277. // 使用当前集的主体音色数据
  9278. $timbre_info = $role_arr[$voice_actor];
  9279. }
  9280. $voice_type = getProp($timbre_info, 'voice_type');
  9281. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  9282. if ($timbre_emotion) {
  9283. $timbre_emotion = explode(',', $timbre_emotion);
  9284. } else {
  9285. $timbre_emotion = [];
  9286. }
  9287. $emotion = getProp($segment, 'emotion', '中性');
  9288. if (!in_array($emotion, $timbre_emotion)) {
  9289. $emotion = '中性';
  9290. }
  9291. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  9292. $segments[] = [
  9293. 'anime_id' => $anime_id,
  9294. 'episode_id' => $episode_id,
  9295. 'episode_number' => $episode_number,
  9296. 'act_number' => getProp($act, 'act_number'),
  9297. 'act_title' => getProp($act, 'act_title'),
  9298. 'act_duration' => getProp($act, 'act_duration'),
  9299. 'segment_id' => getProp($segment, 'segment_id'),
  9300. 'segment_number' => getProp($segment, 'segment_number'),
  9301. 'segment_content' => getProp($segment, 'segment_content'),
  9302. 'description' => getProp($segment, 'description'),
  9303. 'composition' => getProp($segment, 'composition'),
  9304. 'camera_movement' => getProp($segment, 'camera_movement'),
  9305. 'voice_actor' => $voice_actor,
  9306. 'dialogue' => getProp($segment, 'dialogue'),
  9307. 'frame_type' => getProp($segment, 'frame_type'),
  9308. 'scene' => getProp($segment, 'scene'),
  9309. 'characters' => getProp($segment, 'characters'),
  9310. 'tail_frame' => getProp($segment, 'tail_frame'),
  9311. 'voice_name' => getProp($timbre_info, 'voice_name'),
  9312. 'voice_type' => $voice_type,
  9313. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  9314. 'emotion' => $emotion,
  9315. 'emotion_type' => $emotion_type,
  9316. 'gender' => getProp($segment, 'gender', '0'),
  9317. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  9318. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  9319. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  9320. 'pitch' => getProp($segment, 'pitch', 0),
  9321. 'created_at' => $now,
  9322. 'updated_at' => $now
  9323. ];
  9324. }
  9325. }
  9326. }
  9327. if ($segments) {
  9328. if ($del_flag) {
  9329. DB::table('mp_episode_segments')
  9330. ->where('anime_id', $anime_id)
  9331. ->where('episode_id', $episode_id)
  9332. ->delete();
  9333. }
  9334. $boolen = DB::table('mp_episode_segments')->insert($segments);
  9335. if (!$boolen) {
  9336. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  9337. Utils::throwError('20003:分镜内容保存失败');
  9338. }
  9339. }
  9340. dLog('deepseek')->info('segments', $segments);
  9341. // ace_mode=1: acts 返回值按合并格式调整
  9342. if ((int)$ace_mode === 1) {
  9343. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  9344. $act_map = [];
  9345. foreach ($table_act_data as $item) {
  9346. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  9347. }
  9348. $restructured_acts = [];
  9349. foreach ($acts as $act) {
  9350. $act_segments = getProp($act, 'segments', []);
  9351. if (!is_array($act_segments)) {
  9352. continue;
  9353. }
  9354. $merged_parts = [];
  9355. foreach ($act_segments as $seg) {
  9356. $seg_num = getProp($seg, 'segment_number');
  9357. $seg_content = getProp($seg, 'segment_content');
  9358. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  9359. }
  9360. $act_content = implode("\n", $merged_parts);
  9361. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9362. $restructured_acts[] = [
  9363. 'anime_id' => $anime_id,
  9364. 'episode_id' => $episode_id,
  9365. 'episode_number' => $episode_number,
  9366. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  9367. 'act_number' => getProp($act, 'act_number'),
  9368. 'act_title' => getProp($act, 'act_title'),
  9369. 'act_duration' => getProp($act, 'act_duration'),
  9370. 'act_content' => $act_content,
  9371. 'created_at' => $now,
  9372. 'updated_at' => $now,
  9373. ];
  9374. }
  9375. $acts = $restructured_acts;
  9376. }
  9377. $episode['episode_id'] = $episode_id;
  9378. $episode['roles'] = $merged_roles;
  9379. $episode['scenes'] = $merged_scenes;
  9380. $episode['props'] = $merged_props;
  9381. $episode['acts'] = $acts;
  9382. return [
  9383. 'episode' => $episode,
  9384. 'episode_id' => $episode_id,
  9385. 'merged_roles' => $merged_roles,
  9386. 'merged_scenes' => $merged_scenes,
  9387. 'merged_props' => $merged_props,
  9388. ];
  9389. }
  9390. private function buildEpisodeItemContent(array $items, string $nameKey): string
  9391. {
  9392. $content = '';
  9393. foreach ($items as $item) {
  9394. $name = trim((string)getProp($item, $nameKey));
  9395. if ($name === '' || $name === '旁白') {
  9396. continue;
  9397. }
  9398. $description = trim((string)getProp($item, 'description'));
  9399. $content .= $name . ': ' . $description;
  9400. if ($nameKey == 'role') {
  9401. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9402. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9403. $voice_name = trim(getProp($item, 'voice_name'));
  9404. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9405. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  9406. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9407. }else {
  9408. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9409. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9410. }
  9411. $content .= "\n";
  9412. }
  9413. return trim($content);
  9414. }
  9415. private function getEpisodeChatContent($animeId, $sequence, $content) {
  9416. if ((int)$sequence <= 0) {
  9417. return [];
  9418. }
  9419. $origin_content = '';
  9420. if ($content) {
  9421. $origin_content = '本集剧情内容:'.$content;
  9422. }else {
  9423. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  9424. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  9425. }
  9426. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  9427. // 获取分集信息
  9428. $episode = DB::table('mp_anime_episodes')
  9429. ->where('anime_id', $animeId)
  9430. ->where('episode_number', $sequence)
  9431. ->where('is_default', 1)
  9432. ->first();
  9433. if (!$episode) {
  9434. return [];
  9435. }
  9436. $episode_id = getProp($episode, 'id');
  9437. $episode_number = getProp($episode, 'episode_number');
  9438. $title = getProp($episode, 'title');
  9439. $intro = getProp($episode, 'intro');
  9440. $art_style = getProp($episode, 'art_style');
  9441. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9442. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9443. // 组装纯文本内容
  9444. $content = '';
  9445. // 添加分集标题和梗概
  9446. $content .= "###第{$episode_number}集:{$title}\n\n";
  9447. $content .= "###故事梗概\n";
  9448. $content .= trim($intro) . "\n\n";
  9449. // 添加美术风格
  9450. $content .= "###美术风格\n";
  9451. $content .= trim($art_style) . "\n\n";
  9452. // 添加主体列表
  9453. $content .= "###主体列表\n";
  9454. $pangbai_voice_prompt = "";
  9455. foreach ($roles as $role) {
  9456. $name = getProp($role, 'role');
  9457. $description = getProp($role, 'description');
  9458. $pic_prompt = getProp($role, 'pic_prompt');
  9459. $voice_prompt = getProp($role, 'voice_prompt');
  9460. $voice_name = getProp($role, 'voice_name');
  9461. $content .= "{$name}: {$description}";
  9462. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9463. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9464. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9465. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  9466. $content .= "\n";
  9467. }
  9468. $content .= "\n";
  9469. // 添加场景列表
  9470. $content .= "###场景列表\n";
  9471. foreach ($scenes as $scene) {
  9472. $name = getProp($scene, 'scene');
  9473. $description = getProp($scene, 'description');
  9474. $pic_prompt = getProp($scene, 'pic_prompt');
  9475. $content .= "{$name}: {$description}";
  9476. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9477. $content .= "\n";
  9478. }
  9479. $content .= "\n";
  9480. // 获取分镜信息
  9481. $segments = DB::table('mp_episode_segments')
  9482. ->where('anime_id', $animeId)
  9483. ->where('episode_id', $episode_id)
  9484. ->orderBy('segment_number')
  9485. ->get();
  9486. if ($segments && count($segments) > 0) {
  9487. if ((int)$ace_mode === 1) {
  9488. $content .= "###分段剧本\n";
  9489. // 获取片段数量
  9490. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  9491. $content .= "片段数量:{$act_count}\n";
  9492. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  9493. $content .= "\n";
  9494. }else {
  9495. $content .= "###分镜剧本\n";
  9496. }
  9497. // 按幕分组
  9498. $currentAct = null;
  9499. foreach ($segments as $segment) {
  9500. $act_number = getProp($segment, 'act_number');
  9501. $act_title = getProp($segment, 'act_title');
  9502. $act_duration = getProp($segment, 'act_duration');
  9503. $segment_number = getProp($segment, 'segment_number');
  9504. $segment_content = getProp($segment, 'segment_content');
  9505. $scene_description = getProp($segment, 'scene_description');
  9506. $scene_name = getProp($segment, 'scene_name');
  9507. $composition = getProp($segment, 'composition');
  9508. $camera_movement = getProp($segment, 'camera_movement');
  9509. $voice_type = getProp($segment, 'voice_type');
  9510. $characters = getProp($segment, 'characters');
  9511. $dialogue = getProp($segment, 'dialogue');
  9512. $frame_type = getProp($segment, 'frame_type');
  9513. $tail_frame_description = getProp($segment, 'tail_frame_description');
  9514. // 判断是否是全能模式
  9515. if ((int)$ace_mode === 1) { // 全能模式
  9516. // 如果是新的分段,添加分段标题
  9517. if ($act_number !== $currentAct) {
  9518. $currentAct = $act_number;
  9519. $content .= "##{$act_title}\n";
  9520. $content .= "时长:{$act_duration}s\n";
  9521. }
  9522. }else {
  9523. // 如果是新的幕,添加幕标题
  9524. if ($act_number !== $currentAct) {
  9525. $currentAct = $act_number;
  9526. $content .= "##第{$act_number}幕:{$scene_name}\n";
  9527. }
  9528. }
  9529. // 添加分镜信息
  9530. $content .= "分镜{$segment_number}\n";
  9531. $content .= "分镜内容:\n{$segment_content}\n";
  9532. // $content .= "画面描述:{$scene_description}\n";
  9533. // $content .= "场景:{$scene_name}\n";
  9534. // $content .= "构图设计:{$composition}\n";
  9535. // $content .= "运镜调度:{$camera_movement}\n";
  9536. // if (!empty($voice_type)) {
  9537. // $content .= "配音角色:{$voice_type}\n";
  9538. // }
  9539. // if (!empty($characters)) {
  9540. // $content .= "出镜角色:{$characters}\n";
  9541. // }
  9542. // if (!empty($dialogue)) {
  9543. // $content .= "台词内容:\"{$dialogue}\"\n";
  9544. // }
  9545. // $content .= "画面类型:{$frame_type}\n";
  9546. // $content .= "尾帧描述:{$tail_frame_description}\n";
  9547. $content .= "\n";
  9548. }
  9549. }
  9550. $content = trim($content);
  9551. if($content) $content = "上集剧本内容:\n{$content}";
  9552. return [
  9553. [
  9554. 'role' => 'user',
  9555. 'content' => $origin_content
  9556. ],
  9557. [
  9558. 'role' => 'assistant',
  9559. 'content' => $content
  9560. ]
  9561. ];
  9562. }
  9563. private function getEpisodeChatMessages($animeId, $sequence): array
  9564. {
  9565. if ((int)$sequence <= 0) {
  9566. return [];
  9567. }
  9568. return DB::table('mp_anime_records')
  9569. ->where('anime_id', $animeId)
  9570. ->where('sequence', $sequence)
  9571. ->where('episode_id', '>', 0)
  9572. ->select('role', 'content')
  9573. ->orderBy('created_at')
  9574. ->orderBy('id')
  9575. ->get()
  9576. ->map(function ($value) {
  9577. return (array)$value;
  9578. })
  9579. ->toArray();
  9580. }
  9581. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  9582. {
  9583. $existingMap = [];
  9584. foreach ($existingItems as $item) {
  9585. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9586. if ($itemKey === '') {
  9587. continue;
  9588. }
  9589. $existingMap[$itemKey] = $item;
  9590. }
  9591. if (!$generatedItems) {
  9592. return array_values($existingItems);
  9593. }
  9594. $merged = [];
  9595. foreach ($generatedItems as $item) {
  9596. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9597. if ($itemKey === '') {
  9598. continue;
  9599. }
  9600. if (isset($existingMap[$itemKey])) {
  9601. if (trim((string)getProp($item, 'description')) === '') {
  9602. $merged[] = $existingMap[$itemKey];
  9603. continue;
  9604. }
  9605. // 检查内容是否发生变化
  9606. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  9607. if (!$isChanged) {
  9608. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  9609. $mergedItem = [
  9610. $nameKey => trim((string)getProp($item, $nameKey)),
  9611. 'description' => trim((string)getProp($item, 'description')),
  9612. ];
  9613. // 如果有 pic_prompt,添加到合并项中
  9614. $picPrompt = getProp($item, 'pic_prompt');
  9615. if (!empty($picPrompt)) {
  9616. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9617. }
  9618. // 继承现有项的 URL
  9619. $existingUrl = getProp($existingMap[$itemKey], 'url');
  9620. if (!empty($existingUrl)) {
  9621. $mergedItem['url'] = $existingUrl;
  9622. }
  9623. // 继承现有项的 task_id
  9624. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  9625. if (!empty($existingTaskId)) {
  9626. $mergedItem['task_id'] = $existingTaskId;
  9627. }
  9628. // 继承现有项的 task_status
  9629. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  9630. if (!empty($existingTaskStatus)) {
  9631. $mergedItem['task_status'] = $existingTaskStatus;
  9632. }
  9633. // 保留生成项的音色字段
  9634. $voiceName = getProp($item, 'voice_name');
  9635. if (!empty($voiceName)) {
  9636. $mergedItem['voice_name'] = $voiceName;
  9637. }
  9638. $voiceType = getProp($item, 'voice_type');
  9639. if (!empty($voiceType)) {
  9640. $mergedItem['voice_type'] = $voiceType;
  9641. }
  9642. $audioUrl = getProp($item, 'voice_audio_url');
  9643. if (!empty($audioUrl)) {
  9644. $mergedItem['voice_audio_url'] = $audioUrl;
  9645. }
  9646. $merged[] = $mergedItem;
  9647. } else {
  9648. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  9649. $mergedItem = [
  9650. $nameKey => trim((string)getProp($item, $nameKey)),
  9651. 'description' => trim((string)getProp($item, 'description')),
  9652. ];
  9653. // 如果有 pic_prompt,添加到合并项中
  9654. $picPrompt = getProp($item, 'pic_prompt');
  9655. if (!empty($picPrompt)) {
  9656. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9657. }
  9658. // 保留生成项的音色字段
  9659. $voiceName = getProp($item, 'voice_name');
  9660. if (!empty($voiceName)) {
  9661. $mergedItem['voice_name'] = $voiceName;
  9662. }
  9663. $voiceType = getProp($item, 'voice_type');
  9664. if (!empty($voiceType)) {
  9665. $mergedItem['voice_type'] = $voiceType;
  9666. }
  9667. $audioUrl = getProp($item, 'voice_audio_url');
  9668. if (!empty($audioUrl)) {
  9669. $mergedItem['voice_audio_url'] = $audioUrl;
  9670. }
  9671. // 不继承 URL、task_id 和 task_status(重置状态)
  9672. $merged[] = $mergedItem;
  9673. }
  9674. } else {
  9675. // 新增项,保留生成项的所有字段
  9676. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  9677. }
  9678. }
  9679. return $merged ?: array_values($existingItems);
  9680. }
  9681. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  9682. {
  9683. $resetItem = [
  9684. $nameKey => trim((string)getProp($item, $nameKey)),
  9685. 'description' => trim((string)getProp($item, 'description')),
  9686. ];
  9687. // 保留指定的字段
  9688. foreach ($preserveFields as $field) {
  9689. $value = getProp($item, $field);
  9690. if (!empty($value)) {
  9691. $resetItem[$field] = $value;
  9692. }
  9693. }
  9694. return $resetItem;
  9695. }
  9696. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  9697. {
  9698. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  9699. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  9700. if ($existingKey !== $generatedKey) {
  9701. return true;
  9702. }
  9703. // 比较 description 是否变化
  9704. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  9705. return true;
  9706. }
  9707. // 比较 pic_prompt 是否变化
  9708. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  9709. }
  9710. private function normalizeEpisodeResourceKey($value): string
  9711. {
  9712. $value = trim((string)$value);
  9713. if ($value === '') {
  9714. return '';
  9715. }
  9716. return strtolower((string)preg_replace('/\s+/u', '', $value));
  9717. }
  9718. // 生成全局角色图片
  9719. private function batchSetGlobalRoleImg($data, $is_force=false) {
  9720. $anime_id = getProp($data, 'anime_id');
  9721. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9722. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9723. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9724. $art_style = getProp($anime, 'art_style');
  9725. $update_flag = false;
  9726. foreach ($roles as &$role) {
  9727. $role_name = getProp($role, 'role');
  9728. if ($role_name == '旁白') continue;
  9729. // 优先使用 pic_prompt,如果没有则使用 description
  9730. $pic_prompt = getProp($role, 'pic_prompt');
  9731. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  9732. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9733. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9734. // 参考图地址
  9735. $ref_img_url = getProp($role, 'url');
  9736. if (!$is_force && $ref_img_url) continue;
  9737. $update_flag = true;
  9738. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9739. try {
  9740. $params = [
  9741. 'prompt' => $description,
  9742. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  9743. 'ref_img_urls' => []
  9744. ];
  9745. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9746. $task_id = $task->id;
  9747. if (!$task_id) {
  9748. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  9749. }
  9750. $role['task_id'] = $task_id;
  9751. $role['task_status'] = 'processing';
  9752. } catch (\Exception $e) {
  9753. Utils::throwError("20003:" . $e->getMessage());
  9754. }
  9755. }
  9756. if (!$update_flag) return true;
  9757. // 保存角色信息
  9758. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9759. 'roles' => json_encode($roles, 256),
  9760. 'generate_status' => '执行中',
  9761. 'generate_at' => date('Y-m-d H:i:s'),
  9762. 'updated_at' => date('Y-m-d H:i:s')
  9763. ]);
  9764. if (!$boolen) {
  9765. Utils::throwError('20003:保存角色信息失败');
  9766. }
  9767. return $boolen;
  9768. }
  9769. // 生成全局场景图片
  9770. private function batchSetGlobalSceneImg($data, $is_force=false) {
  9771. $anime_id = getProp($data, 'anime_id');
  9772. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9773. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9774. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  9775. $art_style = getProp($anime, 'art_style');
  9776. $update_flag = false;
  9777. foreach ($scenes as &$scene) {
  9778. $scene_name = getProp($scene, 'scene');
  9779. // 优先使用 pic_prompt,如果没有则使用 description
  9780. $pic_prompt = getProp($scene, 'pic_prompt');
  9781. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  9782. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  9783. // 参考图地址
  9784. $ref_img_url = getProp($scene, 'url');
  9785. if (!$is_force && $ref_img_url) continue;
  9786. $update_flag = true;
  9787. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9788. try {
  9789. $params = [
  9790. 'prompt' => $description,
  9791. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  9792. 'ref_img_urls' => []
  9793. ];
  9794. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9795. $task_id = $task->id;
  9796. if (!$task_id) {
  9797. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  9798. }
  9799. $scene['task_id'] = $task_id;
  9800. $scene['task_status'] = 'processing';
  9801. } catch (\Exception $e) {
  9802. Utils::throwError("20003:" . $e->getMessage());
  9803. }
  9804. }
  9805. if (!$update_flag) return true;
  9806. // 保存角色信息
  9807. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9808. 'scenes' => json_encode($scenes, 256),
  9809. 'generate_status' => '执行中',
  9810. 'generate_at' => date('Y-m-d H:i:s'),
  9811. 'updated_at' => date('Y-m-d H:i:s')
  9812. ]);
  9813. if (!$boolen) {
  9814. Utils::throwError('20003:保存角色信息失败');
  9815. }
  9816. return $boolen;
  9817. }
  9818. // 生成分镜主体、场景和道具图片
  9819. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  9820. $character_prefix = '';
  9821. $scene_prefix = '';
  9822. $prop_prefix = '';
  9823. if ($art_style_type) {
  9824. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  9825. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  9826. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  9827. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  9828. }
  9829. $update_flag = false;
  9830. // 获取上一集的roles、scenes和props数据
  9831. $prev_roles = [];
  9832. $prev_scenes = [];
  9833. $prev_props = [];
  9834. if ($episode_number > 1) {
  9835. $prev_episode = DB::table('mp_anime_episodes')
  9836. ->where('anime_id', $anime_id)
  9837. ->where('episode_number', $episode_number - 1)
  9838. ->where('is_default', 1)
  9839. ->first();
  9840. if ($prev_episode) {
  9841. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  9842. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  9843. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  9844. dLog('deepseek')->info("获取上一集数据成功", [
  9845. 'anime_id' => $anime_id,
  9846. 'prev_episode_number' => $episode_number - 1,
  9847. 'prev_roles_count' => count($prev_roles),
  9848. 'prev_scenes_count' => count($prev_scenes),
  9849. 'prev_props_count' => count($prev_props)
  9850. ]);
  9851. }
  9852. }
  9853. // 处理角色图片生成
  9854. foreach ($roles as &$role) {
  9855. $role_name = getProp($role, 'role');
  9856. if ($role_name == '旁白') continue;
  9857. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  9858. if (isset($ref_products[$role_name])) {
  9859. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  9860. if ($role['url']) continue;
  9861. }
  9862. $role_description = getProp($role, 'description');
  9863. $role_pic_prompt = getProp($role, 'pic_prompt');
  9864. $role_url = getProp($role, 'url');
  9865. // 检查是否可以从上一集继承
  9866. $inherited = false;
  9867. if (!$is_force && !empty($prev_roles)) {
  9868. foreach ($prev_roles as $prev_role) {
  9869. $prev_role_name = getProp($prev_role, 'role');
  9870. $prev_description = getProp($prev_role, 'description');
  9871. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  9872. $prev_url = getProp($prev_role, 'url');
  9873. $prev_task_id = getProp($prev_role, 'task_id');
  9874. $prev_task_status = getProp($prev_role, 'task_status');
  9875. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  9876. if ($role_name == $prev_role_name
  9877. && $role_description == $prev_description
  9878. && $role_pic_prompt == $prev_pic_prompt
  9879. && !empty($prev_url)) {
  9880. $role['task_id'] = $prev_task_id;
  9881. $role['task_status'] = $prev_task_status;
  9882. $role['url'] = $prev_url;
  9883. $inherited = true;
  9884. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  9885. 'anime_id' => $anime_id,
  9886. 'episode_number' => $episode_number,
  9887. 'task_id' => $prev_task_id,
  9888. 'url' => $prev_url
  9889. ]);
  9890. break;
  9891. }
  9892. }
  9893. }
  9894. // 如果已继承或已有url,跳过生成
  9895. if ($inherited || (!$is_force && $role_url)) {
  9896. continue;
  9897. }
  9898. // 优先使用 pic_prompt,如果没有则使用 description
  9899. $pic_prompt = getProp($role, 'pic_prompt');
  9900. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  9901. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  9902. $update_flag = true;
  9903. // 调用AIImageGenerationService的生成图片任务接口
  9904. try {
  9905. $params = [
  9906. 'prompt' => $description,
  9907. 'ref_img_urls' => []
  9908. ];
  9909. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9910. $task_id = $task->id;
  9911. if (!$task_id) {
  9912. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  9913. continue; // 不中断,继续处理其他角色
  9914. }
  9915. $role['task_id'] = $task_id;
  9916. $role['task_status'] = 'processing';
  9917. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  9918. 'anime_id' => $anime_id,
  9919. 'episode_number' => $episode_number,
  9920. 'task_id' => $task_id
  9921. ]);
  9922. } catch (\Exception $e) {
  9923. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  9924. // 不抛出异常,继续处理其他角色
  9925. }
  9926. }
  9927. // 处理场景图片生成
  9928. foreach ($scenes as &$scene) {
  9929. $scene_name = getProp($scene, 'scene');
  9930. $scene_description = getProp($scene, 'description');
  9931. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  9932. $scene_url = getProp($scene, 'url');
  9933. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  9934. if (isset($ref_products[$scene_name])) {
  9935. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  9936. if ($scene['url']) continue;
  9937. }
  9938. // 检查是否可以从上一集继承
  9939. $inherited = false;
  9940. if (!$is_force && !empty($prev_scenes)) {
  9941. foreach ($prev_scenes as $prev_scene) {
  9942. $prev_scene_name = getProp($prev_scene, 'scene');
  9943. $prev_description = getProp($prev_scene, 'description');
  9944. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  9945. $prev_url = getProp($prev_scene, 'url');
  9946. $prev_task_id = getProp($prev_scene, 'task_id');
  9947. $prev_task_status = getProp($prev_scene, 'task_status');
  9948. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  9949. if ($scene_name == $prev_scene_name
  9950. && $scene_description == $prev_description
  9951. && $scene_pic_prompt == $prev_pic_prompt
  9952. && !empty($prev_url)) {
  9953. $scene['task_id'] = $prev_task_id;
  9954. $scene['task_status'] = $prev_task_status;
  9955. $scene['url'] = $prev_url;
  9956. $inherited = true;
  9957. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  9958. 'anime_id' => $anime_id,
  9959. 'episode_number' => $episode_number,
  9960. 'task_id' => $prev_task_id,
  9961. 'url' => $prev_url
  9962. ]);
  9963. break;
  9964. }
  9965. }
  9966. }
  9967. // 如果已继承或已有url,跳过生成
  9968. if ($inherited || (!$is_force && $scene_url)) {
  9969. continue;
  9970. }
  9971. // 优先使用 pic_prompt,如果没有则使用 description
  9972. $pic_prompt = getProp($scene, 'pic_prompt');
  9973. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  9974. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  9975. $update_flag = true;
  9976. // 调用AIImageGenerationService的生成图片任务接口
  9977. try {
  9978. $params = [
  9979. 'prompt' => $description,
  9980. 'ref_img_urls' => []
  9981. ];
  9982. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9983. $task_id = $task->id;
  9984. if (!$task_id) {
  9985. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  9986. continue; // 不中断,继续处理其他场景
  9987. }
  9988. $scene['task_id'] = $task_id;
  9989. $scene['task_status'] = 'processing';
  9990. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  9991. 'anime_id' => $anime_id,
  9992. 'episode_number' => $episode_number,
  9993. 'task_id' => $task_id
  9994. ]);
  9995. } catch (\Exception $e) {
  9996. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  9997. // 不抛出异常,继续处理其他场景
  9998. }
  9999. }
  10000. // 处理道具图片生成(逻辑与场景一致)
  10001. foreach ($props as &$prop) {
  10002. $prop_name = getProp($prop, 'prop');
  10003. $prop_description = getProp($prop, 'description');
  10004. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  10005. $prop_url = getProp($prop, 'url');
  10006. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  10007. if (isset($ref_products[$prop_name])) {
  10008. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  10009. if ($prop['url']) continue;
  10010. }
  10011. // 检查是否可以从上一集继承
  10012. $inherited = false;
  10013. if (!$is_force && !empty($prev_props)) {
  10014. foreach ($prev_props as $prev_prop) {
  10015. $prev_prop_name = getProp($prev_prop, 'prop');
  10016. $prev_description = getProp($prev_prop, 'description');
  10017. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  10018. $prev_url = getProp($prev_prop, 'url');
  10019. $prev_task_id = getProp($prev_prop, 'task_id');
  10020. $prev_task_status = getProp($prev_prop, 'task_status');
  10021. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  10022. if ($prop_name == $prev_prop_name
  10023. && $prop_description == $prev_description
  10024. && $prop_pic_prompt == $prev_pic_prompt
  10025. && !empty($prev_url)) {
  10026. $prop['task_id'] = $prev_task_id;
  10027. $prop['task_status'] = $prev_task_status;
  10028. $prop['url'] = $prev_url;
  10029. $inherited = true;
  10030. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  10031. 'anime_id' => $anime_id,
  10032. 'episode_number' => $episode_number,
  10033. 'task_id' => $prev_task_id,
  10034. 'url' => $prev_url
  10035. ]);
  10036. break;
  10037. }
  10038. }
  10039. }
  10040. // 如果已继承或已有url,跳过生成
  10041. if ($inherited || (!$is_force && $prop_url)) {
  10042. continue;
  10043. }
  10044. // 优先使用 pic_prompt,如果没有则使用 description
  10045. $pic_prompt = getProp($prop, 'pic_prompt');
  10046. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  10047. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10048. $update_flag = true;
  10049. // 调用AIImageGenerationService的生成图片任务接口
  10050. try {
  10051. $params = [
  10052. 'prompt' => $description,
  10053. 'ref_img_urls' => []
  10054. ];
  10055. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10056. $task_id = $task->id;
  10057. if (!$task_id) {
  10058. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  10059. continue; // 不中断,继续处理其他道具
  10060. }
  10061. $prop['task_id'] = $task_id;
  10062. $prop['task_status'] = 'processing';
  10063. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  10064. 'anime_id' => $anime_id,
  10065. 'episode_number' => $episode_number,
  10066. 'task_id' => $task_id
  10067. ]);
  10068. } catch (\Exception $e) {
  10069. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  10070. // 不抛出异常,继续处理其他道具
  10071. }
  10072. }
  10073. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10074. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  10075. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  10076. // // 保存剧集的角色和场景信息
  10077. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10078. // 'roles' => json_encode($roles, 256),
  10079. // 'scenes' => json_encode($scenes, 256),
  10080. // 'generate_status' => '执行中',
  10081. // 'generate_at' => date('Y-m-d H:i:s'),
  10082. // 'updated_at' => date('Y-m-d H:i:s')
  10083. // ]);
  10084. // if (!$boolen) {
  10085. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  10086. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  10087. // }
  10088. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  10089. // 'episode_id' => $episode_id,
  10090. 'roles_count' => count($roles),
  10091. 'scenes_count' => count($scenes),
  10092. 'props_count' => count($props)
  10093. ]);
  10094. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10095. }
  10096. /**
  10097. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  10098. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  10099. *
  10100. * @param int $anime_id 动漫对话ID
  10101. * @param array $episode_roles 剧集角色数据
  10102. * @param array $episode_scenes 剧集场景数据
  10103. * @param array $episode_props 剧集道具数据
  10104. * @return bool
  10105. */
  10106. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  10107. // 获取全局数据
  10108. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10109. if (!$anime) {
  10110. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10111. return false;
  10112. }
  10113. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10114. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10115. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  10116. $roles_added = false;
  10117. $roles_updated = false;
  10118. $scenes_added = false;
  10119. $props_added = false;
  10120. // 处理角色同步
  10121. foreach ($episode_roles as $episode_role) {
  10122. $episode_role_name = getProp($episode_role, 'role');
  10123. $episode_description = getProp($episode_role, 'description');
  10124. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10125. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  10126. // 跳过旁白
  10127. if ($episode_role_name == '旁白') {
  10128. continue;
  10129. }
  10130. // 检查全局中是否已存在相同的角色
  10131. $exists = false;
  10132. $global_role_index = -1;
  10133. foreach ($global_roles as $index => $global_role) {
  10134. $global_role_name = getProp($global_role, 'role');
  10135. $global_description = getProp($global_role, 'description');
  10136. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10137. // 如果role、description、pic_prompt三项都一致,则认为已存在
  10138. if ($episode_role_name == $global_role_name
  10139. && $episode_description == $global_description
  10140. && $episode_pic_prompt == $global_pic_prompt) {
  10141. $exists = true;
  10142. $global_role_index = $index;
  10143. break;
  10144. }
  10145. }
  10146. // 如果不存在,则添加到全局
  10147. if (!$exists) {
  10148. $global_roles[] = $episode_role;
  10149. $roles_added = true;
  10150. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  10151. 'anime_id' => $anime_id,
  10152. 'role' => $episode_role_name
  10153. ]);
  10154. } else {
  10155. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  10156. if (!empty($episode_voice_prompt)) {
  10157. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  10158. // 如果全局没有voice_prompt或与剧集不一致,则更新
  10159. if ($global_voice_prompt !== $episode_voice_prompt) {
  10160. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  10161. $roles_updated = true;
  10162. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  10163. 'anime_id' => $anime_id,
  10164. 'role' => $episode_role_name,
  10165. 'voice_prompt' => $episode_voice_prompt
  10166. ]);
  10167. }
  10168. }
  10169. }
  10170. }
  10171. // 处理场景同步
  10172. foreach ($episode_scenes as $episode_scene) {
  10173. $episode_scene_name = getProp($episode_scene, 'scene');
  10174. $episode_description = getProp($episode_scene, 'description');
  10175. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10176. // 检查全局中是否已存在相同的场景
  10177. $exists = false;
  10178. foreach ($global_scenes as $global_scene) {
  10179. $global_scene_name = getProp($global_scene, 'scene');
  10180. $global_description = getProp($global_scene, 'description');
  10181. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10182. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  10183. if ($episode_scene_name == $global_scene_name
  10184. && $episode_description == $global_description
  10185. && $episode_pic_prompt == $global_pic_prompt) {
  10186. $exists = true;
  10187. break;
  10188. }
  10189. }
  10190. // 如果不存在,则添加到全局
  10191. if (!$exists) {
  10192. $global_scenes[] = $episode_scene;
  10193. $scenes_added = true;
  10194. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  10195. 'anime_id' => $anime_id,
  10196. 'scene' => $episode_scene_name
  10197. ]);
  10198. }
  10199. }
  10200. // 处理道具同步(逻辑与场景一致)
  10201. foreach ($episode_props as $episode_prop) {
  10202. $episode_prop_name = getProp($episode_prop, 'prop');
  10203. $episode_description = getProp($episode_prop, 'description');
  10204. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  10205. // 检查全局中是否已存在相同的道具
  10206. $exists = false;
  10207. foreach ($global_props as $global_prop) {
  10208. $global_prop_name = getProp($global_prop, 'prop');
  10209. $global_description = getProp($global_prop, 'description');
  10210. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  10211. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  10212. if ($episode_prop_name == $global_prop_name
  10213. && $episode_description == $global_description
  10214. && $episode_pic_prompt == $global_pic_prompt) {
  10215. $exists = true;
  10216. break;
  10217. }
  10218. }
  10219. // 如果不存在,则添加到全局
  10220. if (!$exists) {
  10221. $global_props[] = $episode_prop;
  10222. $props_added = true;
  10223. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  10224. 'anime_id' => $anime_id,
  10225. 'prop' => $episode_prop_name
  10226. ]);
  10227. }
  10228. }
  10229. // 如果有新增或更新,则更新全局数据
  10230. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  10231. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10232. if ($roles_added || $roles_updated) {
  10233. $update_data['roles'] = json_encode($global_roles, 256);
  10234. }
  10235. if ($scenes_added) {
  10236. $update_data['scenes'] = json_encode($global_scenes, 256);
  10237. }
  10238. if ($props_added) {
  10239. $update_data['props'] = json_encode($global_props, 256);
  10240. }
  10241. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  10242. dLog('deepseek')->info('剧集数据同步到全局完成', [
  10243. 'anime_id' => $anime_id,
  10244. 'roles_added' => $roles_added,
  10245. 'roles_updated' => $roles_updated,
  10246. 'scenes_added' => $scenes_added,
  10247. 'props_added' => $props_added,
  10248. 'global_roles_count' => count($global_roles),
  10249. 'global_scenes_count' => count($global_scenes),
  10250. 'global_props_count' => count($global_props)
  10251. ]);
  10252. }
  10253. return true;
  10254. }
  10255. /**
  10256. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  10257. *
  10258. * @param int $anime_id 动漫对话ID
  10259. * @param int $episode_id 分集ID
  10260. * @return bool
  10261. */
  10262. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  10263. // 获取全局角色和场景数据
  10264. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10265. if (!$anime) {
  10266. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10267. return false;
  10268. }
  10269. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10270. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10271. // 获取指定的分集
  10272. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  10273. if (!$episode) {
  10274. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  10275. return false;
  10276. }
  10277. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10278. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10279. $roles_updated = false;
  10280. $scenes_updated = false;
  10281. // 继承角色的task_id、task_status和url
  10282. foreach ($episode_roles as &$episode_role) {
  10283. $episode_role_name = getProp($episode_role, 'role');
  10284. $episode_description = getProp($episode_role, 'description');
  10285. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10286. $episode_url = getProp($episode_role, 'url');
  10287. // 跳过旁白角色
  10288. if ($episode_role_name == '旁白') {
  10289. continue;
  10290. }
  10291. // 如果剧集中已有URL,跳过
  10292. if (!empty($episode_url)) {
  10293. continue;
  10294. }
  10295. // 遍历全局角色数据,查找匹配的角色
  10296. foreach ($global_roles as $global_role) {
  10297. $global_role_name = getProp($global_role, 'role');
  10298. $global_description = getProp($global_role, 'description');
  10299. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10300. $global_url = getProp($global_role, 'url');
  10301. $global_task_id = getProp($global_role, 'task_id');
  10302. $global_task_status = getProp($global_role, 'task_status');
  10303. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10304. if ($episode_role_name == $global_role_name
  10305. && $episode_description == $global_description
  10306. && $episode_pic_prompt == $global_pic_prompt) {
  10307. // 继承 task_id、task_status 和 url
  10308. if (!empty($global_task_id)) {
  10309. $episode_role['task_id'] = $global_task_id;
  10310. $episode_role['task_status'] = $global_task_status;
  10311. $roles_updated = true;
  10312. dLog('deepseek')->info('剧集角色继承全局task_id', [
  10313. 'episode_id' => $episode_id,
  10314. 'role' => $episode_role_name,
  10315. 'task_id' => $global_task_id,
  10316. 'task_status' => $global_task_status
  10317. ]);
  10318. }
  10319. if (!empty($global_url)) {
  10320. $episode_role['url'] = $global_url;
  10321. $roles_updated = true;
  10322. dLog('deepseek')->info('剧集角色继承全局url', [
  10323. 'episode_id' => $episode_id,
  10324. 'role' => $episode_role_name,
  10325. 'url' => $global_url
  10326. ]);
  10327. }
  10328. break;
  10329. }
  10330. }
  10331. }
  10332. // 继承场景的task_id、task_status和url
  10333. foreach ($episode_scenes as &$episode_scene) {
  10334. $episode_scene_name = getProp($episode_scene, 'scene');
  10335. $episode_description = getProp($episode_scene, 'description');
  10336. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10337. $episode_url = getProp($episode_scene, 'url');
  10338. // 如果剧集中已有URL,跳过
  10339. if (!empty($episode_url)) {
  10340. continue;
  10341. }
  10342. // 遍历全局场景数据,查找匹配的场景
  10343. foreach ($global_scenes as $global_scene) {
  10344. $global_scene_name = getProp($global_scene, 'scene');
  10345. $global_description = getProp($global_scene, 'description');
  10346. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10347. $global_url = getProp($global_scene, 'url');
  10348. $global_task_id = getProp($global_scene, 'task_id');
  10349. $global_task_status = getProp($global_scene, 'task_status');
  10350. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10351. if ($episode_scene_name == $global_scene_name
  10352. && $episode_description == $global_description
  10353. && $episode_pic_prompt == $global_pic_prompt) {
  10354. // 继承 task_id、task_status 和 url
  10355. if (!empty($global_task_id)) {
  10356. $episode_scene['task_id'] = $global_task_id;
  10357. $episode_scene['task_status'] = $global_task_status;
  10358. $scenes_updated = true;
  10359. dLog('deepseek')->info('剧集场景继承全局task_id', [
  10360. 'episode_id' => $episode_id,
  10361. 'scene' => $episode_scene_name,
  10362. 'task_id' => $global_task_id,
  10363. 'task_status' => $global_task_status
  10364. ]);
  10365. }
  10366. if (!empty($global_url)) {
  10367. $episode_scene['url'] = $global_url;
  10368. $scenes_updated = true;
  10369. dLog('deepseek')->info('剧集场景继承全局url', [
  10370. 'episode_id' => $episode_id,
  10371. 'scene' => $episode_scene_name,
  10372. 'url' => $global_url
  10373. ]);
  10374. }
  10375. break;
  10376. }
  10377. }
  10378. }
  10379. // 如果有更新,则保存到数据库
  10380. if ($roles_updated || $scenes_updated) {
  10381. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10382. if ($roles_updated) {
  10383. $update_data['roles'] = json_encode($episode_roles, 256);
  10384. }
  10385. if ($scenes_updated) {
  10386. $update_data['scenes'] = json_encode($episode_scenes, 256);
  10387. }
  10388. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  10389. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  10390. 'episode_id' => $episode_id,
  10391. 'roles_updated' => $roles_updated,
  10392. 'scenes_updated' => $scenes_updated
  10393. ]);
  10394. }
  10395. return true;
  10396. }
  10397. public function chatChangeImg($data) {
  10398. $segment = getProp($data, 'segment');
  10399. $segment_content = getProp($segment, 'segment_content');
  10400. $prompt = getProp($data, 'prompt');
  10401. $ref_img = getProp($data, 'ref_img');
  10402. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  10403. // 处理文本模型
  10404. $model = getProp($data, 'model');
  10405. if (!$model) {
  10406. // 用户没有输入,从anime表获取
  10407. $segment_id = getProp($segment, 'segment_id');
  10408. if ($segment_id) {
  10409. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  10410. if ($episode_id) {
  10411. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  10412. if ($anime_id) {
  10413. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  10414. }
  10415. }
  10416. }
  10417. if (!$model) {
  10418. // anime表也没有,使用默认值
  10419. $model = 'doubao-seed-2-0-mini-260215';
  10420. }
  10421. }
  10422. // 验证模型是否在可用模型表中
  10423. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10424. $model = 'doubao-seed-2-0-mini-260215';
  10425. }
  10426. $messages[] =
  10427. [
  10428. 'role' => 'user',
  10429. 'content' => $question
  10430. ];
  10431. $post_data = [
  10432. 'model' => $model,
  10433. 'messages' => $messages,
  10434. // 'max_tokens' => 8192,
  10435. 'temperature' => 0.7,
  10436. 'frequency_penalty' => 0,
  10437. 'presence_penalty' => 0,
  10438. 'response_format' => ['type' => 'text'],
  10439. 'stream' => false // 是否启用流式输出
  10440. ];
  10441. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10442. // DeepSeek 官方模型使用 DeepSeek API
  10443. $chatResult = $this->chatOnly($post_data);
  10444. } else if (in_array($model, $this->gpt_text_models)) {
  10445. // GPT-5.4 模型使用 TokenRouter API
  10446. $chatResult = $this->gpt54ChatOnly($post_data);
  10447. } else {
  10448. // 其他模型使用火山引擎API
  10449. $chatResult = $this->volcEngineChatCompletion($post_data);
  10450. }
  10451. if (is_array($chatResult)) {
  10452. extract($chatResult);
  10453. }else {
  10454. Utils::throwError('20003: 接口调用失败!');
  10455. }
  10456. return [
  10457. 'type' => 'done',
  10458. // 'episode' => $episode,
  10459. 'answer' => $fullContent,
  10460. 'reasoning' => $fullReasoningContent,
  10461. 'usage' => $usage
  10462. ];
  10463. }
  10464. // 仅调用deepseek对话接口
  10465. private function chatOnly($post_data) {
  10466. $post_data['max_tokens'] = 300000;
  10467. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10468. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  10469. $response = $result->getBody()->getContents();
  10470. $response_arr = json_decode($response, true);
  10471. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  10472. $fullContent = '';
  10473. $fullReasoningContent = [];
  10474. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10475. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10476. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10477. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  10478. }
  10479. return [
  10480. 'fullContent' => $fullContent,
  10481. 'fullReasoningContent' => $fullReasoningContent,
  10482. 'usage' => $usage
  10483. ];
  10484. }
  10485. // 仅调用 GPT-5.4 对话接口(非流式)
  10486. private function gpt54ChatOnly($post_data) {
  10487. $apiKey = env('GPT_54_API_KEY');
  10488. if (empty($apiKey)) {
  10489. Utils::throwError('20003:GPT-5.4 API Key未配置');
  10490. }
  10491. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10492. $headers = [
  10493. 'Authorization' => 'Bearer ' . $apiKey,
  10494. 'Content-Type' => 'application/json'
  10495. ];
  10496. // 移除 thinking 参数,GPT-5.4 不支持
  10497. if (isset($post_data['thinking'])) {
  10498. unset($post_data['thinking']);
  10499. }
  10500. if (isset($post_data['reasoning_effort'])) {
  10501. unset($post_data['reasoning_effort']);
  10502. }
  10503. $post_data['max_completion_tokens'] = 100000;
  10504. // 确保 stream 为 false
  10505. $post_data['stream'] = false;
  10506. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  10507. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  10508. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  10509. 'json' => $post_data,
  10510. 'headers' => $headers
  10511. ]);
  10512. $response = $result->getBody()->getContents();
  10513. $response_arr = json_decode($response, true);
  10514. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  10515. $fullContent = '';
  10516. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10517. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10518. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10519. }
  10520. return [
  10521. 'fullContent' => $fullContent,
  10522. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  10523. 'usage' => $usage
  10524. ];
  10525. }
  10526. private function splitContent($content) {
  10527. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  10528. $chapters = [];
  10529. // 匹配章节标题格式:
  10530. // 1. 标题可能独占一行,也可能在正文末尾或中间
  10531. // 2. 格式支持:
  10532. // - **第一集**
  10533. // - 第一集:
  10534. // - ###第1章 重生
  10535. // - ##第2章 相救
  10536. // - 第三章 共处一室
  10537. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  10538. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  10539. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  10540. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  10541. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  10542. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  10543. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  10544. // 先在每个标题前插入换行符(如果前面不是换行的话)
  10545. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  10546. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  10547. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  10548. // 用正则找出所有章节标题的位置
  10549. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  10550. $titleCount = count($matches[0]);
  10551. for ($i = 0; $i < $titleCount; $i++) {
  10552. // 获取当前章节标题
  10553. $titleLine = trim($matches[0][$i][0]);
  10554. // 去除标题开头的特殊符号
  10555. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  10556. // 去除标题结尾的冒号和特殊符号
  10557. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  10558. $cleanTitle = trim($cleanTitle);
  10559. // 获取当前标题的结束位置
  10560. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  10561. // 获取下一个章节标题的开始位置(如果存在)
  10562. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  10563. // 提取章节内容(从标题结束到下一个标题开始)
  10564. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  10565. // 清理内容:去除前后空白和分隔线
  10566. $chapterContent = trim($chapterContent);
  10567. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  10568. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  10569. if (!empty($cleanTitle) && !empty($chapterContent)) {
  10570. $chapters[] = [
  10571. 'title' => $cleanTitle,
  10572. 'content' => $chapterContent
  10573. ];
  10574. }
  10575. }
  10576. } else {
  10577. // 如果没有匹配到章节,返回整个内容
  10578. $chapters[] = [
  10579. 'title' => '',
  10580. 'content' => $content
  10581. ];
  10582. }
  10583. return $chapters;
  10584. }
  10585. public function getContentByBid($bid) {
  10586. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  10587. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  10588. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  10589. $content = '';
  10590. foreach ($chapters as $chapter) {
  10591. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  10592. }
  10593. return $content;
  10594. }
  10595. public function getContentByScriptId($script_id) {
  10596. $content = '';
  10597. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  10598. if ($contents) {
  10599. $content = implode(PHP_EOL, $contents);
  10600. }else {
  10601. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  10602. }
  10603. return $content;
  10604. }
  10605. /**
  10606. * 根据文件类型提取文本内容
  10607. *
  10608. * @param mixed $file 文件对象或文件路径
  10609. * @return string
  10610. */
  10611. public function extractFileContent($file) {
  10612. // 获取文件路径和扩展名
  10613. if (is_string($file)) {
  10614. $filePath = $file;
  10615. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  10616. } else {
  10617. // Laravel UploadedFile 对象
  10618. $filePath = $file->getRealPath();
  10619. $extension = strtolower($file->getClientOriginalExtension());
  10620. }
  10621. $content = '';
  10622. switch ($extension) {
  10623. case 'txt':
  10624. $content = $this->extractTxtContent($filePath);
  10625. break;
  10626. case 'pdf':
  10627. $content = $this->extractPdfContent($filePath);
  10628. break;
  10629. case 'doc':
  10630. case 'docx':
  10631. $content = $this->extractWordContent($filePath);
  10632. break;
  10633. // case 'jpg':
  10634. // case 'jpeg':
  10635. // case 'png':
  10636. // case 'gif':
  10637. // case 'bmp':
  10638. // case 'webp':
  10639. // $content = $this->extractImageContent($filePath);
  10640. // break;
  10641. default:
  10642. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  10643. }
  10644. return $content;
  10645. }
  10646. /**
  10647. * 提取 TXT 文件内容
  10648. */
  10649. private function extractTxtContent($filePath) {
  10650. if (!file_exists($filePath)) {
  10651. Utils::throwError('20003:文件不存在');
  10652. }
  10653. $content = file_get_contents($filePath);
  10654. // 尝试检测并转换编码
  10655. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  10656. if ($encoding && $encoding !== 'UTF-8') {
  10657. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  10658. }
  10659. return trim($content);
  10660. }
  10661. /**
  10662. * 提取 PDF 文件内容
  10663. */
  10664. private function extractPdfContent($filePath) {
  10665. if (!file_exists($filePath)) {
  10666. Utils::throwError('20003:文件不存在');
  10667. }
  10668. try {
  10669. $parser = new PdfParser();
  10670. $pdf = $parser->parseFile($filePath);
  10671. $content = $pdf->getText();
  10672. return trim($content);
  10673. } catch (\Exception $e) {
  10674. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  10675. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  10676. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  10677. }
  10678. }
  10679. /**
  10680. * 提取 Word 文件内容(支持 doc 和 docx)
  10681. */
  10682. private function extractWordContent($filePath) {
  10683. if (!file_exists($filePath)) {
  10684. Utils::throwError('20003:文件不存在');
  10685. }
  10686. try {
  10687. $phpWord = WordIOFactory::load($filePath);
  10688. $content = '';
  10689. foreach ($phpWord->getSections() as $section) {
  10690. foreach ($section->getElements() as $element) {
  10691. $content .= $this->extractWordElementText($element);
  10692. }
  10693. }
  10694. return trim($content);
  10695. } catch (\Exception $e) {
  10696. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  10697. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  10698. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  10699. }
  10700. }
  10701. /**
  10702. * 递归提取 Word 元素中的文本
  10703. */
  10704. private function extractWordElementText($element) {
  10705. $text = '';
  10706. if (method_exists($element, 'getText')) {
  10707. $text .= $element->getText() . "\n";
  10708. } elseif (method_exists($element, 'getElements')) {
  10709. foreach ($element->getElements() as $childElement) {
  10710. $text .= $this->extractWordElementText($childElement);
  10711. }
  10712. }
  10713. return $text;
  10714. }
  10715. /**
  10716. * 提取图片内容(使用火山引擎 OCR)
  10717. */
  10718. private function extractImageContent($filePath) {
  10719. if (!file_exists($filePath)) {
  10720. Utils::throwError('20003:文件不存在');
  10721. }
  10722. try {
  10723. // 读取图片并转换为 base64
  10724. $imageData = file_get_contents($filePath);
  10725. $base64Image = base64_encode($imageData);
  10726. // 调用火山引擎 OCR 服务
  10727. $content = $this->callVolcEngineOCR($base64Image);
  10728. return trim($content);
  10729. } catch (\Exception $e) {
  10730. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  10731. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  10732. Utils::throwError('20003:图片识别失败');
  10733. }
  10734. }
  10735. /**
  10736. * 调用火山引擎 OCR 服务识别图片文字
  10737. *
  10738. * @param string $base64Image base64 编码的图片数据
  10739. * @return string 识别的文字内容
  10740. */
  10741. private function callVolcEngineOCR($base64Image) {
  10742. $method = 'POST';
  10743. $service = 'cv';
  10744. $host = 'visual.volcengineapi.com';
  10745. $region = env('VOLC_REGION', 'cn-north-1');
  10746. $access_key = env('VOLC_AK');
  10747. $secret_key = env('VOLC_SK');
  10748. $action = 'OCRNormal';
  10749. $version = '2020-08-26';
  10750. if (!$access_key || !$secret_key) {
  10751. Utils::throwError('20003:请配置火山引擎 AK/SK');
  10752. }
  10753. // 请求体
  10754. $body = json_encode([
  10755. 'image_base64' => $base64Image
  10756. ]);
  10757. // 生成签名
  10758. $headers = $this->getVolcEngineSignHeaders(
  10759. $method, $service, $host, $region,
  10760. "Action={$action}&Version={$version}",
  10761. $access_key, $secret_key, $body
  10762. );
  10763. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10764. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  10765. 'headers' => $headers,
  10766. 'body' => $body
  10767. ]);
  10768. $response_arr = json_decode($response->getBody()->getContents(), true);
  10769. // 提取识别的文字
  10770. $textLines = [];
  10771. if (isset($response_arr['data']['line_texts'])) {
  10772. $textLines = $response_arr['data']['line_texts'];
  10773. } elseif (isset($response_arr['data']['ocr_infos'])) {
  10774. foreach ($response_arr['data']['ocr_infos'] as $info) {
  10775. if (isset($info['text'])) {
  10776. $textLines[] = $info['text'];
  10777. }
  10778. }
  10779. }
  10780. if (empty($textLines)) {
  10781. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  10782. return '';
  10783. }
  10784. return implode("\n", $textLines);
  10785. }
  10786. /**
  10787. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  10788. */
  10789. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  10790. $contentType = 'application/json';
  10791. $accept = 'application/json';
  10792. // 获取当前UTC时间
  10793. $t = new DateTime('now', new DateTimeZone('UTC'));
  10794. $xDate = $t->format('Ymd\THis\Z');
  10795. $dateStamp = $t->format('Ymd');
  10796. // 计算 body 的 sha256 哈希
  10797. $payloadHash = hash('sha256', $body);
  10798. // 1. 拼接规范请求串
  10799. $canonicalUri = '/';
  10800. $canonicalQueryString = $queryString;
  10801. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  10802. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  10803. $canonicalRequest = implode("\n", [
  10804. $method,
  10805. $canonicalUri,
  10806. $canonicalQueryString,
  10807. $canonicalHeaders,
  10808. $signedHeaders,
  10809. $payloadHash
  10810. ]);
  10811. // 2. 拼接待签名字符串
  10812. $algorithm = 'HMAC-SHA256';
  10813. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  10814. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  10815. $stringToSign = implode("\n", [
  10816. $algorithm,
  10817. $xDate,
  10818. $credentialScope,
  10819. $hashedCanonicalRequest
  10820. ]);
  10821. // 3. 计算签名
  10822. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  10823. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  10824. // 4. 添加签名到请求头
  10825. $authorizationHeader = sprintf(
  10826. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  10827. $algorithm,
  10828. $access_key,
  10829. $credentialScope,
  10830. $signedHeaders,
  10831. $signature
  10832. );
  10833. return [
  10834. 'Accept' => $accept,
  10835. 'Content-Type' => $contentType,
  10836. 'Host' => $host,
  10837. 'X-Date' => $xDate,
  10838. 'X-Content-Sha256'=> $payloadHash,
  10839. 'Authorization' => $authorizationHeader
  10840. ];
  10841. }
  10842. public function generateScriptWords($cid, $model = 'r1') {
  10843. ini_set('max_execution_time', 0);
  10844. if (!$cid) Utils::throwError('20003: 请选择章节!');
  10845. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  10846. // 模型兼容性处理和思考模式设置
  10847. $thinkingMode = 'disabled';
  10848. $reasoningEffort = 'high';
  10849. if ($model == 'r1') {
  10850. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  10851. $thinkingMode = 'enabled';
  10852. } else {
  10853. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  10854. $thinkingMode = 'disabled';
  10855. }
  10856. $messages = [
  10857. [
  10858. 'role' => 'system',
  10859. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  10860. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  10861. 2.非对话部分请全部用旁白角色代替
  10862. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  10863. ],
  10864. [
  10865. 'role' => 'user',
  10866. 'content' => $content
  10867. ]
  10868. ];
  10869. $post_data = [
  10870. 'model' => $model,
  10871. 'messages' => $messages,
  10872. // 'max_tokens' => 8192,
  10873. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  10874. 'frequency_penalty' => 0,
  10875. 'presence_penalty' => 0,
  10876. 'thinking' => ['type' => $thinkingMode],
  10877. 'response_format' => [
  10878. 'type' => 'text'
  10879. ],
  10880. 'stream' => false
  10881. ];
  10882. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  10883. // 根据模型类型选择调用方法
  10884. $fullContent = '';
  10885. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10886. // DeepSeek 官方模型使用 DeepSeek API
  10887. $chatResult = $this->chatOnly($post_data);
  10888. } else if (in_array($model, $this->gpt_text_models)) {
  10889. // GPT-5.4 模型使用 TokenRouter API
  10890. $chatResult = $this->gpt54ChatOnly($post_data);
  10891. } else {
  10892. // 其他模型使用火山引擎API
  10893. $chatResult = $this->volcEngineChatCompletion($post_data);
  10894. }
  10895. if (is_array($chatResult)) {
  10896. $fullContent = $chatResult['fullContent'];
  10897. }
  10898. return $fullContent;
  10899. }
  10900. /**
  10901. * 智能化解析集数信息
  10902. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  10903. *
  10904. * @param string $prompt 用户输入的提示词
  10905. * @return int|null 解析出的集数,如果没有找到则返回null
  10906. */
  10907. private function extractEpisodeNumber($prompt)
  10908. {
  10909. if (empty($prompt)) {
  10910. return null;
  10911. }
  10912. // 定义各种可能的表达模式
  10913. $patterns = [
  10914. // 基本模式:改成N集、调整成N集、修改成N集
  10915. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  10916. // 扩展模式:分成N集、拆分成N集、分割成N集
  10917. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  10918. // 数量模式:N集、共N集、总共N集
  10919. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  10920. // 制作模式:制作N集、生成N集、创建N集
  10921. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  10922. // 计划模式:计划N集、预计N集、打算N集
  10923. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  10924. // 需要模式:需要N集、要N集
  10925. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  10926. // 中文数字模式:改成三集、调整成五集等
  10927. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  10928. // 英文数字模式
  10929. '/(?: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',
  10930. ];
  10931. // 中文数字转阿拉伯数字的映射
  10932. $chineseNumbers = [
  10933. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  10934. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  10935. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  10936. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  10937. ];
  10938. // 逐个尝试匹配模式
  10939. foreach ($patterns as $pattern) {
  10940. if (preg_match($pattern, $prompt, $matches)) {
  10941. $number = trim($matches[1]);
  10942. // 如果是中文数字,转换为阿拉伯数字
  10943. if (isset($chineseNumbers[$number])) {
  10944. return $chineseNumbers[$number];
  10945. }
  10946. // 如果是阿拉伯数字,直接返回
  10947. if (is_numeric($number)) {
  10948. $episodeNum = intval($number);
  10949. // 合理性检查:集数应该在1-100之间
  10950. if ($episodeNum >= 1 && $episodeNum <= 100) {
  10951. return $episodeNum;
  10952. }
  10953. }
  10954. }
  10955. }
  10956. return null;
  10957. }
  10958. /**
  10959. * 调用火山引擎对话(Chat) API
  10960. *
  10961. * @param array $params 包含以下参数:
  10962. * - model: 模型ID(必填)
  10963. * - messages: 消息列表(必填)
  10964. * - stream: 是否流式输出(可选,默认false)
  10965. * - max_tokens: 最大输出token数(可选)
  10966. * - temperature: 采样温度(可选,默认1)
  10967. * - top_p: 核采样概率(可选,默认0.7)
  10968. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  10969. * - presence_penalty: 存在惩罚系数(可选,默认0)
  10970. * - stop: 停止词(可选)
  10971. * - tools: 工具列表(可选)
  10972. * @return array|Generator 非流式返回数组,流式返回生成器
  10973. */
  10974. public function volcEngineChatCompletion(array $params)
  10975. {
  10976. $apiKey = env('VOLC_AI_API_KEY');
  10977. if (empty($apiKey)) {
  10978. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  10979. }
  10980. // 构建请求参数
  10981. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  10982. $requestData = [
  10983. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  10984. 'messages' => $params['messages'] ?? [],
  10985. ];
  10986. if (!in_array($originalModel, $this->valid_text_models)) {
  10987. Utils::throwError('20003:该模型不支持!');
  10988. }
  10989. // 添加可选参数
  10990. if (isset($params['stream'])) {
  10991. $requestData['stream'] = $params['stream'];
  10992. }
  10993. if (isset($params['stream_options'])) {
  10994. $requestData['stream_options'] = $params['stream_options'];
  10995. }
  10996. if (isset($params['max_tokens'])) {
  10997. $requestData['max_tokens'] = $params['max_tokens'];
  10998. }else if (isset($params['max_completion_tokens'])) {
  10999. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  11000. }else {
  11001. $requestData['max_completion_tokens'] = 100000;
  11002. }
  11003. if (isset($params['temperature'])) {
  11004. $requestData['temperature'] = $params['temperature'];
  11005. }
  11006. if (isset($params['top_p'])) {
  11007. $requestData['top_p'] = $params['top_p'];
  11008. }
  11009. if (isset($params['frequency_penalty'])) {
  11010. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  11011. }
  11012. if (isset($params['presence_penalty'])) {
  11013. $requestData['presence_penalty'] = $params['presence_penalty'];
  11014. }
  11015. if (isset($params['stop'])) {
  11016. $requestData['stop'] = $params['stop'];
  11017. }
  11018. if (isset($params['tools'])) {
  11019. $requestData['tools'] = $params['tools'];
  11020. }
  11021. if (isset($params['tool_choice'])) {
  11022. $requestData['tool_choice'] = $params['tool_choice'];
  11023. }
  11024. if (isset($params['response_format'])) {
  11025. $requestData['response_format'] = $params['response_format'];
  11026. }
  11027. if (isset($params['thinking'])) {
  11028. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  11029. if (is_array($params['thinking'])) {
  11030. $requestData['thinking'] = $params['thinking'];
  11031. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  11032. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11033. }
  11034. } else {
  11035. $requestData['thinking'] = ['type' => $params['thinking']];
  11036. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  11037. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11038. }
  11039. }
  11040. } else {
  11041. $requestData['thinking'] = ['type' => 'disabled'];
  11042. }
  11043. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  11044. $client = new Client(['verify' => false, 'timeout' => 1800]);
  11045. try {
  11046. // 判断是否为流式输出
  11047. $isStream = isset($params['stream']) && $params['stream'] === true;
  11048. if ($isStream) {
  11049. // 流式输出
  11050. // 流式请求默认声明返回 usage(未显式传参时)
  11051. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  11052. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  11053. } else {
  11054. // 非流式输出
  11055. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11056. 'headers' => [
  11057. 'Authorization' => 'Bearer ' . $apiKey,
  11058. 'Content-Type' => 'application/json',
  11059. ],
  11060. 'json' => $requestData
  11061. ]);
  11062. $responseData = json_decode($response->getBody(), true);
  11063. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  11064. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  11065. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  11066. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  11067. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  11068. }
  11069. return [
  11070. 'fullContent' => $fullContent,
  11071. 'fullReasoningContent' => $fullReasoningContent,
  11072. 'usage' => $usage
  11073. ];
  11074. }
  11075. } catch (\Exception $e) {
  11076. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  11077. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  11078. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  11079. }
  11080. }
  11081. /**
  11082. * 火山引擎对话API流式输出
  11083. *
  11084. * @param Client $client HTTP客户端
  11085. * @param string $apiKey API密钥
  11086. * @param array $requestData 请求数据
  11087. * @return Generator
  11088. */
  11089. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  11090. {
  11091. try {
  11092. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11093. 'headers' => [
  11094. 'Authorization' => 'Bearer ' . $apiKey,
  11095. 'Content-Type' => 'application/json',
  11096. ],
  11097. 'json' => $requestData,
  11098. 'stream' => true
  11099. ]);
  11100. $body = $response->getBody();
  11101. $buffer = '';
  11102. $fullContent = '';
  11103. $fullReasoningContent = '';
  11104. $usage = [];
  11105. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  11106. // 逐行读取流式响应
  11107. while (!$body->eof()) {
  11108. $chunk = $body->read(1024);
  11109. $buffer .= $chunk;
  11110. // 按行分割
  11111. $lines = explode("\n", $buffer);
  11112. $buffer = array_pop($lines);
  11113. foreach ($lines as $line) {
  11114. $line = trim($line);
  11115. if (empty($line)) {
  11116. continue;
  11117. }
  11118. // 检查是否是SSE数据行
  11119. if (strpos($line, 'data: ') !== 0) {
  11120. continue;
  11121. }
  11122. $data = substr($line, 6);
  11123. if ($data === '[DONE]') {
  11124. dLog('deepseek')->info('收到结束标记');
  11125. break 2;
  11126. }
  11127. try {
  11128. $json = json_decode($data, true);
  11129. if (json_last_error() !== JSON_ERROR_NONE) {
  11130. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  11131. continue;
  11132. }
  11133. if (isset($json['choices'][0]['delta'])) {
  11134. $delta = $json['choices'][0]['delta'];
  11135. // 处理思维链内容
  11136. if (isset($delta['reasoning_content'])) {
  11137. $fullReasoningContent .= $delta['reasoning_content'];
  11138. yield [
  11139. 'type' => 'reasoning',
  11140. 'content' => $delta['reasoning_content'],
  11141. 'full_reasoning' => $fullReasoningContent
  11142. ];
  11143. }
  11144. // 处理回答内容
  11145. if (isset($delta['content'])) {
  11146. $fullContent .= $delta['content'];
  11147. yield [
  11148. 'type' => 'content',
  11149. 'content' => $delta['content'],
  11150. ];
  11151. }
  11152. }
  11153. // 获取使用统计信息
  11154. if (isset($json['usage'])) {
  11155. $usage = $json['usage'];
  11156. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  11157. }
  11158. } catch (\Exception $e) {
  11159. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  11160. continue;
  11161. }
  11162. }
  11163. }
  11164. dLog('deepseek')->info('流式读取完成', [
  11165. 'content_length' => strlen($fullContent),
  11166. 'reasoning_length' => strlen($fullReasoningContent)
  11167. ]);
  11168. yield [
  11169. 'type' => 'done',
  11170. 'full_content' => $fullContent,
  11171. 'full_reasoning' => $fullReasoningContent,
  11172. 'usage' => $usage
  11173. ];
  11174. } catch (\Exception $e) {
  11175. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  11176. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  11177. throw $e;
  11178. }
  11179. }
  11180. /**
  11181. * 检查并创建图片生成任务
  11182. *
  11183. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  11184. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  11185. * @param string $nameKey 资源名称字段('role' 或 'scene')
  11186. * @param string $art_style 美术风格
  11187. * @return array 更新后的资源列表
  11188. */
  11189. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  11190. {
  11191. // 确保参数为数组
  11192. $merged_items = is_array($merged_items) ? $merged_items : [];
  11193. $global_items = is_array($global_items) ? $global_items : [];
  11194. // 构建全局资源映射表,用于快速查找
  11195. $global_map = [];
  11196. foreach ($global_items as $item) {
  11197. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  11198. if ($itemKey === '') {
  11199. continue;
  11200. }
  11201. $global_map[$itemKey] = $item;
  11202. }
  11203. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  11204. foreach ($merged_items as &$item) {
  11205. $item_name = getProp($item, $nameKey);
  11206. $item_description = getProp($item, 'description');
  11207. // $item_url = getProp($item, 'url');
  11208. // // 如果已有图片URL,跳过
  11209. // if (!empty($item_url)) {
  11210. // continue;
  11211. // }
  11212. // 如果是旁白角色,跳过
  11213. if ($nameKey === 'role' && $item_name === '旁白') {
  11214. continue;
  11215. }
  11216. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  11217. if ($itemKey === '') {
  11218. continue;
  11219. }
  11220. $need_create_task = false;
  11221. // 条件1:在全局资源中找不到匹配的名称
  11222. if (!isset($global_map[$itemKey])) {
  11223. $need_create_task = true;
  11224. } else {
  11225. // 条件2:名称匹配但描述或 pic_prompt 不一致
  11226. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  11227. $current_description = trim((string)$item_description);
  11228. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  11229. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  11230. // 如果 description 或 pic_prompt 有变化,需要重新生成
  11231. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  11232. $need_create_task = true;
  11233. }
  11234. }
  11235. // 如果需要创建任务,调用图片生成服务
  11236. if ($need_create_task) {
  11237. try {
  11238. // 优先使用 pic_prompt,如果没有则使用 description
  11239. $pic_prompt = getProp($item, 'pic_prompt');
  11240. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  11241. // 添加美术风格前缀
  11242. if ($art_style) {
  11243. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  11244. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  11245. $description = "{$prefix}:{$description}";
  11246. }
  11247. $params = [
  11248. 'prompt' => $description,
  11249. 'ref_img_urls' => []
  11250. ];
  11251. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11252. $task_id = $task->id;
  11253. if ($task_id) {
  11254. $item['task_id'] = $task_id;
  11255. $item['task_status'] = 'processing';
  11256. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11257. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  11258. }
  11259. } catch (\Exception $e) {
  11260. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11261. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  11262. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  11263. // 不抛出异常,继续处理其他资源
  11264. }
  11265. }
  11266. }
  11267. return $merged_items;
  11268. }
  11269. /**
  11270. * 同步新出现的主体和场景到全局
  11271. *
  11272. * @param int $anime_id 动漫ID
  11273. * @param array $merged_roles 合并后的角色列表
  11274. * @param array $merged_scenes 合并后的场景列表
  11275. * @param array $global_roles 全局角色列表
  11276. * @param array $global_scenes 全局场景列表
  11277. * @return void
  11278. */
  11279. private function syncNewResourcesToGlobal(
  11280. int $anime_id,
  11281. array $merged_roles,
  11282. array $merged_scenes,
  11283. array $global_roles,
  11284. array $global_scenes
  11285. ): void {
  11286. // 构建全局角色映射表
  11287. $global_role_map = [];
  11288. foreach ($global_roles as $role) {
  11289. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  11290. if ($roleKey !== '') {
  11291. $global_role_map[$roleKey] = $role;
  11292. }
  11293. }
  11294. // 构建全局场景映射表
  11295. $global_scene_map = [];
  11296. foreach ($global_scenes as $scene) {
  11297. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  11298. if ($sceneKey !== '') {
  11299. $global_scene_map[$sceneKey] = $scene;
  11300. }
  11301. }
  11302. $need_update = false;
  11303. $new_global_roles = $global_roles;
  11304. $new_global_scenes = $global_scenes;
  11305. // 检查并添加新角色到全局
  11306. foreach ($merged_roles as $role) {
  11307. $role_name = getProp($role, 'role');
  11308. // 跳过旁白
  11309. if ($role_name === '旁白') {
  11310. continue;
  11311. }
  11312. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  11313. if ($roleKey === '') {
  11314. continue;
  11315. }
  11316. // 如果全局中不存在该角色,添加到全局
  11317. if (!isset($global_role_map[$roleKey])) {
  11318. $new_global_roles[] = [
  11319. 'role' => $role_name,
  11320. 'description' => getProp($role, 'description', ''),
  11321. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  11322. 'voice_name' => getProp($role, 'voice_name', ''),
  11323. 'voice_type' => getProp($role, 'voice_type', ''),
  11324. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  11325. 'url' => getProp($role, 'url', ''),
  11326. 'task_id' => getProp($role, 'task_id', ''),
  11327. 'task_status' => getProp($role, 'task_status', ''),
  11328. ];
  11329. $global_role_map[$roleKey] = true; // 标记已添加
  11330. $need_update = true;
  11331. dLog('deepseek')->info("新角色同步到全局", [
  11332. 'anime_id' => $anime_id,
  11333. 'role' => $role_name,
  11334. 'task_id' => getProp($role, 'task_id', ''),
  11335. ]);
  11336. }
  11337. // else {
  11338. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11339. // $global_role = $global_role_map[$roleKey];
  11340. // if (is_array($global_role)) {
  11341. // $updated = false;
  11342. // $update_fields = [];
  11343. // // 检查描述是否更新
  11344. // $current_description = trim((string)getProp($role, 'description'));
  11345. // $global_description = trim((string)getProp($global_role, 'description'));
  11346. // if ($current_description !== '' && $current_description !== $global_description) {
  11347. // $updated = true;
  11348. // $update_fields[] = 'description';
  11349. // }
  11350. // // 检查pic_prompt是否更新
  11351. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  11352. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  11353. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11354. // $updated = true;
  11355. // $update_fields[] = 'pic_prompt';
  11356. // }
  11357. // // 检查图片任务信息是否更新
  11358. // $current_task_id = getProp($role, 'task_id');
  11359. // $global_task_id = getProp($global_role, 'task_id');
  11360. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11361. // $updated = true;
  11362. // $update_fields[] = 'task_id';
  11363. // }
  11364. // // 如果有更新,同步到全局
  11365. // if ($updated) {
  11366. // foreach ($new_global_roles as &$global_role_item) {
  11367. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  11368. // if ($global_role_key === $roleKey) {
  11369. // if (in_array('description', $update_fields)) {
  11370. // $global_role_item['description'] = $current_description;
  11371. // }
  11372. // if (in_array('pic_prompt', $update_fields)) {
  11373. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  11374. // }
  11375. // if (in_array('task_id', $update_fields)) {
  11376. // $global_role_item['task_id'] = $current_task_id;
  11377. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  11378. // $global_role_item['url'] = getProp($role, 'url', '');
  11379. // }
  11380. // break;
  11381. // }
  11382. // }
  11383. // $need_update = true;
  11384. // dLog('deepseek')->info("角色信息更新到全局", [
  11385. // 'anime_id' => $anime_id,
  11386. // 'role' => $role_name,
  11387. // 'update_fields' => implode(',', $update_fields),
  11388. // ]);
  11389. // }
  11390. // }
  11391. // }
  11392. }
  11393. // 检查并添加新场景到全局
  11394. foreach ($merged_scenes as $scene) {
  11395. $scene_name = getProp($scene, 'scene');
  11396. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  11397. if ($sceneKey === '') {
  11398. continue;
  11399. }
  11400. // 如果全局中不存在该场景,添加到全局
  11401. if (!isset($global_scene_map[$sceneKey])) {
  11402. $new_global_scenes[] = [
  11403. 'scene' => $scene_name,
  11404. 'description' => getProp($scene, 'description', ''),
  11405. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  11406. 'url' => getProp($scene, 'url', ''),
  11407. 'task_id' => getProp($scene, 'task_id', ''),
  11408. 'task_status' => getProp($scene, 'task_status', ''),
  11409. ];
  11410. $global_scene_map[$sceneKey] = true; // 标记已添加
  11411. $need_update = true;
  11412. dLog('deepseek')->info("新场景同步到全局", [
  11413. 'anime_id' => $anime_id,
  11414. 'scene' => $scene_name,
  11415. 'task_id' => getProp($scene, 'task_id', ''),
  11416. ]);
  11417. }
  11418. // else {
  11419. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11420. // $global_scene = $global_scene_map[$sceneKey];
  11421. // if (is_array($global_scene)) {
  11422. // $updated = false;
  11423. // $update_fields = [];
  11424. // // 检查描述是否更新
  11425. // $current_description = trim((string)getProp($scene, 'description'));
  11426. // $global_description = trim((string)getProp($global_scene, 'description'));
  11427. // if ($current_description !== '' && $current_description !== $global_description) {
  11428. // $updated = true;
  11429. // $update_fields[] = 'description';
  11430. // }
  11431. // // 检查pic_prompt是否更新
  11432. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  11433. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  11434. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11435. // $updated = true;
  11436. // $update_fields[] = 'pic_prompt';
  11437. // }
  11438. // // 检查图片任务信息是否更新
  11439. // $current_task_id = getProp($scene, 'task_id');
  11440. // $global_task_id = getProp($global_scene, 'task_id');
  11441. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11442. // $updated = true;
  11443. // $update_fields[] = 'task_id';
  11444. // }
  11445. // // 如果有更新,同步到全局
  11446. // if ($updated) {
  11447. // foreach ($new_global_scenes as &$global_scene_item) {
  11448. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  11449. // if ($global_scene_key === $sceneKey) {
  11450. // if (in_array('description', $update_fields)) {
  11451. // $global_scene_item['description'] = $current_description;
  11452. // }
  11453. // if (in_array('pic_prompt', $update_fields)) {
  11454. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  11455. // }
  11456. // if (in_array('task_id', $update_fields)) {
  11457. // $global_scene_item['task_id'] = $current_task_id;
  11458. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  11459. // $global_scene_item['url'] = getProp($scene, 'url', '');
  11460. // }
  11461. // break;
  11462. // }
  11463. // }
  11464. // $need_update = true;
  11465. // dLog('deepseek')->info("场景信息更新到全局", [
  11466. // 'anime_id' => $anime_id,
  11467. // 'scene' => $scene_name,
  11468. // 'update_fields' => implode(',', $update_fields),
  11469. // ]);
  11470. // }
  11471. // }
  11472. // }
  11473. }
  11474. // 如果有新增或更新,更新数据库
  11475. if ($need_update) {
  11476. $update_data = [
  11477. 'roles' => json_encode($new_global_roles, 256),
  11478. 'scenes' => json_encode($new_global_scenes, 256),
  11479. 'updated_at' => date('Y-m-d H:i:s'),
  11480. ];
  11481. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  11482. if ($result !== false) {
  11483. dLog('deepseek')->info("全局角色和场景更新成功", [
  11484. 'anime_id' => $anime_id,
  11485. 'roles_count' => count($new_global_roles),
  11486. 'scenes_count' => count($new_global_scenes),
  11487. ]);
  11488. } else {
  11489. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  11490. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  11491. }
  11492. }
  11493. }
  11494. }