DeepSeekService.php 949 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431
  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\JsonSafeRepair;
  7. use App\Libs\Utils;
  8. use GuzzleHttp\Client;
  9. use DateTime;
  10. use DateTimeZone;
  11. use App\Models\MpTaskCenter;
  12. use App\Models\MpUserPointsDetail;
  13. use App\Services\AIGeneration\AIImageGenerationService;
  14. use App\Services\PointsService;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Log;
  17. use Illuminate\Support\Facades\Redis;
  18. use OSS\Core\OssException;
  19. use OSS\OssClient;
  20. use Smalot\PdfParser\Parser as PdfParser;
  21. use TCPDF;
  22. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  23. use Predis\Command\Traits\Get\Get;
  24. class DeepSeekService
  25. {
  26. private $url;
  27. private $api_key;
  28. private $sys_message;
  29. private $headers;
  30. private $valid_text_models;
  31. private $gpt_text_models;
  32. private $gemini_text_models;
  33. private $baidu_glm_text_models;
  34. protected $aiImageGenerationService;
  35. protected $pointsService;
  36. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  37. $this->aiImageGenerationService = $aiImageGenerationService;
  38. $this->pointsService = $pointsService;
  39. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  40. $this->api_key = env('DEEPSEEK_API_KEY');
  41. $this->headers = [
  42. 'Authorization' => 'Bearer '.$this->api_key,
  43. 'Content-Type' => 'application/json; charset=UTF-8'
  44. ];
  45. // 火山引擎模型列表
  46. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  47. // GPT文本模型列表
  48. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  49. // Gemini文本模型列表
  50. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  51. // 百度 AI 网关 GLM 文本模型列表
  52. $this->baidu_glm_text_models = BaseConst::BAIDU_GLM_TEXT_MODELS;
  53. $this->sys_message = [
  54. 'role' => 'system',
  55. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  56. 强制要求:\n
  57. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  58. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  59. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  60. 普通要求:\n
  61. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  62. 2.<分集剧本>的要求如下:
  63.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  64.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  65.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  66.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  67. \n\n
  68. 示例如下:\n
  69. ###剧本名:西昆仑
  70. ###故事梗概
  71. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  72. ###剧本亮点
  73. 亮点1:绝境奇药,生死一线
  74. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  75. 亮点2:结拜兄妹,化解尴尬
  76. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  77. 亮点3:纤发夺命,情愫暗涌
  78. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  79. ###人物关系
  80. 阿雪与梁萧之间存在兄妹之情。
  81. ###核心矛盾
  82. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  83. ###主体列表
  84. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  85. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  86. 阴阳球:天地异宝,能化生精气,救人于危难。
  87. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  88. ###美术风格
  89. 基础画风风格词:厚涂古风
  90. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  91. ###场景列表
  92. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  93. ###分集剧本
  94. ##分集01
  95. 第1集: 第一集的标题
  96. 场景描述:地点、时间、场景
  97. 运镜:固定近距离
  98. 出场角色:男主、女主
  99. 台词内容:
  100. 女主: 女主对话
  101. 男主:男主对话
  102. 女主: 女主对话
  103. 男主: 男主对话
  104. ##分集02
  105. 第2集: 第二集的标题
  106. 场景描述:地点、时间、场景
  107. 运镜:固定近距离
  108. 出场角色:男主、女主
  109. 台词内容:
  110. 女主: 女主对话
  111. 男主:男主对话
  112. 女主: 女主对话
  113. 男主: 男主对话"
  114. ];
  115. }
  116. /**
  117. * 通用文生文方法 - 支持多模型流式输出、图片输入;视频输入仅 Gemini 模型支持
  118. *
  119. * @param array $data 请求参数
  120. * @return \Generator 返回生成器,用于流式输出
  121. */
  122. public function generateText($data) {
  123. // 获取请求参数
  124. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  125. $messages = getProp($data, 'messages', []);
  126. $systemPrompt = getProp($data, 'system_prompt', '');
  127. $prompt = getProp($data, 'prompt', '');
  128. $images = getProp($data, 'images', []); // 支持多张图片
  129. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  130. $videos = getProp($data, 'videos', []); // Gemini 支持视频文件
  131. $videoUrls = getProp($data, 'video_urls', []); // Gemini 支持视频URL
  132. $isGeminiModel = in_array($model, $this->gemini_text_models);
  133. if ((!empty($videos) || !empty($videoUrls)) && !$isGeminiModel) {
  134. Utils::throwError('20003:仅Gemini模型支持视频输入');
  135. }
  136. // 计费预检:纯文生文按 normal 档(3);有参考图/视频输入按模型固定价格(图生文)
  137. $uid = Site::getUid();
  138. $chargeModality = '';
  139. $chargePoints = 0;
  140. $hasImageMedia = !empty($images) || !empty($imageUrls)
  141. || $this->messagesContainMedia($messages, ['image_url', 'image']);
  142. $hasVideoMedia = !empty($videos) || !empty($videoUrls)
  143. || $this->messagesContainMedia($messages, ['video_url', 'video']);
  144. if ($hasImageMedia || $hasVideoMedia) {
  145. $chargeModality = $hasVideoMedia ? 'video' : 'image';
  146. $chargePoints = $this->pointsService->getImageChatChargePoints($model);
  147. } else {
  148. $chargeModality = 'text';
  149. $chargePoints = $this->pointsService->getChatChargePoints('', 'normal');
  150. }
  151. if ($chargePoints > 0) {
  152. $this->pointsService->checkUserPointsEnough($chargePoints, $uid);
  153. }
  154. // 如果没有提供messages,则根据system_prompt、content和images构建
  155. if (empty($messages)) {
  156. $messages = [];
  157. // 添加系统提示词
  158. if (!empty($systemPrompt)) {
  159. $messages[] = [
  160. 'role' => 'system',
  161. 'content' => $systemPrompt
  162. ];
  163. }
  164. // 构建用户消息内容(支持文本+图片)
  165. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  166. $userMessage = [
  167. 'role' => 'user',
  168. 'content' => []
  169. ];
  170. // 添加文本内容
  171. if (!empty($prompt)) {
  172. $userMessage['content'][] = [
  173. 'type' => 'text',
  174. 'text' => $prompt
  175. ];
  176. }
  177. // 处理上传的图片文件
  178. if (!empty($images)) {
  179. if (!is_array($images)) {
  180. $images = [$images];
  181. }
  182. foreach ($images as $image) {
  183. $imageBase64 = $this->processImageToBase64($image);
  184. if ($imageBase64) {
  185. $userMessage['content'][] = [
  186. 'type' => 'image_url',
  187. 'image_url' => [
  188. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  189. ]
  190. ];
  191. }
  192. }
  193. }
  194. // 处理图片URL
  195. if (!empty($imageUrls)) {
  196. if (!is_array($imageUrls)) {
  197. $imageUrls = [$imageUrls];
  198. }
  199. foreach ($imageUrls as $url) {
  200. if (!empty($url)) {
  201. $userMessage['content'][] = [
  202. 'type' => 'image_url',
  203. 'image_url' => [
  204. 'url' => $url
  205. ]
  206. ];
  207. }
  208. }
  209. }
  210. // 处理上传的视频文件(仅 Gemini)
  211. if (!empty($videos) && $isGeminiModel) {
  212. if (!is_array($videos)) {
  213. $videos = [$videos];
  214. }
  215. foreach ($videos as $video) {
  216. $inlineData = $this->processMediaToInlineData($video);
  217. if ($inlineData) {
  218. $userMessage['content'][] = [
  219. 'type' => 'video',
  220. 'inline_data' => $inlineData
  221. ];
  222. }
  223. }
  224. }
  225. // 处理视频URL(仅 Gemini)
  226. if (!empty($videoUrls) && $isGeminiModel) {
  227. if (!is_array($videoUrls)) {
  228. $videoUrls = [$videoUrls];
  229. }
  230. foreach ($videoUrls as $url) {
  231. if (!empty($url)) {
  232. $userMessage['content'][] = [
  233. 'type' => 'video_url',
  234. 'video_url' => ['url' => $url]
  235. ];
  236. }
  237. }
  238. }
  239. // 如果只有文本内容,简化为字符串格式
  240. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  241. $userMessage['content'] = $userMessage['content'][0]['text'];
  242. }
  243. $messages[] = $userMessage;
  244. }
  245. }
  246. // 验证messages不为空
  247. if (empty($messages)) {
  248. Utils::throwError('20003:请提供有效的对话内容');
  249. }
  250. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  251. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  252. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  253. if ($model === 'deepseek-chat') {
  254. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  255. $model = 'deepseek-v4-flash';
  256. $thinkingMode = 'disabled';
  257. } elseif ($model === 'deepseek-reasoner') {
  258. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  259. $model = 'deepseek-v4-flash';
  260. $thinkingMode = 'enabled';
  261. }
  262. // 构建请求参数
  263. $post_data = [
  264. 'model' => $model,
  265. 'messages' => $messages,
  266. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  267. 'temperature' => getProp($data, 'temperature', 1),
  268. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  269. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  270. 'thinking' => ['type' => $thinkingMode],
  271. 'stream' => true // 启用流式输出
  272. ];
  273. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  274. // 添加可选参数
  275. if (isset($data['top_p'])) {
  276. $post_data['top_p'] = $data['top_p'];
  277. }
  278. if (isset($data['response_format'])) {
  279. $post_data['response_format'] = $data['response_format'];
  280. }
  281. // 根据模型类型选择流式实现
  282. $streamGenerator = $this->dispatchStreamByModel($post_data);
  283. if ($chargePoints > 0) {
  284. return $this->wrapGenerateTextCharge($streamGenerator, $uid, $model, $chargePoints, $chargeModality);
  285. }
  286. // 免费场景(0 积分):流式生成成功后仅记录 token 使用明细
  287. return $this->wrapGenerateTextTokenRecord($streamGenerator, $uid, $model);
  288. }
  289. /**
  290. * 流式生成成功后仅记录 token 明细(纯文本免费场景,不扣积分)
  291. *
  292. * @param \Generator $generator
  293. * @param int $uid
  294. * @param string $model
  295. * @return \Generator
  296. */
  297. private function wrapGenerateTextTokenRecord(\Generator $generator, int $uid, string $model, string $source = 'generateText'): \Generator
  298. {
  299. $recorded = false;
  300. foreach ($generator as $chunk) {
  301. if (!$recorded && isset($chunk['type']) && $chunk['type'] === 'done') {
  302. $this->recordTextTokenOnly($uid, $this->pointsService->getTokensFromUsage(getProp($chunk, 'usage', [])), [
  303. 'model' => $model,
  304. 'source' => $source,
  305. ], $model);
  306. $recorded = true;
  307. }
  308. yield $chunk;
  309. }
  310. }
  311. /**
  312. * 流式生成成功后再按档位/模型规则扣费(文生文 normal 档 / 图生文按模型固定价格)
  313. *
  314. * @param \Generator $generator
  315. * @param int $uid
  316. * @param string $model
  317. * @param int $points
  318. * @param string $modality
  319. * @return \Generator
  320. */
  321. private function wrapGenerateTextCharge(\Generator $generator, int $uid, string $model, int $points, string $modality): \Generator
  322. {
  323. $charged = false;
  324. foreach ($generator as $chunk) {
  325. if (!$charged && isset($chunk['type']) && $chunk['type'] === 'done') {
  326. $fullContent = (string)getProp($chunk, 'full_content', getProp($chunk, 'answer', ''));
  327. if ($fullContent !== '') {
  328. $this->chargeMultimodal($uid, $model, $points, $modality, getProp($chunk, 'usage', []));
  329. $charged = true;
  330. }
  331. }
  332. yield $chunk;
  333. }
  334. }
  335. /**
  336. * AI 对话(含图片/视频 -> 文本)成功后扣费并记录积分与 token 明细
  337. *
  338. * @param int $uid
  339. * @param string $model
  340. * @param int $points
  341. * @param string $modality
  342. * @param mixed $usage
  343. * @return void
  344. */
  345. private function chargeMultimodal(int $uid, string $model, int $points, string $modality, $usage): void
  346. {
  347. $result = $this->pointsService->recordChatCharge(
  348. $uid,
  349. $points,
  350. $this->pointsService->getTokensFromUsage($usage),
  351. [
  352. 'model' => $model,
  353. 'modality' => $modality,
  354. 'source' => 'generateText',
  355. ],
  356. '',
  357. $model
  358. );
  359. if (empty($result['charged'])) {
  360. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  361. }
  362. }
  363. /**
  364. * 检查 OpenAI 风格消息中是否包含指定媒体类型
  365. *
  366. * @param array $messages
  367. * @param array $mediaTypes
  368. * @return bool
  369. */
  370. private function messagesContainMedia(array $messages, array $mediaTypes): bool
  371. {
  372. foreach ($messages as $message) {
  373. $content = getProp($message, 'content', '');
  374. if (!is_array($content)) {
  375. continue;
  376. }
  377. foreach ($content as $part) {
  378. if (is_array($part) && in_array(getProp($part, 'type', ''), $mediaTypes, true)) {
  379. return true;
  380. }
  381. }
  382. }
  383. return false;
  384. }
  385. public function createGenerateText($data) {
  386. $file = getProp($data, 'file');
  387. $episode_num = getProp($data, 'episode_num');
  388. $uid = Site::getUid();
  389. $cpid = Site::getCpid();
  390. if (!$file) {
  391. Utils::throwError('20003:请上传文件');
  392. }
  393. // 提取文件内容
  394. $content = $this->extractFileContent($file);
  395. if (!$content) {
  396. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  397. }
  398. // 拆分章节并校验章节总数、标题连续性
  399. if ($episode_num) {
  400. $this->validateGenerateTextChapters($content, (int)$episode_num);
  401. }
  402. // 获取原始文件名(不含扩展名)作为script_name
  403. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  404. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  405. // 字节安全剥离,不依赖服务器locale设置
  406. $originalName = $file->getClientOriginalName();
  407. $extension = $file->getClientOriginalExtension();
  408. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  409. ? substr($originalName, 0, -strlen($extension) - 1)
  410. : $originalName;
  411. if ($script_name === '') {
  412. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  413. }
  414. // 如果同一用户的剧本名存在则提示
  415. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  416. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  417. }
  418. // 插入数据到mp_scripts表
  419. $script_id = DB::table('mp_scripts')->insertGetId([
  420. 'script_name' => $script_name,
  421. 'user_id' => $uid,
  422. 'cpid' => $cpid,
  423. 'content' => $content,
  424. 'created_at' => date('Y-m-d H:i:s'),
  425. 'updated_at' => date('Y-m-d H:i:s')
  426. ]);
  427. return [
  428. 'script_id' => $script_id,
  429. 'script_name' => $script_name
  430. ];
  431. }
  432. /**
  433. * AI对话调用成功后的积分扣费(返回结果前调用)
  434. *
  435. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  436. *
  437. * @param int $uid
  438. * @param int $tokens
  439. * @param array $chargeInfo
  440. * @return void
  441. */
  442. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo, string $chargeType = 'special'): void
  443. {
  444. // api_type 记录真实模型名(缺失时回退 deepseek 大类),保证明细与统计口径准确
  445. $model = (string)getProp($chargeInfo, 'model', '');
  446. $result = $this->pointsService->recordChatCharge(
  447. $uid,
  448. $this->pointsService->getChatChargePoints($model, $chargeType),
  449. $tokens,
  450. $chargeInfo,
  451. '',
  452. $model !== '' ? $model : 'deepseek'
  453. );
  454. if (empty($result['charged'])) {
  455. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  456. }
  457. }
  458. /**
  459. * 安全获取当前登录用户ID
  460. *
  461. * 命令行/队列等无用户上下文的场景返回 0,由记录方法自行跳过。
  462. *
  463. * @return int
  464. */
  465. private function getCurrentUid(): int
  466. {
  467. try {
  468. return (int)Site::getUid();
  469. } catch (\Throwable $e) {
  470. return 0;
  471. }
  472. }
  473. /**
  474. * 记录文生文 token 使用明细(仅记录,不扣积分)
  475. *
  476. * 用于不按积分计费的文生文接口;记录失败不影响主流程。
  477. *
  478. * @param int $uid 用户ID(0 时跳过)
  479. * @param int $tokens 消耗 token 数
  480. * @param array $chargeInfo 计费/来源信息(model、source 等)
  481. * @param string $apiType API 类型/模型标识
  482. * @return void
  483. */
  484. private function recordTextTokenOnly(int $uid, int $tokens, array $chargeInfo, string $apiType = ''): void
  485. {
  486. try {
  487. $this->pointsService->recordTokenOnlyDetail(
  488. $uid,
  489. $tokens,
  490. $chargeInfo,
  491. MpUserPointsDetail::TYPE_CHAT,
  492. $apiType,
  493. ''
  494. );
  495. } catch (\Throwable $e) {
  496. dLog('points')->warning('token明细记录异常(不影响主流程): ' . $e->getMessage(), [
  497. 'uid' => $uid,
  498. 'source' => $chargeInfo['source'] ?? '',
  499. ]);
  500. }
  501. }
  502. /**
  503. * 拆分剧本内容并校验章节总数与标题连续性
  504. *
  505. * @param string $content
  506. * @param int $episodeNum
  507. * @return void
  508. */
  509. private function validateGenerateTextChapters($content, $episodeNum)
  510. {
  511. $chapters = splitContent($content);
  512. if (count($chapters) !== $episodeNum) {
  513. Utils::throwError('20003:章节总数与集数不一致,请检查上传内容');
  514. }
  515. if (empty($chapters)) {
  516. return;
  517. }
  518. // 先尝试从标题正则中解析序号,确认是否从1开始连续递增
  519. $numbers = [];
  520. $unparsedIndex = null;
  521. foreach ($chapters as $index => $chapter) {
  522. $num = $this->parseChapterNumber($chapter['title']);
  523. if ($num === null) {
  524. $unparsedIndex = $index;
  525. break;
  526. }
  527. $numbers[] = $num;
  528. }
  529. if ($unparsedIndex === null) {
  530. $expected = 1;
  531. foreach ($numbers as $index => $num) {
  532. if ($num !== $expected) {
  533. $title = mb_substr(trim((string)$chapters[$index]['title']), 0, 40);
  534. Utils::throwError('20003:章节序号不连续:第' . ($index + 1) . '个章节“' . $title . '”序号为' . $num . ',预期为' . $expected);
  535. }
  536. $expected++;
  537. }
  538. return;
  539. }
  540. // 标题格式无法用正则确认时,交给模型分析
  541. $titles = array_column($chapters, 'title');
  542. $aiResult = $this->validateChapterSequenceByAI($titles);
  543. if ($aiResult['valid'] === false) {
  544. $badIndex = $aiResult['invalid_index'] ?: $unparsedIndex + 1;
  545. if (isset($chapters[$badIndex - 1])) {
  546. $title = mb_substr(trim((string)$chapters[$badIndex - 1]['title']), 0, 40);
  547. Utils::throwError('20003:章节序号不连续:第' . $badIndex . '个章节“' . $title . '”序号异常,请检查');
  548. }
  549. Utils::throwError('20003:章节序号不连续,请检查章节标题格式');
  550. }
  551. if ($aiResult['valid'] === null) {
  552. if (isset($chapters[$unparsedIndex])) {
  553. $title = mb_substr(trim((string)$chapters[$unparsedIndex]['title']), 0, 40);
  554. Utils::throwError('20003:无法确认第' . ($unparsedIndex + 1) . '个章节“' . $title . '”的章节序号,请检查标题格式');
  555. }
  556. Utils::throwError('20003:无法确认章节标题连续性,请检查章节标题格式');
  557. }
  558. }
  559. /**
  560. * 从章节标题中解析序号,支持阿拉伯数字和中文数字
  561. *
  562. * @param string $title
  563. * @return int|null
  564. */
  565. private function parseChapterNumber($title)
  566. {
  567. if (!preg_match('/第\s*([一二两三四五六七八九十百千万0-9]+)\s*[章节集幕场回话]/u', $title, $match)) {
  568. return null;
  569. }
  570. return $this->convertChineseNumber($match[1]);
  571. }
  572. /**
  573. * 中文数字转阿拉伯数字(支持到千)
  574. *
  575. * @param string $numStr
  576. * @return int
  577. */
  578. private function convertChineseNumber($numStr)
  579. {
  580. if (preg_match('/^\d+$/', $numStr)) {
  581. return (int)$numStr;
  582. }
  583. $map = [
  584. '零' => 0,
  585. '一' => 1,
  586. '二' => 2,
  587. '两' => 2,
  588. '三' => 3,
  589. '四' => 4,
  590. '五' => 5,
  591. '六' => 6,
  592. '七' => 7,
  593. '八' => 8,
  594. '九' => 9
  595. ];
  596. $total = 0;
  597. $section = 0;
  598. $length = mb_strlen($numStr);
  599. for ($i = 0; $i < $length; $i++) {
  600. $char = mb_substr($numStr, $i, 1);
  601. if (isset($map[$char])) {
  602. $section = $map[$char];
  603. } elseif ($char === '十') {
  604. $total += $section === 0 ? 10 : $section * 10;
  605. $section = 0;
  606. } elseif ($char === '百') {
  607. $total += $section === 0 ? 100 : $section * 100;
  608. $section = 0;
  609. } elseif ($char === '千') {
  610. $total += $section === 0 ? 1000 : $section * 1000;
  611. $section = 0;
  612. }
  613. }
  614. return $total + $section;
  615. }
  616. /**
  617. * 用 deepseek-v4-flash 非流式判断章节标题是否从1开始连续编号
  618. *
  619. * @param array $titles
  620. * @return array{valid: bool|null, invalid_index: int|null}
  621. */
  622. private function validateChapterSequenceByAI($titles)
  623. {
  624. $titleLines = [];
  625. foreach (array_slice($titles, 0, 200) as $index => $title) {
  626. $titleLines[] = ($index + 1) . '. ' . mb_substr(trim((string)$title), 0, 80);
  627. }
  628. $result = [
  629. 'valid' => null,
  630. 'invalid_index' => null
  631. ];
  632. $post_data = [
  633. 'model' => 'deepseek-v4-flash',
  634. 'messages' => [
  635. [
  636. 'role' => 'system',
  637. 'content' => '你是剧本章节校验助手。用户会给出章节标题列表,请判断这些标题中的编号是否从第1章/第1集开始连续递增,支持阿拉伯数字和中文数字。只输出 JSON,格式为 {"valid":true};若不连续则输出 {"valid":false,"invalid_index":N},其中 N 是第一个序号异常的章节序号(从1开始),不要输出其他内容。',
  638. ],
  639. [
  640. 'role' => 'user',
  641. 'content' => implode("\n", $titleLines),
  642. ],
  643. ],
  644. 'temperature' => 0,
  645. 'frequency_penalty' => 0,
  646. 'presence_penalty' => 0,
  647. 'stream' => false,
  648. ];
  649. try {
  650. $result = $this->chatOnly($post_data, 8);
  651. $content = trim((string)($result['fullContent'] ?? ''));
  652. if (preg_match('/"valid"\s*:\s*(true|false)/i', $content, $match)) {
  653. $result['valid'] = strtolower($match[1]) === 'true';
  654. }
  655. if (preg_match('/"invalid_index"\s*:\s*(\d+)/i', $content, $match)) {
  656. $result['invalid_index'] = (int)$match[1];
  657. }
  658. // 仅记录 token 使用明细(不扣积分):该校验为流程内的额外模型调用
  659. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  660. 'model' => 'deepseek-v4-flash',
  661. 'source' => 'validateChapterSequenceByAI',
  662. ], 'deepseek-v4-flash');
  663. } catch (\Exception $e) {
  664. dLog('deepseek')->error('章节连续性AI校验失败: ' . $e->getMessage());
  665. }
  666. return $result;
  667. }
  668. /**
  669. * 通用文生文(流式版本)- newGenerateText 的 stream=1 分支
  670. * 支持与 newGenerateText 相同的参数(模板/剧本/JSON输出/图片输入),
  671. * 输出格式与 generateText 一致:yield type=content / reasoning / done
  672. *
  673. * @param array $data 请求参数
  674. * @return \Generator
  675. */
  676. public function newGenerateTextStream($data, $existingTask = null) {
  677. $model = getProp($data, 'model', 'deepseek-v4-pro');
  678. $messages = getProp($data, 'messages', []);
  679. $systemPrompt = getProp($data, 'system_prompt', '');
  680. $prompt = getProp($data, 'prompt', '');
  681. $images = getProp($data, 'images', []);
  682. $imageUrls = getProp($data, 'image_urls', []);
  683. $responseFormat = getProp($data, 'response_format', 'text');
  684. $templateId = getProp($data, 'template_id', 0);
  685. $script_id = getProp($data, 'script_id', 0);
  686. $sequence = getProp($data, 'sequence', 0);
  687. $generateTaskId = 0;
  688. // 异步 worker 场景直接使用任务记录中的用户,避免命令行下无登录上下文
  689. $uid = $existingTask ? (int)$existingTask->uid : (int)Site::getUid();
  690. if ($script_id > 0 && !$existingTask) {
  691. $runningTask = DB::table('mp_script_generate_tasks')
  692. ->where('uid', $uid)
  693. ->where('script_id', $script_id)
  694. ->orderByDesc('id')
  695. ->first();
  696. if ($runningTask && in_array(getProp($runningTask, 'status'), ['pending', 'processing'])) {
  697. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  698. }
  699. }
  700. // 如果提供了script_id,从数据库获取剧本内容作为原文
  701. $originalContent = '';
  702. $hasValidScript = false;
  703. $rawPrompt = $prompt; // 保存用户原始输入,供模板一致性判断
  704. if ($script_id > 0) {
  705. $script = DB::table('mp_scripts')
  706. ->where('id', $script_id)
  707. ->where('is_deleted', 0)
  708. ->first();
  709. if (!$script) {
  710. Utils::throwError('20003:剧本不存在或已删除');
  711. }
  712. $originalContent = $script->content ?? '';
  713. if (empty($originalContent)) {
  714. Utils::throwError('20003:剧本内容为空');
  715. }
  716. $hasValidScript = true;
  717. if (!empty($prompt)) {
  718. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  719. } else {
  720. $prompt = "原文内容:\n" . $originalContent;
  721. }
  722. }
  723. // 如果提供了template_id,从数据库获取template_prompt
  724. if ($templateId > 0) {
  725. $template = DB::table('mp_prompt_templates')
  726. ->where('id', $templateId)
  727. ->where('is_deleted', 0)
  728. ->first();
  729. if (!$template) {
  730. Utils::throwError('20003:模板不存在或已删除');
  731. }
  732. $templatePrompt = $template->template_prompt ?? '';
  733. if (!empty($templatePrompt)) {
  734. // 模板提示词与用户输入基本一致时只保留一个,避免重复提示词
  735. // 剧本模式下当前 prompt 含原文内容需保留,其余情况以模板内容为准
  736. $trimmedRawPrompt = trim((string)$rawPrompt);
  737. if ($trimmedRawPrompt !== '' && mb_strtolower($trimmedRawPrompt) === mb_strtolower(trim($templatePrompt))) {
  738. if (!$hasValidScript) {
  739. $prompt = $templatePrompt;
  740. }
  741. } elseif (!empty($prompt)) {
  742. $prompt = $templatePrompt . "\n\n" . $prompt;
  743. } else {
  744. $prompt = $templatePrompt;
  745. }
  746. }
  747. }
  748. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  749. if (empty($messages)) {
  750. $messages = [];
  751. if (!empty($systemPrompt)) {
  752. $messages[] = [
  753. 'role' => 'system',
  754. 'content' => $systemPrompt
  755. ];
  756. }
  757. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  758. $userMessage = [
  759. 'role' => 'user',
  760. 'content' => []
  761. ];
  762. if (!empty($prompt)) {
  763. $userMessage['content'][] = [
  764. 'type' => 'text',
  765. 'text' => $prompt
  766. ];
  767. }
  768. if (!empty($images)) {
  769. if (!is_array($images)) {
  770. $images = [$images];
  771. }
  772. foreach ($images as $image) {
  773. $imageBase64 = $this->processImageToBase64($image);
  774. if ($imageBase64) {
  775. $userMessage['content'][] = [
  776. 'type' => 'image_url',
  777. 'image_url' => [
  778. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  779. ]
  780. ];
  781. }
  782. }
  783. }
  784. if (!empty($imageUrls)) {
  785. if (!is_array($imageUrls)) {
  786. $imageUrls = [$imageUrls];
  787. }
  788. foreach ($imageUrls as $url) {
  789. if (!empty($url)) {
  790. $userMessage['content'][] = [
  791. 'type' => 'image_url',
  792. 'image_url' => [
  793. 'url' => $url
  794. ]
  795. ];
  796. }
  797. }
  798. }
  799. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  800. $userMessage['content'] = $userMessage['content'][0]['text'];
  801. }
  802. $messages[] = $userMessage;
  803. }
  804. }
  805. if (empty($messages)) {
  806. Utils::throwError('20003:请提供有效的对话内容');
  807. }
  808. // 模型兼容性处理
  809. $thinkingMode = getProp($data, 'thinking', 'disabled');
  810. $reasoningEffort = getProp($data, 'reasoning_effort', 'high');
  811. if ($model === 'deepseek-chat') {
  812. $model = 'deepseek-v4-flash';
  813. $thinkingMode = 'disabled';
  814. } elseif ($model === 'deepseek-reasoner') {
  815. $model = 'deepseek-v4-flash';
  816. $thinkingMode = 'enabled';
  817. }
  818. // 构建请求参数(流式)
  819. $post_data = [
  820. 'model' => $model,
  821. 'messages' => $messages,
  822. 'temperature' => getProp($data, 'temperature', 1),
  823. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  824. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  825. 'thinking' => ['type' => $thinkingMode],
  826. 'stream' => true
  827. ];
  828. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  829. if (isset($data['top_p'])) {
  830. $post_data['top_p'] = $data['top_p'];
  831. }
  832. // response_format=json 时附加 JSON 说明与响应格式(与 newGenerateText 一致)
  833. if ($responseFormat === 'json') {
  834. $hasJsonKeyword = false;
  835. foreach ($post_data['messages'] as $message) {
  836. if (isset($message['content'])) {
  837. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  838. if (stripos($content, 'json') !== false) {
  839. $hasJsonKeyword = true;
  840. break;
  841. }
  842. }
  843. }
  844. if (!$hasJsonKeyword) {
  845. $lastMessageIndex = count($post_data['messages']) - 1;
  846. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  847. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  848. if (is_string($lastContent)) {
  849. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  850. } elseif (is_array($lastContent)) {
  851. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  852. if ($contentPart['type'] === 'text') {
  853. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  854. break;
  855. }
  856. }
  857. }
  858. }
  859. }
  860. $post_data['response_format'] = ['type' => 'json_object'];
  861. }
  862. // 如果提供了script_id,创建剧本资产生成任务
  863. if ($script_id > 0) {
  864. if ($existingTask) {
  865. // 异步 worker:接管已创建的 pending 任务,不再新建
  866. $generateTaskId = (int)$existingTask->id;
  867. } else {
  868. // 同步调用:保持原行为,创建 processing 任务
  869. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  870. 'uid' => $uid,
  871. 'script_id' => $script_id,
  872. 'sequence' => $sequence,
  873. 'status' => 'processing',
  874. 'prompt' => getProp($data, 'prompt', ''),
  875. 'started_at' => date('Y-m-d H:i:s'),
  876. 'created_at' => date('Y-m-d H:i:s'),
  877. 'updated_at' => date('Y-m-d H:i:s')
  878. ]);
  879. }
  880. }
  881. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  882. if ($hasValidScript) {
  883. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  884. }
  885. // 根据模型类型选择流式实现
  886. $streamGenerator = $this->dispatchStreamByModel($post_data);
  887. // 流式输出包装:done 时更新任务状态、扣费并保存对话记录
  888. return $this->wrapNewGenerateTextStream($streamGenerator, [
  889. 'uid' => $uid,
  890. 'model' => $model,
  891. 'generate_task_id' => $generateTaskId,
  892. 'has_valid_script' => $hasValidScript,
  893. 'script_id' => $script_id,
  894. 'sequence' => $sequence,
  895. 'original_prompt' => getProp($data, 'prompt', ''),
  896. 'response_format' => $responseFormat,
  897. ]);
  898. }
  899. /**
  900. * 流式生成收尾包装:done 时更新剧本资产生成任务、扣除积分并保存对话记录
  901. *
  902. * @param \Generator $generator
  903. * @param array $ctx
  904. * @return \Generator
  905. */
  906. private function wrapNewGenerateTextStream(\Generator $generator, array $ctx): \Generator
  907. {
  908. $fullContent = '';
  909. $usage = [];
  910. $finished = false;
  911. try {
  912. foreach ($generator as $chunk) {
  913. if (isset($chunk['type']) && $chunk['type'] === 'content') {
  914. $fullContent .= (string)getProp($chunk, 'content', '');
  915. }
  916. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  917. $fullContent = (string)getProp($chunk, 'full_content', $fullContent);
  918. $usage = getProp($chunk, 'usage', []);
  919. // 流式场景下部分模型/中转站不强制 JSON 输出,兜底提取标准 JSON
  920. if (($ctx['response_format'] ?? 'text') === 'json') {
  921. $fullContent = $this->extractJsonContent($fullContent);
  922. }
  923. $finished = true;
  924. // 保存对话记录并将 records 附加到 done 消息(无论 script_id 是否有值都返回 records 数组)
  925. $chunk['records'] = [];
  926. if (!empty($ctx['script_id'])) {
  927. try {
  928. $now = now();
  929. // 两条对话记录(user/assistant)在同一事务内写入,保证原子性
  930. $chunk['records'] = DB::transaction(function () use ($ctx, $fullContent, $now) {
  931. DB::table('mp_script_records')->insert([
  932. [
  933. 'uid' => $ctx['uid'],
  934. 'script_id' => $ctx['script_id'],
  935. 'sequence' => $ctx['sequence'],
  936. 'role' => 'user',
  937. 'content' => $ctx['original_prompt'],
  938. 'created_at' => $now,
  939. 'updated_at' => $now,
  940. ],
  941. [
  942. 'uid' => $ctx['uid'],
  943. 'script_id' => $ctx['script_id'],
  944. 'sequence' => $ctx['sequence'],
  945. 'role' => 'assistant',
  946. 'content' => $fullContent,
  947. 'created_at' => $now,
  948. 'updated_at' => $now,
  949. ],
  950. ]);
  951. return DB::table('mp_script_records')
  952. ->where('uid', $ctx['uid'])
  953. ->where('script_id', $ctx['script_id'])
  954. ->where('sequence', $ctx['sequence'])
  955. ->orderBy('id', 'desc')
  956. ->limit(2)
  957. ->get()
  958. ->map(function ($record) {
  959. return [
  960. 'rid' => $record->id,
  961. 'script_id' => $record->script_id,
  962. 'sequence' => $record->sequence,
  963. 'role' => $record->role,
  964. 'content' => $record->content,
  965. 'created_at' => $record->created_at,
  966. ];
  967. })
  968. ->reverse()
  969. ->values()
  970. ->toArray();
  971. });
  972. } catch (\Exception $e) {
  973. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  974. $chunk['records'] = [];
  975. }
  976. }
  977. }
  978. yield $chunk;
  979. }
  980. if ($finished) {
  981. // 任务状态与扣费在同一事务内:扣费失败则任务状态一并回滚,由外层 catch 置为 failed
  982. DB::transaction(function () use ($ctx, $fullContent, $usage) {
  983. if (!empty($ctx['generate_task_id'])) {
  984. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  985. 'status' => 'success',
  986. 'result' => $fullContent,
  987. 'completed_at' => date('Y-m-d H:i:s'),
  988. 'updated_at' => date('Y-m-d H:i:s'),
  989. ]);
  990. }
  991. if ($ctx['has_valid_script'] && $fullContent !== '') {
  992. $this->chargeChatSuccess($ctx['uid'], $this->pointsService->getTokensFromUsage($usage), [
  993. 'model' => $ctx['model'],
  994. 'script_id' => $ctx['script_id'],
  995. 'sequence' => $ctx['sequence'],
  996. 'source' => 'newGenerateText',
  997. ]);
  998. }
  999. });
  1000. // JSON 输出结果的安全校验/修复与观察(事务外执行,不改变 result 与 SSE 推送内容)
  1001. if (!empty($ctx['generate_task_id'])) {
  1002. $this->guardScriptGenerateJsonResult(
  1003. (int)$ctx['generate_task_id'],
  1004. (int)($ctx['script_id'] ?? 0),
  1005. (int)($ctx['uid'] ?? 0),
  1006. (string)$fullContent,
  1007. (string)($ctx['response_format'] ?? '')
  1008. );
  1009. }
  1010. }
  1011. } catch (\Throwable $e) {
  1012. if (!empty($ctx['generate_task_id'])) {
  1013. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  1014. 'status' => 'failed',
  1015. 'error_message' => $e->getMessage(),
  1016. 'completed_at' => date('Y-m-d H:i:s'),
  1017. 'updated_at' => date('Y-m-d H:i:s'),
  1018. ]);
  1019. }
  1020. yield [
  1021. 'type' => 'error',
  1022. 'message' => $e->getMessage(),
  1023. ];
  1024. }
  1025. }
  1026. /**
  1027. * 从模型输出中提取标准 JSON(剥离 markdown 代码块及前后说明文字)
  1028. *
  1029. * @param string $content
  1030. * @return string
  1031. */
  1032. private function extractJsonContent(string $content): string
  1033. {
  1034. $content = trim($content);
  1035. if ($content === '') {
  1036. return $content;
  1037. }
  1038. // 剥离 ```json ... ``` 代码块
  1039. if (preg_match('/```(?:json)?\s*(.*?)```/s', $content, $m)) {
  1040. $content = trim($m[1]);
  1041. }
  1042. // 提取第一个 { 到最后一个 } 之间的内容(去除前后说明文字)
  1043. $first = strpos($content, '{');
  1044. $last = strrpos($content, '}');
  1045. if ($first !== false && $last !== false && $last > $first) {
  1046. $content = substr($content, $first, $last - $first + 1);
  1047. }
  1048. // 校验是否为合法 JSON,非法则原样返回(不强行截断)
  1049. json_decode($content, true);
  1050. if (json_last_error() !== JSON_ERROR_NONE) {
  1051. return trim($content);
  1052. }
  1053. return $content;
  1054. }
  1055. /**
  1056. * 剧本资产生成结果的 JSON 安全校验/修复与观察
  1057. *
  1058. * 规则:
  1059. * - result 永远保留模型原文,本方法不修改 result;
  1060. * - 仅当原文非法 JSON 且 JsonSafeRepair 安全修复成功时,才把修复后的标准
  1061. * JSON 写入 mp_script_generate_tasks.json_result;
  1062. * - 每次生成结果都写一条 system_logs(channel=script_generate_json),
  1063. * 用于观察非法 JSON 的发生率与修复率。
  1064. *
  1065. * @param int $taskId 剧本资产生成任务 ID
  1066. * @param int $scriptId 剧本 ID
  1067. * @param int $uid 用户 ID
  1068. * @param string $raw 已落库的 result 原文
  1069. * @param string $responseFormat 请求的 response_format
  1070. * @return void
  1071. */
  1072. private function guardScriptGenerateJsonResult(int $taskId, int $scriptId, int $uid, string $raw, string $responseFormat): void
  1073. {
  1074. if ($taskId <= 0 || $raw === '') {
  1075. return;
  1076. }
  1077. // 仅对"要求 JSON 输出"或"内容明显是 JSON"的结果做校验,避免误伤普通文本结果
  1078. $trimmed = ltrim($raw);
  1079. $looksLikeJson = $responseFormat === 'json'
  1080. || (isset($trimmed[0]) && ($trimmed[0] === '{' || $trimmed[0] === '['));
  1081. if (!$looksLikeJson) {
  1082. return;
  1083. }
  1084. $repair = JsonSafeRepair::repair($raw);
  1085. $common = [
  1086. 'task_id' => $taskId,
  1087. 'script_id' => $scriptId,
  1088. 'uid' => $uid,
  1089. 'raw_length' => strlen($raw),
  1090. ];
  1091. if ($repair['ok'] && $repair['json'] !== $raw) {
  1092. // 原文非法但安全修复成功:修复版另存 json_result,result 仍保留原文
  1093. DB::table('mp_script_generate_tasks')->where('id', $taskId)->update([
  1094. 'json_result' => $repair['json'],
  1095. 'updated_at' => date('Y-m-d H:i:s'),
  1096. ]);
  1097. logDB('script_generate_json', 'warning', '生成JSON修复成功', $common + [
  1098. 'json_state' => 'repaired',
  1099. 'json_length' => strlen((string)$repair['json']),
  1100. 'removed_count' => count($repair['removed_positions']),
  1101. 'removed_positions' => $repair['removed_positions'],
  1102. ]);
  1103. return;
  1104. }
  1105. if ($repair['ok']) {
  1106. // 原文本身就是合法 JSON
  1107. logDB('script_generate_json', 'info', '生成JSON校验通过', $common + [
  1108. 'json_state' => 'valid',
  1109. ]);
  1110. return;
  1111. }
  1112. // 非法 JSON 且不在安全修复范围内:保留原文,只记录观察日志
  1113. logDB('script_generate_json', 'error', '生成JSON修复失败', $common + [
  1114. 'json_state' => 'repair_failed',
  1115. 'reason' => $repair['reason'],
  1116. ]);
  1117. }
  1118. /**
  1119. * 创建剧本资产生成异步任务(stream=1 + script_id 走异步任务模式)
  1120. *
  1121. * @param array $data 原请求参数
  1122. * @return int 任务ID
  1123. */
  1124. public function createScriptGenerateAsyncTask(array $data): int
  1125. {
  1126. $script_id = (int)getProp($data, 'script_id', 0);
  1127. if ($script_id <= 0) {
  1128. Utils::throwError('20003:缺少剧本ID');
  1129. }
  1130. $uid = (int)Site::getUid();
  1131. // 与同步逻辑一致:同一剧本存在生成中任务时直接拒绝
  1132. $runningTask = DB::table('mp_script_generate_tasks')
  1133. ->where('uid', $uid)
  1134. ->where('script_id', $script_id)
  1135. ->orderByDesc('id')
  1136. ->first();
  1137. if ($runningTask && in_array(getProp($runningTask, 'status'), ['pending', 'processing'])) {
  1138. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  1139. }
  1140. // 前置校验剧本存在且内容非空,避免创建无效任务
  1141. $script = DB::table('mp_scripts')
  1142. ->where('id', $script_id)
  1143. ->where('is_deleted', 0)
  1144. ->first();
  1145. if (!$script) {
  1146. Utils::throwError('20003:剧本不存在或已删除');
  1147. }
  1148. if (empty($script->content)) {
  1149. Utils::throwError('20003:剧本内容为空');
  1150. }
  1151. // newGenerateText 请求不含上传文件对象,images/image_urls 以字符串形式传入,可直接序列化
  1152. $paramsJson = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  1153. if ($paramsJson === false) {
  1154. Utils::throwError('20003:请求参数序列化失败');
  1155. }
  1156. $now = date('Y-m-d H:i:s');
  1157. return (int)DB::table('mp_script_generate_tasks')->insertGetId([
  1158. 'uid' => $uid,
  1159. 'script_id' => $script_id,
  1160. 'sequence' => (int)getProp($data, 'sequence', 0),
  1161. 'status' => 'pending',
  1162. 'prompt' => (string)getProp($data, 'prompt', ''),
  1163. 'request_params' => $paramsJson,
  1164. 'started_at' => $now,
  1165. 'created_at' => $now,
  1166. 'updated_at' => $now,
  1167. ]);
  1168. }
  1169. /**
  1170. * 供 SSE 轮询:查询任务状态与增量 chunks
  1171. *
  1172. * @param int $taskId
  1173. * @param int $uid 当前登录用户,防越权
  1174. * @param int $afterSeq 已推送的最大 seq
  1175. * @return array{found:bool, task:?object, chunks:array, status:?string, error_message:?string}
  1176. */
  1177. public function pollScriptGenerateTask(int $taskId, int $uid, int $afterSeq = -1): array
  1178. {
  1179. $task = DB::table('mp_script_generate_tasks')
  1180. ->where('id', $taskId)
  1181. ->where('uid', $uid)
  1182. ->first();
  1183. if (!$task) {
  1184. return ['found' => false, 'task' => null, 'chunks' => [], 'status' => null, 'error_message' => null];
  1185. }
  1186. $rows = DB::table('mp_script_generate_task_chunks')
  1187. ->where('task_id', $taskId)
  1188. ->where('seq', '>', $afterSeq)
  1189. ->orderBy('seq')
  1190. ->get();
  1191. $chunks = [];
  1192. foreach ($rows as $row) {
  1193. $payload = json_decode((string)$row->payload, true);
  1194. if (is_array($payload)) {
  1195. $chunks[] = $payload;
  1196. }
  1197. }
  1198. return [
  1199. 'found' => true,
  1200. 'task' => $task,
  1201. 'chunks' => $chunks,
  1202. 'status' => (string)$task->status,
  1203. 'error_message' => (string)($task->error_message ?? ''),
  1204. ];
  1205. }
  1206. /**
  1207. * 异步 worker 执行入口:抢占 pending 任务并流式请求大模型
  1208. *
  1209. * 由 text:generate:run 命令调用;worker 内完成 chunks 落库,模型结束后
  1210. * 由流式包装(wrapNewGenerateTextStream)完成 records/扣费/任务状态/json 修复收尾。
  1211. *
  1212. * @param int $taskId
  1213. * @return array{ok:bool, task_id:int, status:?string, seq:int, error:?string}
  1214. */
  1215. public function runScriptGenerateTaskAsync(int $taskId): array
  1216. {
  1217. // 原子抢占:只允许 pending -> processing,避免重复执行
  1218. $claimed = DB::table('mp_script_generate_tasks')
  1219. ->where('id', $taskId)
  1220. ->where('status', 'pending')
  1221. ->update([
  1222. 'status' => 'processing',
  1223. 'started_at' => date('Y-m-d H:i:s'),
  1224. 'updated_at' => date('Y-m-d H:i:s'),
  1225. ]);
  1226. if (!$claimed) {
  1227. return ['ok' => false, 'task_id' => $taskId, 'status' => null, 'seq' => 0, 'error' => '任务已被处理或状态异常'];
  1228. }
  1229. $task = DB::table('mp_script_generate_tasks')->where('id', $taskId)->first();
  1230. if (!$task) {
  1231. return ['ok' => false, 'task_id' => $taskId, 'status' => null, 'seq' => 0, 'error' => '任务不存在'];
  1232. }
  1233. $params = json_decode((string)getProp($task, 'request_params', ''), true);
  1234. if (!is_array($params)) {
  1235. DB::table('mp_script_generate_tasks')->where('id', $taskId)->update([
  1236. 'status' => 'failed',
  1237. 'error_message' => '任务请求参数缺失',
  1238. 'completed_at' => date('Y-m-d H:i:s'),
  1239. 'updated_at' => date('Y-m-d H:i:s'),
  1240. ]);
  1241. return ['ok' => false, 'task_id' => $taskId, 'status' => 'failed', 'seq' => 0, 'error' => '任务请求参数缺失'];
  1242. }
  1243. // 兼容旧参数未带 stream 的情况
  1244. $params['stream'] = 1;
  1245. $seq = 0;
  1246. try {
  1247. $generator = $this->newGenerateTextStream($params, $task);
  1248. foreach ($generator as $chunk) {
  1249. DB::table('mp_script_generate_task_chunks')->insert([
  1250. 'task_id' => $taskId,
  1251. 'seq' => $seq,
  1252. 'chunk_type' => (string)getProp($chunk, 'type', 'content'),
  1253. 'payload' => json_encode($chunk, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE),
  1254. 'created_at' => date('Y-m-d H:i:s'),
  1255. ]);
  1256. $seq++;
  1257. }
  1258. $finalStatus = (string)DB::table('mp_script_generate_tasks')->where('id', $taskId)->value('status');
  1259. return ['ok' => $finalStatus === 'success', 'task_id' => $taskId, 'status' => $finalStatus, 'seq' => $seq, 'error' => null];
  1260. } catch (\Throwable $e) {
  1261. // 兜底:正常流程中 wrap 会自行把任务置为 failed,这里防止未知异常导致任务卡死
  1262. DB::table('mp_script_generate_tasks')->where('id', $taskId)->update([
  1263. 'status' => 'failed',
  1264. 'error_message' => $e->getMessage(),
  1265. 'completed_at' => date('Y-m-d H:i:s'),
  1266. 'updated_at' => date('Y-m-d H:i:s'),
  1267. ]);
  1268. return ['ok' => false, 'task_id' => $taskId, 'status' => 'failed', 'seq' => $seq, 'error' => $e->getMessage()];
  1269. }
  1270. }
  1271. /**
  1272. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  1273. *
  1274. * @param array $data 请求参数
  1275. * @return array 返回结果数组
  1276. */
  1277. public function newGenerateText($data) {
  1278. // stream=1 时改为流式请求大模型(输出格式参考 generateText:yield type=content/reasoning/done)
  1279. if ((int)getProp($data, 'stream', 0) === 1) {
  1280. return $this->newGenerateTextStream($data);
  1281. }
  1282. // 获取请求参数
  1283. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  1284. $messages = getProp($data, 'messages', []);
  1285. $systemPrompt = getProp($data, 'system_prompt', '');
  1286. $prompt = getProp($data, 'prompt', '');
  1287. $images = getProp($data, 'images', []); // 支持多张图片
  1288. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  1289. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  1290. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  1291. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  1292. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  1293. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  1294. $generateTaskId = 0;
  1295. $uid = Site::getUid();
  1296. if ($script_id > 0) {
  1297. $existingTask = DB::table('mp_script_generate_tasks')
  1298. ->where('uid', $uid)
  1299. ->where('script_id', $script_id)
  1300. ->orderByDesc('id')
  1301. ->first();
  1302. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  1303. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  1304. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  1305. }
  1306. }
  1307. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  1308. $originalContent = '';
  1309. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  1310. $rawPrompt = $prompt; // 保存用户原始输入,供模板一致性判断
  1311. if ($script_id > 0) {
  1312. $script = DB::table('mp_scripts')
  1313. ->where('id', $script_id)
  1314. ->where('is_deleted', 0)
  1315. ->first();
  1316. if (!$script) {
  1317. Utils::throwError('20003:剧本不存在或已删除');
  1318. }
  1319. $originalContent = $script->content ?? '';
  1320. if (empty($originalContent)) {
  1321. Utils::throwError('20003:剧本内容为空');
  1322. }
  1323. $hasValidScript = true;
  1324. // 将剧本内容添加到提示词前面
  1325. if (!empty($originalContent)) {
  1326. if (!empty($prompt)) {
  1327. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  1328. } else {
  1329. $prompt = "原文内容:\n" . $originalContent;
  1330. }
  1331. }
  1332. }
  1333. // 新增: 如果提供了template_id,从数据库获取template_prompt
  1334. if ($templateId > 0) {
  1335. $template = DB::table('mp_prompt_templates')
  1336. ->where('id', $templateId)
  1337. ->where('is_deleted', 0)
  1338. ->first();
  1339. if (!$template) {
  1340. Utils::throwError('20003:模板不存在或已删除');
  1341. }
  1342. $templatePrompt = $template->template_prompt ?? '';
  1343. // 将模板提示词和用户输入的prompt组合
  1344. // 模板为准,用户输入作为补充要求
  1345. // 模板提示词与用户输入基本一致时只保留一个,避免重复提示词
  1346. // 剧本模式下当前 prompt 含原文内容需保留,其余情况以模板内容为准
  1347. if (!empty($templatePrompt)) {
  1348. $trimmedRawPrompt = trim((string)$rawPrompt);
  1349. if ($trimmedRawPrompt !== '' && mb_strtolower($trimmedRawPrompt) === mb_strtolower(trim($templatePrompt))) {
  1350. if (!$hasValidScript) {
  1351. $prompt = $templatePrompt;
  1352. }
  1353. } elseif (!empty($prompt)) {
  1354. $prompt = $templatePrompt . "\n\n" . $prompt;
  1355. } else {
  1356. $prompt = $templatePrompt;
  1357. }
  1358. }
  1359. }
  1360. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  1361. if (empty($messages)) {
  1362. $messages = [];
  1363. // 添加系统提示词
  1364. if (!empty($systemPrompt)) {
  1365. $messages[] = [
  1366. 'role' => 'system',
  1367. 'content' => $systemPrompt
  1368. ];
  1369. }
  1370. // 构建用户消息内容(支持文本+图片)
  1371. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1372. $userMessage = [
  1373. 'role' => 'user',
  1374. 'content' => []
  1375. ];
  1376. // 添加文本内容
  1377. if (!empty($prompt)) {
  1378. $userMessage['content'][] = [
  1379. 'type' => 'text',
  1380. 'text' => $prompt
  1381. ];
  1382. }
  1383. // 处理上传的图片文件
  1384. if (!empty($images)) {
  1385. if (!is_array($images)) {
  1386. $images = [$images];
  1387. }
  1388. foreach ($images as $image) {
  1389. $imageBase64 = $this->processImageToBase64($image);
  1390. if ($imageBase64) {
  1391. $userMessage['content'][] = [
  1392. 'type' => 'image_url',
  1393. 'image_url' => [
  1394. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  1395. ]
  1396. ];
  1397. }
  1398. }
  1399. }
  1400. // 处理图片URL
  1401. if (!empty($imageUrls)) {
  1402. if (!is_array($imageUrls)) {
  1403. $imageUrls = [$imageUrls];
  1404. }
  1405. foreach ($imageUrls as $url) {
  1406. if (!empty($url)) {
  1407. $userMessage['content'][] = [
  1408. 'type' => 'image_url',
  1409. 'image_url' => [
  1410. 'url' => $url
  1411. ]
  1412. ];
  1413. }
  1414. }
  1415. }
  1416. // 如果只有文本内容,简化为字符串格式
  1417. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  1418. $userMessage['content'] = $userMessage['content'][0]['text'];
  1419. }
  1420. $messages[] = $userMessage;
  1421. }
  1422. }
  1423. // 验证messages不为空
  1424. if (empty($messages)) {
  1425. Utils::throwError('20003:请提供有效的对话内容');
  1426. }
  1427. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1428. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1429. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1430. if ($model === 'deepseek-chat') {
  1431. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1432. $model = 'deepseek-v4-flash';
  1433. $thinkingMode = 'disabled';
  1434. } elseif ($model === 'deepseek-reasoner') {
  1435. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1436. $model = 'deepseek-v4-flash';
  1437. $thinkingMode = 'enabled';
  1438. }
  1439. // 构建请求参数(非流式)
  1440. $post_data = [
  1441. 'model' => $model,
  1442. 'messages' => $messages,
  1443. 'temperature' => getProp($data, 'temperature', 1),
  1444. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  1445. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  1446. 'thinking' => ['type' => $thinkingMode],
  1447. 'stream' => false // 非流式输出
  1448. ];
  1449. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1450. // 添加可选参数
  1451. if (isset($data['top_p'])) {
  1452. $post_data['top_p'] = $data['top_p'];
  1453. }
  1454. // 新增: 根据response_format设置响应格式
  1455. if ($responseFormat === 'json') {
  1456. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  1457. $hasJsonKeyword = false;
  1458. foreach ($post_data['messages'] as $message) {
  1459. if (isset($message['content'])) {
  1460. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  1461. if (stripos($content, 'json') !== false) {
  1462. $hasJsonKeyword = true;
  1463. break;
  1464. }
  1465. }
  1466. }
  1467. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  1468. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  1469. if (!$hasJsonKeyword) {
  1470. $lastMessageIndex = count($post_data['messages']) - 1;
  1471. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  1472. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  1473. // 如果content是字符串,直接追加
  1474. if (is_string($lastContent)) {
  1475. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  1476. }
  1477. // 如果content是数组(包含文本和图片),在文本部分追加
  1478. else if (is_array($lastContent)) {
  1479. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  1480. if ($contentPart['type'] === 'text') {
  1481. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  1482. break;
  1483. }
  1484. }
  1485. }
  1486. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  1487. }
  1488. }
  1489. // 设置response_format参数(所有支持的模型)
  1490. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1491. // DeepSeek模型
  1492. $post_data['response_format'] = ['type' => 'json_object'];
  1493. } else if (in_array($model, $this->gpt_text_models)) {
  1494. // GPT模型
  1495. $post_data['response_format'] = ['type' => 'json_object'];
  1496. } else if (in_array($model, $this->valid_text_models)) {
  1497. // 火山引擎模型
  1498. $post_data['response_format'] = ['type' => 'json_object'];
  1499. }
  1500. }
  1501. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  1502. if ($script_id > 0) {
  1503. $uid = Site::getUid();
  1504. // 创建新的生成任务
  1505. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  1506. 'uid' => $uid,
  1507. 'script_id' => $script_id,
  1508. 'sequence' => $sequence,
  1509. 'status' => 'processing',
  1510. 'prompt' => getProp($data, 'prompt', ''),
  1511. 'started_at' => date('Y-m-d H:i:s'),
  1512. 'created_at' => date('Y-m-d H:i:s'),
  1513. 'updated_at' => date('Y-m-d H:i:s')
  1514. ]);
  1515. }
  1516. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  1517. if ($hasValidScript) {
  1518. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  1519. }
  1520. // 统一分模型调用非流式实现
  1521. try {
  1522. $aiResult = null;
  1523. $result = $this->dispatchChatOnlyByModel($post_data);
  1524. dLog('deepseek')->info('newGenerateText模型调用完成', ['requested_model' => $model]);
  1525. $aiResult = [
  1526. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  1527. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  1528. 'usage' => $result['usage'] ?? [],
  1529. 'model' => $model,
  1530. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  1531. ];
  1532. } catch (\Exception $e) {
  1533. // 生成失败,更新任务状态
  1534. if ($generateTaskId) {
  1535. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1536. 'status' => 'failed',
  1537. 'error_message' => $e->getMessage(),
  1538. 'completed_at' => date('Y-m-d H:i:s'),
  1539. 'updated_at' => date('Y-m-d H:i:s')
  1540. ]);
  1541. }
  1542. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  1543. }
  1544. // 生成成功,更新任务状态
  1545. if ($generateTaskId && $aiResult) {
  1546. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1547. 'status' => 'success',
  1548. 'result' => getProp($aiResult, 'content', ''),
  1549. 'completed_at' => date('Y-m-d H:i:s'),
  1550. 'updated_at' => date('Y-m-d H:i:s')
  1551. ]);
  1552. $aiResult['generate_task_id'] = $generateTaskId;
  1553. // JSON 输出结果的安全校验/修复与观察(不改变 result)
  1554. $this->guardScriptGenerateJsonResult(
  1555. (int)$generateTaskId,
  1556. (int)$script_id,
  1557. (int)$uid,
  1558. (string)getProp($aiResult, 'content', ''),
  1559. (string)$responseFormat
  1560. );
  1561. }
  1562. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  1563. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  1564. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  1565. 'model' => $model,
  1566. 'script_id' => $script_id,
  1567. 'sequence' => $sequence,
  1568. 'source' => 'newGenerateText',
  1569. ]);
  1570. }
  1571. // 新增: 如果提供了script_id,保存对话记录
  1572. if ($script_id > 0 && $aiResult) {
  1573. try {
  1574. $uid = Site::getUid();
  1575. $now = now();
  1576. // 获取用户原始的prompt(不包含剧本内容)
  1577. $originalPrompt = getProp($data, 'prompt', '');
  1578. $recordsToInsert = [
  1579. [
  1580. 'uid' => $uid,
  1581. 'script_id' => $script_id,
  1582. 'sequence' => $sequence,
  1583. 'role' => 'user',
  1584. 'content' => $originalPrompt,
  1585. 'created_at' => $now,
  1586. 'updated_at' => $now,
  1587. ],
  1588. [
  1589. 'uid' => $uid,
  1590. 'script_id' => $script_id,
  1591. 'sequence' => $sequence,
  1592. 'role' => 'assistant',
  1593. 'content' => $aiResult['content'],
  1594. 'created_at' => $now,
  1595. 'updated_at' => $now,
  1596. ]
  1597. ];
  1598. DB::table('mp_script_records')->insert($recordsToInsert);
  1599. // 获取刚插入的记录ID(假设按插入顺序返回)
  1600. $insertedRecords = DB::table('mp_script_records')
  1601. ->where('uid', $uid)
  1602. ->where('script_id', $script_id)
  1603. ->where('sequence', $sequence)
  1604. ->orderBy('id', 'desc')
  1605. ->limit(2)
  1606. ->get()
  1607. ->map(function ($record) {
  1608. return [
  1609. 'rid' => $record->id,
  1610. 'script_id' => $record->script_id,
  1611. 'sequence' => $record->sequence,
  1612. 'role' => $record->role,
  1613. 'content' => $record->content,
  1614. 'created_at' => $record->created_at,
  1615. ];
  1616. })
  1617. ->reverse()
  1618. ->values()
  1619. ->toArray();
  1620. // 将记录信息添加到返回结果中
  1621. $aiResult['records'] = $insertedRecords;
  1622. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  1623. } catch (\Exception $e) {
  1624. // 记录错误但不影响主流程
  1625. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  1626. }
  1627. }
  1628. // 未提供 script_id 或保存失败时,也返回 records 数组(保持返回结构一致)
  1629. if (!isset($aiResult['records'])) {
  1630. $aiResult['records'] = [];
  1631. }
  1632. return $aiResult;
  1633. }
  1634. /**
  1635. * 通用 Gemini 文生文方法(支持流式和非流式)
  1636. *
  1637. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  1638. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  1639. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  1640. * system_prompt 系统提示词(可选)
  1641. * prompt 用户提示词(可选)
  1642. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  1643. * image_urls 图片/视频URL列表(可选,同上)
  1644. * temperature 温度(可选,默认 1)
  1645. * top_p 核采样(可选)
  1646. * max_tokens 最大输出 token(可选,默认 8192)
  1647. * response_format text/json(可选)
  1648. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  1649. * thinking_budget 思考预算(可选,默认 20)
  1650. * stream 是否流式(可选,默认 false)
  1651. *
  1652. * @param array $data 请求参数
  1653. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  1654. */
  1655. public function geminiGenerateText($data) {
  1656. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  1657. $isStream = (bool)getProp($data, 'stream', false);
  1658. if (!in_array($model, $this->gemini_text_models)) {
  1659. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  1660. }
  1661. $requestData = $this->buildGeminiRequestBody($data, $model);
  1662. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  1663. if ($isStream) {
  1664. // 流式返回生成器,成功后记录 token 使用明细(不扣积分)
  1665. return $this->wrapGenerateTextTokenRecord(
  1666. $this->geminiStreamResponse($requestData, $model),
  1667. $this->getCurrentUid(),
  1668. $model,
  1669. 'geminiGenerateText'
  1670. );
  1671. }
  1672. // 非流式:成功后记录 token 使用明细(不扣积分)
  1673. $result = $this->geminiChatOnly($requestData, $model);
  1674. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  1675. 'model' => $model,
  1676. 'source' => 'geminiGenerateText',
  1677. ], $model);
  1678. return $result;
  1679. }
  1680. /**
  1681. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  1682. */
  1683. private function geminiMediaMaxBytes() {
  1684. return 14 * 1024 * 1024;
  1685. }
  1686. /**
  1687. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  1688. */
  1689. private function buildGeminiRequestBody($data, $model) {
  1690. $messages = getProp($data, 'messages', []);
  1691. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  1692. if (empty($messages)) {
  1693. $systemPrompt = getProp($data, 'system_prompt', '');
  1694. $prompt = getProp($data, 'prompt', '');
  1695. $images = getProp($data, 'images', []);
  1696. $imageUrls = getProp($data, 'image_urls', []);
  1697. $messages = [];
  1698. if (!empty($systemPrompt)) {
  1699. $messages[] = [
  1700. 'role' => 'system',
  1701. 'content' => $systemPrompt
  1702. ];
  1703. }
  1704. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1705. $userMessage = ['role' => 'user', 'content' => []];
  1706. if (!empty($prompt)) {
  1707. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  1708. }
  1709. if (!empty($images)) {
  1710. if (!is_array($images)) {
  1711. $images = [$images];
  1712. }
  1713. foreach ($images as $image) {
  1714. $inlineData = $this->processMediaToInlineData($image);
  1715. if ($inlineData) {
  1716. $userMessage['content'][] = [
  1717. 'type' => 'image',
  1718. 'inline_data' => $inlineData
  1719. ];
  1720. }
  1721. }
  1722. }
  1723. if (!empty($imageUrls)) {
  1724. if (!is_array($imageUrls)) {
  1725. $imageUrls = [$imageUrls];
  1726. }
  1727. foreach ($imageUrls as $url) {
  1728. if (!empty($url)) {
  1729. $inlineData = $this->processMediaToInlineData($url);
  1730. if ($inlineData) {
  1731. $userMessage['content'][] = [
  1732. 'type' => 'image',
  1733. 'inline_data' => $inlineData
  1734. ];
  1735. }
  1736. }
  1737. }
  1738. }
  1739. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  1740. $userMessage['content'] = $userMessage['content'][0]['text'];
  1741. }
  1742. $messages[] = $userMessage;
  1743. }
  1744. }
  1745. if (empty($messages)) {
  1746. Utils::throwError('20003:请提供有效的对话内容');
  1747. }
  1748. // 转换为 Gemini contents 格式
  1749. $systemInstruction = '';
  1750. $contents = [];
  1751. foreach ($messages as $message) {
  1752. $role = getProp($message, 'role', 'user');
  1753. $content = getProp($message, 'content', '');
  1754. if ($role === 'system') {
  1755. if (is_array($content)) {
  1756. $systemInstruction = $this->extractGeminiTextFromParts($content);
  1757. } else {
  1758. $systemInstruction = (string)$content;
  1759. }
  1760. continue;
  1761. }
  1762. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  1763. $parts = [];
  1764. if (is_array($content)) {
  1765. foreach ($content as $part) {
  1766. $partType = getProp($part, 'type', 'text');
  1767. if ($partType === 'text') {
  1768. $text = (string)getProp($part, 'text', '');
  1769. if ($text !== '') {
  1770. $parts[] = ['text' => $text];
  1771. }
  1772. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  1773. if (in_array($partType, ['image_url', 'video_url'])) {
  1774. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  1775. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  1776. } elseif (isset($part['inline_data'])) {
  1777. // 已处理过的 inline_data 直接使用
  1778. $parts[] = ['inline_data' => $part['inline_data']];
  1779. continue;
  1780. } else {
  1781. $url = '';
  1782. }
  1783. $inlineData = $this->processMediaToInlineData($url);
  1784. if ($inlineData) {
  1785. $parts[] = ['inline_data' => $inlineData];
  1786. }
  1787. }
  1788. }
  1789. } else {
  1790. $text = (string)$content;
  1791. if ($text !== '') {
  1792. $parts[] = ['text' => $text];
  1793. }
  1794. }
  1795. if (!empty($parts)) {
  1796. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  1797. }
  1798. }
  1799. if (empty($contents)) {
  1800. Utils::throwError('20003:请提供有效的对话内容');
  1801. }
  1802. // 构建生成配置
  1803. $generationConfig = [];
  1804. if (getProp($data, 'temperature', null) !== null) {
  1805. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  1806. }
  1807. if (getProp($data, 'top_p', null) !== null) {
  1808. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  1809. }
  1810. if (getProp($data, 'frequency_penalty', null) !== null) {
  1811. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  1812. }
  1813. if (getProp($data, 'presence_penalty', null) !== null) {
  1814. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  1815. }
  1816. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  1817. if ($maxOutputTokens <= 0) {
  1818. $maxOutputTokens = 8192;
  1819. }
  1820. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  1821. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  1822. $maxOutputTokens = 32768;
  1823. }
  1824. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  1825. // response_format 映射:text -> text/plain,json -> application/json
  1826. $responseFormat = getProp($data, 'response_format', 'text');
  1827. if (is_array($responseFormat)) {
  1828. $responseFormat = getProp($responseFormat, 'type', 'text');
  1829. }
  1830. if (in_array($responseFormat, ['json', 'json_object'])) {
  1831. $generationConfig['responseMimeType'] = 'application/json';
  1832. } else {
  1833. $generationConfig['responseMimeType'] = 'text/plain';
  1834. }
  1835. $requestData = [
  1836. 'contents' => $contents,
  1837. 'generationConfig' => $generationConfig,
  1838. ];
  1839. if ($systemInstruction !== '') {
  1840. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  1841. }
  1842. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  1843. $thinkingMode = getProp($data, 'thinking', null);
  1844. if (is_array($thinkingMode)) {
  1845. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  1846. }
  1847. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  1848. if ($thinkingMode === null) {
  1849. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  1850. }
  1851. if ($thinkingMode === 'enabled') {
  1852. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  1853. if ($thinkingBudget <= 0) {
  1854. $thinkingBudget = 20;
  1855. }
  1856. $requestData['generationConfig']['thinkingConfig'] = [
  1857. 'thinkingBudget' => $thinkingBudget
  1858. ];
  1859. } elseif ($defaultThinking) {
  1860. // 该模型仅支持思考模式,传 0 会返回 400
  1861. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  1862. } else {
  1863. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  1864. }
  1865. return $requestData;
  1866. }
  1867. /**
  1868. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  1869. *
  1870. * 模型名 -> env 变量名映射:
  1871. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  1872. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  1873. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  1874. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  1875. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  1876. */
  1877. private function getGeminiApiKey($model) {
  1878. $map = [
  1879. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  1880. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  1881. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  1882. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  1883. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  1884. ];
  1885. if (isset($map[$model])) {
  1886. $key = env($map[$model]);
  1887. if (!empty($key)) {
  1888. return $key;
  1889. }
  1890. }
  1891. return env('GEMINI_API_KEY', '');
  1892. }
  1893. /**
  1894. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  1895. */
  1896. private function geminiChatOnly($requestData, $model) {
  1897. $apiKey = $this->getGeminiApiKey($model);
  1898. if (empty($apiKey)) {
  1899. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1900. }
  1901. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1902. if (isset($requestData['messages'])) {
  1903. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1904. }
  1905. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1906. . '/models/' . $model . ':generateContent';
  1907. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1908. $headers = [
  1909. 'Authorization' => 'Bearer ' . $apiKey,
  1910. 'Content-Type' => 'application/json'
  1911. ];
  1912. $maxRetries = $this->gptRetryTimes();
  1913. $interval = $this->gptRetryInterval();
  1914. $attempt = 0;
  1915. while (true) {
  1916. try {
  1917. $response = $client->post($url, [
  1918. 'json' => $requestData,
  1919. 'headers' => $headers
  1920. ]);
  1921. $responseArr = json_decode($response->getBody()->getContents(), true);
  1922. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  1923. $fullContent = $this->extractGeminiContent($responseArr);
  1924. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  1925. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  1926. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  1927. ? $responseArr['candidates'][0]['finishReason']
  1928. : '';
  1929. return [
  1930. 'fullContent' => $fullContent,
  1931. 'fullReasoningContent' => $fullReasoningContent,
  1932. 'usage' => $usage,
  1933. 'finish_reason' => $finishReason
  1934. ];
  1935. } catch (\Exception $e) {
  1936. $retryable = true;
  1937. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1938. $status = $e->getResponse()->getStatusCode();
  1939. $retryable = $status >= 500 || $status == 429;
  1940. }
  1941. if (!$retryable || $attempt >= $maxRetries) {
  1942. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  1943. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  1944. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  1945. }
  1946. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  1947. 'retry' => $attempt + 1,
  1948. 'max_retries' => $maxRetries,
  1949. 'error' => $e->getMessage()
  1950. ]);
  1951. sleep($interval);
  1952. $attempt++;
  1953. }
  1954. }
  1955. }
  1956. /**
  1957. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  1958. */
  1959. private function geminiStreamResponse($requestData, $model) {
  1960. $apiKey = $this->getGeminiApiKey($model);
  1961. if (empty($apiKey)) {
  1962. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1963. }
  1964. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1965. if (isset($requestData['messages'])) {
  1966. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1967. }
  1968. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1969. . '/models/' . $model . ':generateContent?alt=sse';
  1970. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1971. $headers = [
  1972. 'Authorization' => 'Bearer ' . $apiKey,
  1973. 'Content-Type' => 'application/json'
  1974. ];
  1975. try {
  1976. $response = $client->post($url, [
  1977. 'json' => $requestData,
  1978. 'headers' => $headers,
  1979. 'stream' => true
  1980. ]);
  1981. $body = $response->getBody();
  1982. $fullContent = '';
  1983. $fullReasoningContent = '';
  1984. $usage = [];
  1985. $buffer = '';
  1986. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1987. while (!$body->eof()) {
  1988. $chunk = $body->read(1024);
  1989. $buffer .= $chunk;
  1990. $lines = explode("\n", $buffer);
  1991. $buffer = array_pop($lines);
  1992. foreach ($lines as $line) {
  1993. $line = trim($line);
  1994. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1995. continue;
  1996. }
  1997. $data = substr($line, 6);
  1998. if ($data === '[DONE]') {
  1999. break 2;
  2000. }
  2001. try {
  2002. $json = json_decode($data, true);
  2003. if (json_last_error() !== JSON_ERROR_NONE) {
  2004. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2005. continue;
  2006. }
  2007. // 思考内容(thoughts)
  2008. $thoughts = $this->extractGeminiThoughts($json);
  2009. if ($thoughts !== '') {
  2010. $fullReasoningContent .= $thoughts;
  2011. yield [
  2012. 'type' => 'reasoning',
  2013. 'content' => $thoughts,
  2014. 'full_reasoning' => $fullReasoningContent
  2015. ];
  2016. }
  2017. // 回答内容
  2018. $partText = $this->extractGeminiContent($json);
  2019. if ($partText !== '') {
  2020. $fullContent .= $partText;
  2021. yield [
  2022. 'type' => 'content',
  2023. 'content' => $partText,
  2024. ];
  2025. }
  2026. // 使用统计
  2027. if (isset($json['usageMetadata'])) {
  2028. $usage = $json['usageMetadata'];
  2029. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  2030. }
  2031. } catch (\Exception $e) {
  2032. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2033. continue;
  2034. }
  2035. }
  2036. }
  2037. dLog('deepseek')->info('Gemini流式读取完成', [
  2038. 'content_length' => strlen($fullContent),
  2039. 'reasoning_length' => strlen($fullReasoningContent)
  2040. ]);
  2041. yield [
  2042. 'type' => 'done',
  2043. 'full_content' => $fullContent,
  2044. 'full_reasoning' => $fullReasoningContent,
  2045. 'usage' => $usage
  2046. ];
  2047. } catch (\Exception $e) {
  2048. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  2049. yield [
  2050. 'type' => 'error',
  2051. 'msg' => $e->getMessage(),
  2052. 'code' => $e->getCode()
  2053. ];
  2054. }
  2055. }
  2056. /**
  2057. * 从 Gemini 响应中提取回答文本
  2058. */
  2059. private function extractGeminiContent($responseArr) {
  2060. $text = '';
  2061. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  2062. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  2063. if (isset($part['text'])) {
  2064. $text .= $part['text'];
  2065. }
  2066. }
  2067. }
  2068. return $text;
  2069. }
  2070. /**
  2071. * 从 Gemini 响应中提取思考内容
  2072. */
  2073. private function extractGeminiReasoningContent($responseArr) {
  2074. $reasoning = '';
  2075. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  2076. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  2077. if (isset($thought['text'])) {
  2078. $reasoning .= $thought['text'];
  2079. }
  2080. }
  2081. }
  2082. return $reasoning;
  2083. }
  2084. /**
  2085. * 从 Gemini 流式响应中提取本次增量思考内容
  2086. */
  2087. private function extractGeminiThoughts($responseArr) {
  2088. $thoughts = '';
  2089. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  2090. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  2091. if (isset($thought['text'])) {
  2092. $thoughts .= $thought['text'];
  2093. }
  2094. }
  2095. }
  2096. return $thoughts;
  2097. }
  2098. /**
  2099. * 提取消息数组中的纯文本
  2100. */
  2101. private function extractGeminiTextFromParts($parts) {
  2102. $text = '';
  2103. if (is_array($parts)) {
  2104. foreach ($parts as $part) {
  2105. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  2106. $text .= (string)getProp($part, 'text', '');
  2107. }
  2108. }
  2109. }
  2110. return $text;
  2111. }
  2112. /**
  2113. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  2114. *
  2115. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  2116. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  2117. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  2118. *
  2119. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  2120. * @return array|null ['mime_type' => string, 'data' => string]
  2121. */
  2122. private function processMediaToInlineData($media) {
  2123. if (empty($media)) {
  2124. return null;
  2125. }
  2126. $localPath = null;
  2127. $isTempFile = false;
  2128. try {
  2129. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  2130. if (is_string($media) && strpos($media, 'data:') === 0) {
  2131. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  2132. return [
  2133. 'mime_type' => $matches[1],
  2134. 'data' => $matches[2]
  2135. ];
  2136. }
  2137. return null;
  2138. }
  2139. // 2. 获取本地文件路径
  2140. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  2141. $localPath = $this->downloadMediaToTemp($media);
  2142. $isTempFile = true;
  2143. } elseif (is_string($media)) {
  2144. $localPath = $media;
  2145. } else {
  2146. // Laravel UploadedFile 对象
  2147. $localPath = $media->getRealPath();
  2148. }
  2149. if (!$localPath || !file_exists($localPath)) {
  2150. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  2151. return null;
  2152. }
  2153. $fileSize = filesize($localPath);
  2154. $maxBytes = $this->geminiMediaMaxBytes();
  2155. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  2156. $mimeType = $this->detectMediaMime($localPath);
  2157. $isVideo = strpos($mimeType, 'video/') === 0;
  2158. $needCompress = $fileSize > $maxBytes;
  2159. $duration = 0;
  2160. if ($isVideo) {
  2161. $duration = $this->getMediaDuration($localPath);
  2162. if ($duration > 300) {
  2163. $needCompress = true;
  2164. }
  2165. }
  2166. $finalPath = $localPath;
  2167. $compressedPath = null;
  2168. if ($needCompress && $this->ffmpegAvailable()) {
  2169. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  2170. if ($compressed && file_exists($compressed)) {
  2171. $compressedPath = $compressed;
  2172. if (filesize($compressed) < $fileSize || $isVideo) {
  2173. $finalPath = $compressed;
  2174. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  2175. } else {
  2176. @unlink($compressed);
  2177. $compressedPath = null;
  2178. }
  2179. }
  2180. }
  2181. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  2182. $finalSize = filesize($finalPath);
  2183. if ($finalSize > $maxBytes) {
  2184. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  2185. 'path' => $localPath,
  2186. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  2187. 'limit_mb' => 14
  2188. ]);
  2189. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  2190. }
  2191. // 兜底校验:视频时长超过5分钟且未能压缩成功
  2192. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  2193. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  2194. }
  2195. $data = base64_encode(file_get_contents($finalPath));
  2196. return [
  2197. 'mime_type' => $mimeType,
  2198. 'data' => $data
  2199. ];
  2200. } catch (\App\Exceptions\ApiException $e) {
  2201. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  2202. throw $e;
  2203. } catch (\Exception $e) {
  2204. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  2205. return null;
  2206. } finally {
  2207. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  2208. @unlink($compressedPath);
  2209. }
  2210. if ($isTempFile && $localPath && file_exists($localPath)) {
  2211. @unlink($localPath);
  2212. }
  2213. }
  2214. }
  2215. /**
  2216. * 下载远程多媒体到临时目录
  2217. *
  2218. * @return string|null 本地临时文件路径
  2219. */
  2220. private function downloadMediaToTemp($url) {
  2221. try {
  2222. $tempDir = storage_path('app/temp/gemini');
  2223. if (!is_dir($tempDir)) {
  2224. mkdir($tempDir, 0775, true);
  2225. }
  2226. $extension = 'tmp';
  2227. $pathInfo = parse_url($url, PHP_URL_PATH);
  2228. if ($pathInfo) {
  2229. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  2230. if ($ext && strlen($ext) <= 10) {
  2231. $extension = strtolower($ext);
  2232. }
  2233. }
  2234. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  2235. $client = new Client(['timeout' => 300, 'verify' => false]);
  2236. $response = $client->get($url, ['sink' => $tmpFile]);
  2237. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  2238. @unlink($tmpFile);
  2239. return null;
  2240. }
  2241. return $tmpFile;
  2242. } catch (\Exception $e) {
  2243. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  2244. return null;
  2245. }
  2246. }
  2247. /**
  2248. * 检测多媒体文件 MIME 类型
  2249. */
  2250. private function detectMediaMime($filePath) {
  2251. $imageInfo = @getimagesize($filePath);
  2252. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  2253. return $imageInfo['mime'];
  2254. }
  2255. // 视频按扩展名粗略判断
  2256. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  2257. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  2258. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  2259. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  2260. if (isset($videoExts[$ext])) {
  2261. return $videoExts[$ext];
  2262. }
  2263. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  2264. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  2265. if (isset($imageExts[$ext])) {
  2266. return $imageExts[$ext];
  2267. }
  2268. return 'application/octet-stream';
  2269. }
  2270. /**
  2271. * 获取多媒体时长(秒),非视频或失败返回 0
  2272. */
  2273. private function getMediaDuration($filePath) {
  2274. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  2275. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  2276. $output = trim((string)shell_exec($cmd));
  2277. $duration = (float)$output;
  2278. return $duration > 0 ? $duration : 0;
  2279. }
  2280. /**
  2281. * 检查 ffmpeg 是否可用
  2282. */
  2283. private function ffmpegAvailable() {
  2284. static $available = null;
  2285. if ($available !== null) {
  2286. return $available;
  2287. }
  2288. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2289. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  2290. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  2291. $available = false;
  2292. return $available;
  2293. }
  2294. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  2295. $output = shell_exec($cmd);
  2296. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  2297. return $available;
  2298. }
  2299. /**
  2300. * 使用 ffmpeg 压缩多媒体文件
  2301. *
  2302. * @param string $inputFile 输入文件路径
  2303. * @param bool $isVideo 是否为视频
  2304. * @param float $duration 视频时长(秒),非视频传 0
  2305. * @return string|null 压缩后的文件路径,失败返回 null
  2306. */
  2307. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  2308. try {
  2309. $tempDir = storage_path('app/temp/gemini');
  2310. if (!is_dir($tempDir)) {
  2311. mkdir($tempDir, 0775, true);
  2312. }
  2313. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2314. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  2315. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  2316. if ($isVideo) {
  2317. // 视频:时长超过5分钟则加速压缩到5分钟以内
  2318. $speedFactor = 1.0;
  2319. if ($duration > 300) {
  2320. $speedFactor = $duration / 300;
  2321. }
  2322. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  2323. $finalDuration = $duration / max(1.0, $speedFactor);
  2324. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  2325. $targetBitrate = max(300, min(6000, $targetBitrate));
  2326. $filters = [];
  2327. $filters[] = 'scale=min(1280,iw):-2';
  2328. $filters[] = 'fps=24';
  2329. if ($speedFactor > 1.0) {
  2330. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  2331. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  2332. $fullCount = (int)ceil($speedFactor / 2.0);
  2333. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2334. if ($lastTempo < 0.5) {
  2335. $fullCount++;
  2336. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2337. }
  2338. for ($i = 0; $i < $fullCount; $i++) {
  2339. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  2340. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  2341. }
  2342. }
  2343. $filterStr = implode(',', $filters);
  2344. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  2345. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  2346. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  2347. } else {
  2348. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  2349. $imageInfo = @getimagesize($inputFile);
  2350. $scaleW = 2048;
  2351. $scaleH = 2048;
  2352. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  2353. if ($imageInfo[0] >= $imageInfo[1]) {
  2354. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  2355. $scaleW = 2048;
  2356. } else {
  2357. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  2358. $scaleH = 2048;
  2359. }
  2360. }
  2361. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  2362. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  2363. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  2364. }
  2365. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  2366. $output = shell_exec($cmd);
  2367. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  2368. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  2369. 'input' => $inputFile,
  2370. 'output' => $output
  2371. ]);
  2372. @unlink($outputFile);
  2373. return null;
  2374. }
  2375. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  2376. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  2377. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  2378. ]);
  2379. return $outputFile;
  2380. } catch (\Exception $e) {
  2381. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  2382. return null;
  2383. }
  2384. }
  2385. /**
  2386. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  2387. *
  2388. * @param array $data
  2389. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  2390. */
  2391. public function getScriptGenerateTasks($data) {
  2392. $uid = Site::getUid();
  2393. return DB::table('mp_script_generate_tasks as t')
  2394. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  2395. ->where('t.uid', $uid)
  2396. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  2397. ->orderByDesc('t.id')
  2398. ->paginate(15);
  2399. }
  2400. public function saveScriptChatHistory($data) {
  2401. $uid = Site::getUid();
  2402. $rid = getProp($data, 'rid');
  2403. $script_id = getProp($data, 'script_id');
  2404. $sequence = getProp($data, 'sequence', 0);
  2405. $content = getProp($data, 'content');
  2406. if (!$rid) {
  2407. Utils::throwError('20003:请选择对话记录ID');
  2408. }
  2409. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  2410. if (!$record) {
  2411. Utils::throwError('20003:对话记录不存在');
  2412. }
  2413. if (!$script_id) {
  2414. Utils::throwError('20003:请选择剧本');
  2415. }
  2416. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  2417. if (!$script) {
  2418. Utils::throwError('20003:剧本不存在');
  2419. }
  2420. // 批量插入数据
  2421. return DB::table('mp_script_records')->where('id', $rid)->update([
  2422. 'content' => $content,
  2423. 'updated_at' => date('Y-m-d H:i:s')
  2424. ]);
  2425. }
  2426. /**
  2427. * 获取剧本的历史对话记录
  2428. *
  2429. * @param array $data 请求参数
  2430. * @return array 返回历史记录数组
  2431. */
  2432. public function getScriptChatHistory($data) {
  2433. $uid = Site::getUid();
  2434. $script_id = getProp($data, 'script_id');
  2435. $rid = getProp($data, 'rid');
  2436. $sequence = getProp($data, 'sequence', null);
  2437. if (!$script_id) {
  2438. Utils::throwError('20003:请提供剧本ID');
  2439. }
  2440. // 验证剧本是否存在
  2441. $script = DB::table('mp_scripts')
  2442. ->where('id', $script_id)
  2443. ->where('is_deleted', 0)
  2444. ->first();
  2445. if (!$script) {
  2446. Utils::throwError('20003:剧本不存在');
  2447. }
  2448. // 构建查询
  2449. $query = DB::table('mp_script_records')
  2450. ->where('script_id', $script_id);
  2451. // ->where('uid', $uid);
  2452. // 如果提供了 sequence,则过滤指定剧集
  2453. if ($sequence !== null) {
  2454. $query->where('sequence', $sequence);
  2455. }
  2456. // 记录ID筛选
  2457. if ($rid) {
  2458. $query->where('id', $rid);
  2459. }
  2460. // 查询记录并按 id 正序排序
  2461. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  2462. ->orderBy('created_at', 'asc')
  2463. ->orderBy('id', 'asc')
  2464. ->get()
  2465. ->map(function ($record) {
  2466. return [
  2467. 'rid' => $record->id,
  2468. 'script_id' => $record->script_id,
  2469. 'sequence' => $record->sequence,
  2470. 'role' => $record->role,
  2471. 'content' => $record->content,
  2472. 'products' => $record->products ? json_decode($record->products) : [],
  2473. 'created_at' => $record->created_at,
  2474. ];
  2475. })
  2476. ->toArray();
  2477. return $records;
  2478. }
  2479. /**
  2480. * 处理图片转换为base64
  2481. *
  2482. * @param mixed $image 图片文件对象或文件路径
  2483. * @return string|null base64编码的图片数据
  2484. */
  2485. private function processImageToBase64($image) {
  2486. try {
  2487. // 获取文件路径
  2488. if (is_string($image)) {
  2489. $filePath = $image;
  2490. } else {
  2491. // Laravel UploadedFile 对象
  2492. $filePath = $image->getRealPath();
  2493. }
  2494. if (!file_exists($filePath)) {
  2495. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  2496. return null;
  2497. }
  2498. // 验证是否为图片文件
  2499. $imageInfo = @getimagesize($filePath);
  2500. if ($imageInfo === false) {
  2501. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  2502. return null;
  2503. }
  2504. // 读取图片并转换为base64
  2505. $imageData = file_get_contents($filePath);
  2506. $base64Image = base64_encode($imageData);
  2507. dLog('deepseek')->info('图片转换成功', [
  2508. 'size' => strlen($imageData),
  2509. 'type' => $imageInfo['mime']
  2510. ]);
  2511. return $base64Image;
  2512. } catch (\Exception $e) {
  2513. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  2514. return null;
  2515. }
  2516. }
  2517. private function getArtStylePromptMappings($art_style='')
  2518. {
  2519. // 优先从画风表读取(入库后以表数据为准,保持原返回结构:['画风名' => ['aliases' => [...], 'prompt' => "..."]]
  2520. $dbRows = DB::table('mp_art_styles')
  2521. ->where('is_deleted', 0)
  2522. ->orderBy('id')
  2523. ->get(['art_style', 'aliases', 'prompt']);
  2524. if ($dbRows->isNotEmpty()) {
  2525. $arr = [];
  2526. foreach ($dbRows as $row) {
  2527. $arr[$row->art_style] = [
  2528. 'aliases' => is_string($row->aliases) ? json_decode($row->aliases, true) : [],
  2529. 'prompt' => (string)$row->prompt,
  2530. ];
  2531. }
  2532. if ($art_style) {
  2533. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2534. }
  2535. return $arr;
  2536. }
  2537. $arr = [
  2538. '唯美真人风格' => [
  2539. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2540. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  2541. ],
  2542. '真人古风风格' => [
  2543. 'aliases' => ['真人古风风格', '真人古风'],
  2544. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  2545. ],
  2546. '日系动漫风格' => [
  2547. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2548. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  2549. ],
  2550. '国漫风格' => [
  2551. 'aliases' => ['国漫风格', '国漫'],
  2552. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  2553. ],
  2554. 'Q版卡通风格' => [
  2555. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2556. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  2557. ],
  2558. '简约扁平风格' => [
  2559. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2560. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  2561. ],
  2562. '武侠风格' => [
  2563. 'aliases' => ['武侠风格', '武侠'],
  2564. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  2565. ],
  2566. '古风仙侠风格' => [
  2567. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2568. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  2569. ],
  2570. '新中式水墨风格' => [
  2571. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2572. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  2573. ],
  2574. '写实插画风格' => [
  2575. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2576. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  2577. ],
  2578. '3D卡通风格' => [
  2579. 'aliases' => ['3D卡通风格', '3D卡通'],
  2580. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  2581. ],
  2582. '条漫风格' => [
  2583. 'aliases' => ['条漫风格', '条漫'],
  2584. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  2585. ],
  2586. '赛博朋克风格' => [
  2587. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2588. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  2589. ],
  2590. '暗黑悬疑风格' => [
  2591. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2592. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  2593. ],
  2594. '治愈清新风格' => [
  2595. 'aliases' => ['治愈清新风格', '治愈清新'],
  2596. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  2597. ],
  2598. '3D真人风格' => [
  2599. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  2600. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  2601. ],
  2602. ];
  2603. if($art_style) {
  2604. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2605. }
  2606. return $arr;
  2607. $arr = [
  2608. '唯美真人风格' => [
  2609. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2610. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  2611. 2. 色彩色调
  2612. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  2613. 3. 画质精度
  2614. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  2615. 4. 画面观感
  2616. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  2617. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  2618. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  2619. ],
  2620. '真人古风风格' => [
  2621. 'aliases' => ['真人古风风格', '真人古风'],
  2622. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  2623. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  2624. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  2625. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  2626. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  2627. ],
  2628. '日系动漫风格' => [
  2629. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2630. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  2631. 正向提示词(中文)
  2632. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  2633. 必须遵守规则
  2634. • 全程保持日系动漫风格,不混入其他画风
  2635. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  2636. • 画面适配所选画面比例,构图居中,主体突出
  2637. • 线条干净、色彩统一,不杂乱、不突兀
  2638. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  2639. ],
  2640. '国漫风格' => [
  2641. 'aliases' => ['国漫风格', '国漫'],
  2642. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  2643. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  2644. 必须遵守规则
  2645. • 严格保持国漫画风,不串风格、不混画风
  2646. • 角色形象统一,不随意改变五官、身材、服饰
  2647. • 画面构图稳定,适合漫剧叙事展示
  2648. • 色调统一,不出现脏色、杂色
  2649. 禁止/避免词汇
  2650. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  2651. ],
  2652. 'Q版卡通风格' => [
  2653. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2654. 'prompt' => "风格说明
  2655. 头大身小,造型可爱圆润,简约干净
  2656. 正向提示词(中文)
  2657. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  2658. 必须遵守规则
  2659. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  2660. • 角色造型统一,表情可爱,不诡异
  2661. • 画面简洁清爽,无多余复杂元素
  2662. • 色彩明亮柔和,不刺眼
  2663. 禁止/避免词汇
  2664. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  2665. ],
  2666. '简约扁平风格' => [
  2667. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2668. 'prompt' => "风格说明
  2669. 色块简洁、无复杂渐变,现代极简风
  2670. 正向提示词(中文)
  2671. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  2672. 必须遵守规则
  2673. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  2674. • 构图简洁,主体突出,无多余装饰
  2675. • 色彩统一、干净,不杂乱
  2676. 禁止/避免词汇
  2677. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  2678. ],
  2679. '武侠风格' => [
  2680. 'aliases' => ['武侠风格', '武侠'],
  2681. 'prompt' => "风格说明
  2682. 江湖气息,线条硬朗,动作感强
  2683. 正向提示词(中文)
  2684. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  2685. 必须遵守规则
  2686. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  2687. • 角色形象、服饰、身材比例统一
  2688. • 画面动作自然,不扭曲、不畸形
  2689. 禁止/避免词汇
  2690. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  2691. ],
  2692. '古风仙侠风格' => [
  2693. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2694. 'prompt' => "风格说明
  2695. 飘逸汉服、云雾仙气、唯美空灵
  2696. 正向提示词(中文)
  2697. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  2698. 必须遵守规则
  2699. • 保持古风仙侠统一画风,不混入现代、科幻元素
  2700. • 角色服饰、发型、形象前后一致
  2701. • 场景仙气飘逸,色调清雅统一
  2702. • 画面唯美柔和,不阴暗、不诡异
  2703. 禁止/避免词汇
  2704. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  2705. ],
  2706. '新中式水墨风格' => [
  2707. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2708. 'prompt' => "风格说明
  2709. 淡墨渲染,毛笔笔触,留白意境
  2710. 正向提示词(中文)
  2711. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  2712. 必须遵守规则
  2713. • 严格保持水墨质感,不混入厚涂、写实、卡通
  2714. • 色调淡雅统一,不浓艳杂乱
  2715. • 画面干净有意境,不堆砌元素
  2716. 禁止/避免词汇
  2717. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  2718. ],
  2719. '写实插画风格' => [
  2720. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2721. 'prompt' => "风格说明
  2722. 接近真人比例,光影真实,质感细腻
  2723. 正向提示词(中文)
  2724. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  2725. 必须遵守规则
  2726. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  2727. • 角色五官、身材、服饰高度统一
  2728. • 画面清晰、光影自然、不扭曲
  2729. 禁止/避免词汇
  2730. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  2731. ],
  2732. '3D卡通风格' => [
  2733. 'aliases' => ['3D卡通风格', '3D卡通'],
  2734. 'prompt' => "风格说明
  2735. 3D建模质感,柔和渲染,圆润可爱
  2736. 正向提示词(中文)
  2737. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  2738. 必须遵守规则
  2739. • 保持3D卡通统一质感,不出现2D杂乱线条
  2740. • 角色模型、比例、形象前后一致
  2741. • 画面干净,不模糊、不穿模
  2742. 禁止/避免词汇
  2743. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  2744. ],
  2745. '条漫风格' => [
  2746. 'aliases' => ['条漫风格', '条漫'],
  2747. 'prompt' => "风格说明
  2748. 纵向分镜,上下滑动阅读,轻量化
  2749. 正向提示词(中文)
  2750. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  2751. 必须遵守规则
  2752. • 保持条漫纵向阅读逻辑,构图简洁
  2753. • 画风统一,不混写实、3D、水墨
  2754. • 画面干净,不杂乱
  2755. 禁止/避免词汇
  2756. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  2757. ],
  2758. '赛博朋克风格' => [
  2759. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2760. 'prompt' => "风格说明
  2761. 霓虹灯光、未来都市、暗色调、科技机械
  2762. 正向提示词(中文)
  2763. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  2764. 必须遵守规则
  2765. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  2766. • 色调以暗调+霓虹为主,色彩统一
  2767. • 画面科技感强,不杂乱
  2768. 禁止/避免词汇
  2769. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  2770. ],
  2771. '暗黑悬疑风格' => [
  2772. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2773. 'prompt' => "风格说明
  2774. 低饱和、冷色调、阴影重、神秘压抑
  2775. 正向提示词(中文)
  2776. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  2777. 必须遵守规则
  2778. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  2779. • 画面氛围压抑神秘,但不低俗、不血腥
  2780. • 角色形象统一,不崩坏
  2781. 禁止/避免词汇
  2782. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  2783. ],
  2784. '治愈清新风格' => [
  2785. 'aliases' => ['治愈清新风格', '治愈清新'],
  2786. 'prompt' => "风格说明
  2787. 马卡龙色系、柔光、温暖干净
  2788. 正向提示词(中文)
  2789. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  2790. 必须遵守规则
  2791. • 保持治愈清新统一色调,不阴暗、不诡异
  2792. • 画面柔和干净,无杂乱元素
  2793. • 角色形象柔和可爱,不狰狞
  2794. 禁止/避免词汇
  2795. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  2796. ],
  2797. ];
  2798. return $arr;
  2799. }
  2800. public function getArtStylePromptByInput($inputArtStyle): string
  2801. {
  2802. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  2803. if ($normalizedInput === '') {
  2804. return '';
  2805. }
  2806. return $this->getArtStylePromptMappings($normalizedInput);
  2807. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  2808. // foreach ($mapping['aliases'] as $alias) {
  2809. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  2810. // if ($normalizedAlias === '') {
  2811. // continue;
  2812. // }
  2813. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  2814. // return $mapping['prompt'];
  2815. // }
  2816. // }
  2817. // }
  2818. return '';
  2819. }
  2820. public function getArtStyleShortPromptByInput($inputArtStyle) {
  2821. // 优先从画风表读取;character_prefix/scene_prefix 缺失时用通用 prompt 兜底,均缺失则返回空数组
  2822. $row = DB::table('mp_art_styles')
  2823. ->where('art_style', $inputArtStyle)
  2824. ->where('is_deleted', 0)
  2825. ->first(['character_prefix', 'scene_prefix', 'prompt']);
  2826. if ($row) {
  2827. $prompt = (string)$row->prompt;
  2828. $result = [
  2829. 'character_prefix' => (string)$row->character_prefix !== '' ? (string)$row->character_prefix : $prompt,
  2830. 'scene_prefix' => (string)$row->scene_prefix !== '' ? (string)$row->scene_prefix : $prompt,
  2831. ];
  2832. // 前缀与通用提示词均不存在时返回空数组
  2833. if ($result['character_prefix'] === '' && $result['scene_prefix'] === '') {
  2834. return [];
  2835. }
  2836. return $result;
  2837. }
  2838. $stylePrefixes = [
  2839. '唯美真人风格' => [
  2840. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  2841. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强',
  2842. 'prompt' => '唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质'
  2843. ],
  2844. '真人古风风格' => [
  2845. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  2846. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清',
  2847. 'prompt' => '真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清'
  2848. ],
  2849. '日系动漫风格' => [
  2850. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  2851. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强',
  2852. 'prompt' => '日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影'
  2853. ],
  2854. '国漫风格' => [
  2855. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  2856. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染',
  2857. 'prompt' => '国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节'
  2858. ],
  2859. 'Q版卡通风格' => [
  2860. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  2861. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感',
  2862. 'prompt' => 'Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画'
  2863. ],
  2864. '简约扁平风格' => [
  2865. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  2866. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽',
  2867. 'prompt' => '简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽'
  2868. ],
  2869. '武侠风格' => [
  2870. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  2871. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学',
  2872. 'prompt' => '武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制'
  2873. ],
  2874. '古风仙侠风格' => [
  2875. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  2876. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学',
  2877. 'prompt' => '古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面'
  2878. ],
  2879. '新中式水墨风格' => [
  2880. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  2881. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景',
  2882. 'prompt' => '新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感'
  2883. ],
  2884. '写实插画风格' => [
  2885. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  2886. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图',
  2887. 'prompt' => '写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染'
  2888. ],
  2889. '3D卡通风格' => [
  2890. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  2891. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染',
  2892. 'prompt' => '3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富'
  2893. ],
  2894. '条漫风格' => [
  2895. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  2896. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感',
  2897. 'prompt' => '条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制'
  2898. ],
  2899. '赛博朋克风格' => [
  2900. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  2901. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影',
  2902. 'prompt' => '赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染'
  2903. ],
  2904. '暗黑悬疑风格' => [
  2905. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  2906. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图',
  2907. 'prompt' => '暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现'
  2908. ],
  2909. '治愈清新风格' => [
  2910. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  2911. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强',
  2912. 'prompt' => '治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足'
  2913. ]
  2914. ];
  2915. if (isset($stylePrefixes[$inputArtStyle])) {
  2916. $item = $stylePrefixes[$inputArtStyle];
  2917. $prompt = (string)($item['prompt'] ?? '');
  2918. // 前缀缺失时用通用 prompt 兜底
  2919. $result = [
  2920. 'character_prefix' => !empty($item['character_prefix']) ? $item['character_prefix'] : $prompt,
  2921. 'scene_prefix' => !empty($item['scene_prefix']) ? $item['scene_prefix'] : $prompt,
  2922. ];
  2923. // 与表分支一致:前缀与通用提示词均不存在时返回空数组
  2924. if ($result['character_prefix'] === '' && $result['scene_prefix'] === '') {
  2925. return [];
  2926. }
  2927. return $result;
  2928. }
  2929. return [];
  2930. }
  2931. private function normalizeArtStyleInput($value): string
  2932. {
  2933. $value = trim((string)$value);
  2934. if ($value === '') {
  2935. return '';
  2936. }
  2937. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  2938. return mb_strtolower($value, 'UTF-8');
  2939. }
  2940. private function replaceArtStyleSection(string $content, string $artStyle): string
  2941. {
  2942. if ($content === '' || $artStyle === '') {
  2943. return $content;
  2944. }
  2945. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  2946. if (!preg_match($pattern, $content)) {
  2947. return $content;
  2948. }
  2949. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  2950. }
  2951. /**
  2952. * 解开模型偶发返回的 JSON 包装内容
  2953. *
  2954. * @param mixed $content 模型返回的原始内容
  2955. * @return mixed 解开后的内容(若无法解开则原样返回)
  2956. */
  2957. private function unwrapJsonWrappedContent($content) {
  2958. $trimmed = ltrim((string)$content);
  2959. if ($trimmed === '' || ($trimmed[0] !== '{' && $trimmed[0] !== '[')) {
  2960. return $content;
  2961. }
  2962. $decoded = json_decode($trimmed, true);
  2963. if (!is_array($decoded)) {
  2964. return $content;
  2965. }
  2966. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2967. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2968. return $decoded[$key];
  2969. }
  2970. }
  2971. return $content;
  2972. }
  2973. /**
  2974. * 流式文生文统一分发:根据模型路由到对应提供商的流式实现
  2975. *
  2976. * @param array $post_data 请求参数(含 model / messages / stream 等)
  2977. * @return \Generator
  2978. */
  2979. public function dispatchStreamByModel($post_data) {
  2980. // 强制按流式模式分发
  2981. $post_data['stream'] = true;
  2982. $model = (string)getProp($post_data, 'model', '');
  2983. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2984. // DeepSeek 官方模型
  2985. return $this->deepSeekStreamResponse($post_data);
  2986. } else if (in_array($model, $this->gpt_text_models)) {
  2987. // GPT 模型
  2988. return $this->gpt54StreamResponse($post_data);
  2989. } else if (in_array($model, $this->gemini_text_models)) {
  2990. // Gemini 模型
  2991. return $this->geminiStreamResponse($post_data, $model);
  2992. } else if (in_array($model, $this->baidu_glm_text_models)) {
  2993. // 百度 AI 网关 GLM 模型
  2994. return $this->baiduGLMStreamResponse($post_data);
  2995. } else if (in_array($model, $this->valid_text_models)) {
  2996. // 火山引擎等其他模型
  2997. return $this->volcEngineChatCompletion($post_data);
  2998. }
  2999. Utils::throwError('20003:不支持的模型: ' . $model);
  3000. }
  3001. /**
  3002. * 非流式文生文统一分发:根据模型路由到对应提供商的非流式实现
  3003. *
  3004. * @param array $post_data 请求参数(含 model / messages / stream 等)
  3005. * @return array
  3006. */
  3007. public function dispatchChatOnlyByModel($post_data) {
  3008. // 强制按非流式模式分发
  3009. $post_data['stream'] = false;
  3010. $model = (string)getProp($post_data, 'model', '');
  3011. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3012. // DeepSeek 官方模型
  3013. return $this->chatOnly($post_data);
  3014. } else if (in_array($model, $this->gpt_text_models)) {
  3015. // GPT 模型
  3016. return $this->gpt54ChatOnly($post_data);
  3017. } else if (in_array($model, $this->gemini_text_models)) {
  3018. // Gemini 模型
  3019. return $this->geminiChatOnly($post_data, $model);
  3020. } else if (in_array($model, $this->baidu_glm_text_models)) {
  3021. // 百度 AI 网关 GLM 模型
  3022. return $this->baiduGLMChatOnly($post_data);
  3023. } else if (in_array($model, $this->valid_text_models)) {
  3024. // 火山引擎等其他模型
  3025. return $this->volcEngineChatCompletion($post_data);
  3026. }
  3027. Utils::throwError('20003:不支持的模型: ' . $model);
  3028. }
  3029. /**
  3030. * 百度 AI 网关 GLM 流式实现(OpenAI Chat Completions 协议)
  3031. *
  3032. * @param array $post_data 请求参数(前端模型名 baidu-glm-5.2 / baidu-glm-5.3)
  3033. * @return \Generator
  3034. */
  3035. private function baiduGLMStreamResponse($post_data) {
  3036. $payload = $this->buildBaiduGLMPayload($post_data, true);
  3037. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3038. try {
  3039. $response = $client->post('https://ai-gateway.baidubce.com/v1/chat/completions', [
  3040. 'json' => $payload,
  3041. 'headers' => $this->baiduGLMHeaders(),
  3042. 'stream' => true,
  3043. ]);
  3044. } catch (\Exception $e) {
  3045. $errorDetail = $this->extractBaiduGLMErrorDetail($e);
  3046. dLog('deepseek')->error('百度GLM流式请求建立失败: ' . $e->getMessage(), [
  3047. 'payload' => $payload,
  3048. 'detail' => $errorDetail,
  3049. ]);
  3050. Utils::throwError('20003:百度GLM流式请求失败: ' . $errorDetail);
  3051. }
  3052. $body = $response->getBody();
  3053. $buffer = '';
  3054. $fullContent = '';
  3055. $fullReasoning = '';
  3056. $usage = [];
  3057. dLog('deepseek')->info('开始读取百度GLM流式响应');
  3058. try {
  3059. while (!$body->eof()) {
  3060. $chunk = $body->read(1024);
  3061. $buffer .= $chunk;
  3062. $lines = explode("\n", $buffer);
  3063. $buffer = array_pop($lines);
  3064. foreach ($lines as $line) {
  3065. $line = trim($line);
  3066. if (empty($line)) {
  3067. continue;
  3068. }
  3069. if (strpos($line, 'data: ') !== 0) {
  3070. dLog('deepseek')->warning('百度GLM非SSE数据行', ['line' => $line]);
  3071. continue;
  3072. }
  3073. $data = substr($line, 6);
  3074. if ($data === '[DONE]') {
  3075. dLog('deepseek')->info('百度GLM收到结束标记');
  3076. break 2;
  3077. }
  3078. try {
  3079. $json = json_decode($data, true);
  3080. if (json_last_error() !== JSON_ERROR_NONE) {
  3081. dLog('deepseek')->warning('百度GLM JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3082. continue;
  3083. }
  3084. if (isset($json['choices'][0]['delta'])) {
  3085. $delta = $json['choices'][0]['delta'];
  3086. // 思考链内容(兼容 reasoning_content / reasoning 两种字段)
  3087. $reasoningDelta = '';
  3088. if (isset($delta['reasoning_content']) && is_string($delta['reasoning_content'])) {
  3089. $reasoningDelta = $delta['reasoning_content'];
  3090. } elseif (isset($delta['reasoning']) && is_string($delta['reasoning'])) {
  3091. $reasoningDelta = $delta['reasoning'];
  3092. }
  3093. if ($reasoningDelta !== '') {
  3094. $fullReasoning .= $reasoningDelta;
  3095. yield [
  3096. 'type' => 'reasoning',
  3097. 'content' => $reasoningDelta,
  3098. 'full_reasoning' => $fullReasoning,
  3099. ];
  3100. }
  3101. // 正文内容
  3102. if (isset($delta['content']) && is_string($delta['content'])) {
  3103. $fullContent .= $delta['content'];
  3104. yield [
  3105. 'type' => 'content',
  3106. 'content' => $delta['content'],
  3107. ];
  3108. }
  3109. }
  3110. if (isset($json['usage'])) {
  3111. $usage = $json['usage'];
  3112. }
  3113. } catch (\Exception $e) {
  3114. dLog('deepseek')->error('百度GLM解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3115. continue;
  3116. }
  3117. }
  3118. }
  3119. } catch (\Exception $e) {
  3120. dLog('deepseek')->error('百度GLM流式读取中断: ' . $e->getMessage());
  3121. throw $e;
  3122. }
  3123. dLog('deepseek')->info('百度GLM流式读取完成', [
  3124. 'content_length' => strlen($fullContent),
  3125. 'reasoning_length' => strlen($fullReasoning),
  3126. ]);
  3127. yield [
  3128. 'type' => 'done',
  3129. 'full_content' => $fullContent,
  3130. 'full_reasoning' => $fullReasoning,
  3131. 'usage' => $usage,
  3132. ];
  3133. }
  3134. /**
  3135. * 百度 AI 网关 GLM 非流式实现(OpenAI Chat Completions 协议)
  3136. *
  3137. * @param array $post_data 请求参数(前端模型名 baidu-glm-5.2 / baidu-glm-5.3)
  3138. * @return array
  3139. */
  3140. private function baiduGLMChatOnly($post_data) {
  3141. $payload = $this->buildBaiduGLMPayload($post_data, false);
  3142. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3143. try {
  3144. $result = $client->post('https://ai-gateway.baidubce.com/v1/chat/completions', [
  3145. 'json' => $payload,
  3146. 'headers' => $this->baiduGLMHeaders(),
  3147. ]);
  3148. $response_arr = json_decode($result->getBody()->getContents(), true);
  3149. dLog('deepseek')->info('百度GLM非流式请求完成', ['response' => $response_arr]);
  3150. $fullContent = '';
  3151. $fullReasoningContent = '';
  3152. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  3153. if (isset($response_arr['choices'][0]['message'])) {
  3154. $message = $response_arr['choices'][0]['message'];
  3155. if (isset($message['content']) && is_string($message['content'])) {
  3156. $fullContent = $message['content'];
  3157. }
  3158. if (isset($message['reasoning_content']) && is_string($message['reasoning_content'])) {
  3159. $fullReasoningContent = $message['reasoning_content'];
  3160. } elseif (isset($message['reasoning']) && is_string($message['reasoning'])) {
  3161. $fullReasoningContent = $message['reasoning'];
  3162. }
  3163. }
  3164. return [
  3165. 'fullContent' => $fullContent,
  3166. 'fullReasoningContent' => $fullReasoningContent,
  3167. 'usage' => $usage,
  3168. ];
  3169. } catch (\Exception $e) {
  3170. $errorDetail = $this->extractBaiduGLMErrorDetail($e);
  3171. dLog('deepseek')->error('百度GLM非流式请求失败: ' . $e->getMessage(), [
  3172. 'payload' => $payload,
  3173. 'detail' => $errorDetail,
  3174. ]);
  3175. Utils::throwError('20003:百度GLM请求失败: ' . $errorDetail);
  3176. }
  3177. }
  3178. /**
  3179. * 组装百度 AI 网关 GLM 请求参数
  3180. *
  3181. * @param array $data 请求参数
  3182. * @param bool $stream 是否流式
  3183. * @return array
  3184. */
  3185. private function buildBaiduGLMPayload(array $data, bool $stream): array
  3186. {
  3187. if (empty(env('BAIDU_GLM_AK'))) {
  3188. Utils::throwError('20003:百度GLM API Key未配置,请检查环境变量BAIDU_GLM_AK');
  3189. }
  3190. $frontModel = (string)getProp($data, 'model', '');
  3191. $externalModel = isset(BaseConst::BAIDU_GLM_MODEL_MAP[$frontModel])
  3192. ? BaseConst::BAIDU_GLM_MODEL_MAP[$frontModel]
  3193. : '';
  3194. if ($externalModel === '') {
  3195. Utils::throwError('20003:不支持的百度GLM模型: ' . $frontModel);
  3196. }
  3197. $messages = getProp($data, 'messages', []);
  3198. if (empty($messages)) {
  3199. Utils::throwError('20003:请提供有效的对话内容');
  3200. }
  3201. // OpenAI Chat Completions 标准参数白名单。
  3202. // 注意:百度 GLM-5.x 始终思考,不支持 thinking 开关(传 disabled 会报 400),
  3203. // 因此不转发 thinking;仅透传网关原生支持的 reasoning_effort(low/high/max)。
  3204. $allowedKeys = [
  3205. 'temperature',
  3206. 'top_p',
  3207. 'max_tokens',
  3208. 'max_completion_tokens',
  3209. 'reasoning_effort',
  3210. 'frequency_penalty',
  3211. 'presence_penalty',
  3212. 'stop',
  3213. 'response_format',
  3214. 'stream_options',
  3215. 'tools',
  3216. 'tool_choice',
  3217. 'user',
  3218. 'seed',
  3219. ];
  3220. $payload = [
  3221. 'model' => $externalModel,
  3222. 'messages' => $messages,
  3223. 'stream' => $stream,
  3224. ];
  3225. foreach ($allowedKeys as $key) {
  3226. if (array_key_exists($key, $data) && $data[$key] !== null && $data[$key] !== '') {
  3227. $payload[$key] = $data[$key];
  3228. }
  3229. }
  3230. // 百度网关只接受 low / high / max;其它取值(如 none)会导致 400
  3231. if (isset($payload['reasoning_effort']) && !in_array($payload['reasoning_effort'], ['low', 'high', 'max'], true)) {
  3232. unset($payload['reasoning_effort']);
  3233. }
  3234. if ($stream && !isset($payload['stream_options'])) {
  3235. $payload['stream_options'] = ['include_usage' => true];
  3236. }
  3237. if (!isset($payload['max_tokens']) && !isset($payload['max_completion_tokens'])) {
  3238. // GLM-5.x 输出上限较高,给长文生成留足空间
  3239. $payload['max_tokens'] = 100000;
  3240. }
  3241. return $payload;
  3242. }
  3243. /**
  3244. * 百度 AI 网关 GLM 鉴权请求头
  3245. *
  3246. * @return array
  3247. */
  3248. private function baiduGLMHeaders(): array
  3249. {
  3250. return [
  3251. 'Authorization' => 'Bearer ' . env('BAIDU_GLM_AK'),
  3252. 'Content-Type' => 'application/json; charset=UTF-8',
  3253. 'Accept' => 'text/event-stream',
  3254. ];
  3255. }
  3256. /**
  3257. * 从 Guzzle 异常响应体中提取百度 AI 网关返回的错误信息
  3258. *
  3259. * @param \Exception $e
  3260. * @return string
  3261. */
  3262. private function extractBaiduGLMErrorDetail(\Exception $e): string
  3263. {
  3264. $detail = $e->getMessage();
  3265. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  3266. try {
  3267. $responseBody = (string)$e->getResponse()->getBody();
  3268. $decoded = json_decode($responseBody, true);
  3269. if (is_array($decoded)) {
  3270. if (isset($decoded['error']['message']) && $decoded['error']['message'] !== '') {
  3271. $detail = $decoded['error']['message'];
  3272. } elseif (isset($decoded['message']) && $decoded['message'] !== '') {
  3273. $detail = $decoded['message'];
  3274. } elseif (isset($decoded['error']) && is_string($decoded['error'])) {
  3275. $detail = $decoded['error'];
  3276. }
  3277. } elseif ($responseBody !== '') {
  3278. $detail = $responseBody;
  3279. }
  3280. } catch (\Throwable $parseError) {
  3281. // 保留原始异常信息
  3282. }
  3283. }
  3284. return mb_substr($detail, 0, 500);
  3285. }
  3286. private function deepSeekStreamResponse($post_data) {
  3287. // 设置最大输出tokens
  3288. $post_data['max_tokens'] = 300000;
  3289. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  3290. $post_data['stream_options'] = ['include_usage' => true];
  3291. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3292. $response = $client->post($this->url, [
  3293. 'json' => $post_data,
  3294. 'headers' => $this->headers,
  3295. 'stream' => true // 启用流式响应
  3296. ]);
  3297. $body = $response->getBody();
  3298. $fullContent = '';
  3299. $fullReasoningContent = '';
  3300. $usage = [];
  3301. $buffer = '';
  3302. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  3303. // 逐行读取流式响应
  3304. while (!$body->eof()) {
  3305. $chunk = $body->read(1024); // 每次读取 1KB
  3306. $buffer .= $chunk;
  3307. // 按行分割
  3308. $lines = explode("\n", $buffer);
  3309. // 保留最后一个不完整的行
  3310. $buffer = array_pop($lines);
  3311. foreach ($lines as $line) {
  3312. $line = trim($line);
  3313. // 跳过空行
  3314. if (empty($line)) {
  3315. continue;
  3316. }
  3317. // 检查是否是 SSE 数据行
  3318. if (strpos($line, 'data: ') !== 0) {
  3319. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  3320. continue;
  3321. }
  3322. $data = substr($line, 6); // 移除 "data: " 前缀
  3323. if ($data === '[DONE]') {
  3324. dLog('deepseek')->info('收到结束标记');
  3325. break 2; // 跳出两层循环
  3326. }
  3327. try {
  3328. $json = json_decode($data, true);
  3329. if (json_last_error() !== JSON_ERROR_NONE) {
  3330. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3331. continue;
  3332. }
  3333. if (isset($json['choices'][0]['delta'])) {
  3334. $delta = $json['choices'][0]['delta'];
  3335. // 处理思维链内容(仅 deepseek-reasoner 模型)
  3336. if (isset($delta['reasoning_content'])) {
  3337. $fullReasoningContent .= $delta['reasoning_content'];
  3338. yield [
  3339. 'type' => 'reasoning',
  3340. 'content' => $delta['reasoning_content'],
  3341. 'full_reasoning' => $fullReasoningContent
  3342. ];
  3343. }
  3344. // 处理最终回答内容
  3345. if (isset($delta['content'])) {
  3346. $fullContent .= $delta['content'];
  3347. yield [
  3348. 'type' => 'content',
  3349. 'content' => $delta['content'],
  3350. ];
  3351. }
  3352. }
  3353. // 获取使用统计信息
  3354. if (isset($json['usage'])) {
  3355. $usage = $json['usage'];
  3356. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  3357. }
  3358. } catch (\Exception $e) {
  3359. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3360. continue;
  3361. }
  3362. }
  3363. }
  3364. dLog('deepseek')->info('流式读取完成', [
  3365. 'content_length' => strlen($fullContent),
  3366. 'reasoning_length' => strlen($fullReasoningContent)
  3367. ]);
  3368. yield [
  3369. 'type' => 'done',
  3370. 'full_content' => $fullContent,
  3371. 'full_reasoning' => $fullReasoningContent,
  3372. 'usage' => $usage
  3373. ];
  3374. }
  3375. /**
  3376. * GPT 重试次数(env 可配置,默认 5 次)
  3377. */
  3378. private function gptRetryTimes()
  3379. {
  3380. return (int)env('GPT_RETRY_TIMES', 5);
  3381. }
  3382. /**
  3383. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  3384. */
  3385. private function gptRetryInterval()
  3386. {
  3387. return (int)env('GPT_RETRY_INTERVAL', 10);
  3388. }
  3389. /**
  3390. * 判断 GPT 请求异常是否可重试
  3391. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  3392. */
  3393. private function isGptRetryableException(\Exception $e)
  3394. {
  3395. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  3396. return false;
  3397. }
  3398. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  3399. $status = $e->getResponse()->getStatusCode();
  3400. return $status >= 500 || $status == 429;
  3401. }
  3402. return true;
  3403. }
  3404. /**
  3405. * GPT 中转站探活:GET /v1/models,5 秒短超时
  3406. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  3407. */
  3408. private function checkGptServiceAvailable($apiKey = null)
  3409. {
  3410. if ($apiKey === null) {
  3411. $apiKey = env('GPT_54_API_KEY');
  3412. }
  3413. if (empty($apiKey)) {
  3414. return false;
  3415. }
  3416. try {
  3417. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  3418. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  3419. 'headers' => [
  3420. 'Authorization' => 'Bearer ' . $apiKey,
  3421. 'Content-Type' => 'application/json'
  3422. ]
  3423. ]);
  3424. $status = $response->getStatusCode();
  3425. return $status < 500 && $status != 429;
  3426. } catch (\Exception $e) {
  3427. return false;
  3428. }
  3429. }
  3430. /**
  3431. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  3432. * 全部失败抛出友好错误
  3433. */
  3434. private function ensureGptServiceAvailable($apiKey = null)
  3435. {
  3436. $maxRetries = $this->gptRetryTimes();
  3437. $interval = $this->gptRetryInterval();
  3438. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  3439. if ($this->checkGptServiceAvailable($apiKey)) {
  3440. return;
  3441. }
  3442. if ($attempt < $maxRetries) {
  3443. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  3444. 'retry' => $attempt + 1,
  3445. 'max_retries' => $maxRetries
  3446. ]);
  3447. sleep($interval);
  3448. }
  3449. }
  3450. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  3451. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  3452. 'max_retries' => $maxRetries,
  3453. 'interval' => $interval
  3454. ]);
  3455. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  3456. }
  3457. /**
  3458. * GPT 流式输出处理方法
  3459. *
  3460. * @param array $post_data GPT API请求参数
  3461. * @return \Generator 返回生成器,用于流式输出
  3462. */
  3463. private function gpt54StreamResponse($post_data) {
  3464. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  3465. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  3466. // gpt-5.4 中转已下线,强制映射到 gpt-5.6-sol
  3467. if ($modelName === 'gpt-5.4') {
  3468. $modelName = 'gpt-5.6-terra';
  3469. $post_data['model'] = $modelName;
  3470. }
  3471. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  3472. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  3473. $usedLunaFallback = false;
  3474. // 流式请求长时间无任何返回(TTFB)超过该秒数时切换备用 Key(env 可配置,默认 600 秒)
  3475. $ttfbTimeoutSeconds = (int)env('GPT_SWITCH_LUNA_AFTER_SECONDS', 600);
  3476. if (empty($apiKey)) {
  3477. Utils::throwError('20003:GPT API Key未配置');
  3478. }
  3479. // 先探活,服务不可用时自动重试
  3480. $this->ensureGptServiceAvailable($apiKey);
  3481. $client = new Client(['timeout' => 1800, 'verify' => false, 'read_timeout' => $ttfbTimeoutSeconds]);
  3482. // 移除 thinking 参数,GPT-5.4 不支持
  3483. if (isset($post_data['thinking'])) {
  3484. unset($post_data['thinking']);
  3485. }
  3486. if (isset($post_data['reasoning_effort'])) {
  3487. unset($post_data['reasoning_effort']);
  3488. }
  3489. // 流式场景下保留 response_format(json 输出时强制模型输出完整 JSON,与非流式 gpt54ChatOnly 对齐)
  3490. // 中转站对 response_format 的兼容性由请求方控制:仅在需要 json 输出时传入
  3491. $post_data['max_completion_tokens'] = 100000;
  3492. // GPT-5.x 上游仅支持 max_completion_tokens,同时携带 max_tokens 会返回 400:
  3493. // Unsupported parameter: 'max_tokens' is not supported with this model.
  3494. // 这里显式移除,防止调用方在 post_data 中残留 max_tokens。
  3495. unset($post_data['max_tokens']);
  3496. // GPT-5.x(推理型上游)不接受 frequency_penalty / presence_penalty:
  3497. // Unsupported parameter: 'frequency_penalty' is not supported with this model.
  3498. // 调用方默认传 0,移除后采样行为不变,显式清理避免 400。
  3499. unset($post_data['frequency_penalty'], $post_data['presence_penalty']);
  3500. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  3501. $post_data['stream_options'] = ['include_usage' => true];
  3502. $maxRetries = $this->gptRetryTimes();
  3503. $interval = $this->gptRetryInterval();
  3504. $attempt = 0;
  3505. while (true) {
  3506. $fullContent = '';
  3507. $usage = [];
  3508. $buffer = '';
  3509. // JSON 输出场景:不启用"整段正文包成 JSON 字符串"的暂缓缓存,流式过程中直接输出供前端展示
  3510. $isJsonRequest = isset($post_data['response_format'])
  3511. && is_array($post_data['response_format'])
  3512. && ($post_data['response_format']['type'] ?? '') === 'json_object';
  3513. $suspectJsonWrap = false;
  3514. $pendingContent = '';
  3515. $requestStartedAt = microtime(true);
  3516. $headers = [
  3517. 'Authorization' => 'Bearer ' . $apiKey,
  3518. 'Content-Type' => 'application/json',
  3519. 'Accept' => 'text/event-stream'
  3520. ];
  3521. try {
  3522. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  3523. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  3524. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  3525. 'json' => $post_data,
  3526. 'headers' => $headers,
  3527. 'stream' => true // 启用流式响应
  3528. ]);
  3529. $body = $response->getBody();
  3530. dLog('deepseek')->info('开始读取 GPT 流式响应');
  3531. // 逐行读取流式响应
  3532. while (!$body->eof()) {
  3533. // 长时间没有任何内容返回时,切换备用 Key 重试
  3534. if ($fullContent === '' && empty($usage) && (microtime(true) - $requestStartedAt) > $ttfbTimeoutSeconds) {
  3535. throw new \RuntimeException('GPT 流式响应长时间无返回,等待切换备用 Key');
  3536. }
  3537. $chunk = $body->read(1024); // 每次读取 1KB
  3538. $buffer .= $chunk;
  3539. // 按行分割
  3540. $lines = explode("\n", $buffer);
  3541. // 保留最后一个不完整的行
  3542. $buffer = array_pop($lines);
  3543. foreach ($lines as $line) {
  3544. $line = trim($line);
  3545. // 跳过空行
  3546. if (empty($line)) {
  3547. continue;
  3548. }
  3549. // 检查是否是 SSE 数据行
  3550. if (strpos($line, 'data: ') !== 0) {
  3551. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  3552. continue;
  3553. }
  3554. $data = substr($line, 6); // 移除 "data: " 前缀
  3555. if ($data === '[DONE]') {
  3556. dLog('deepseek')->info('收到结束标记');
  3557. break 2; // 跳出 foreach 和流读取循环
  3558. }
  3559. try {
  3560. $json = json_decode($data, true);
  3561. if (json_last_error() !== JSON_ERROR_NONE) {
  3562. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3563. continue;
  3564. }
  3565. if (isset($json['choices'][0]['delta'])) {
  3566. $delta = $json['choices'][0]['delta'];
  3567. // 处理回答内容
  3568. if (isset($delta['content'])) {
  3569. $fullContent .= $delta['content'];
  3570. $trimmed = ltrim($fullContent);
  3571. if (!$suspectJsonWrap && !$isJsonRequest && $trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
  3572. // 可能模型把整段正文包成了 JSON 字符串,先暂缓输出
  3573. $suspectJsonWrap = true;
  3574. }
  3575. if (!$suspectJsonWrap) {
  3576. // 中转可能一次返回大段内容,按小块输出保持流式节奏
  3577. $chunkSize = 256;
  3578. $chunkLength = mb_strlen($delta['content']);
  3579. for ($offset = 0; $offset < $chunkLength; $offset += $chunkSize) {
  3580. yield [
  3581. 'type' => 'content',
  3582. 'content' => mb_substr($delta['content'], $offset, $chunkSize),
  3583. ];
  3584. }
  3585. } else {
  3586. $pendingContent .= $delta['content'];
  3587. }
  3588. }
  3589. }
  3590. // 获取使用统计信息
  3591. if (isset($json['usage'])) {
  3592. $usage = $json['usage'];
  3593. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  3594. }
  3595. } catch (\Exception $e) {
  3596. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3597. continue;
  3598. }
  3599. }
  3600. }
  3601. dLog('deepseek')->info('流式读取完成', [
  3602. 'content_length' => strlen($fullContent)
  3603. ]);
  3604. // 兼容模型偶发把整段正文包裹成 JSON 字符串返回
  3605. if ($suspectJsonWrap) {
  3606. $decoded = json_decode(trim($fullContent), true);
  3607. $unwrapped = null;
  3608. if (is_array($decoded)) {
  3609. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  3610. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  3611. $unwrapped = $decoded[$key];
  3612. break;
  3613. }
  3614. }
  3615. }
  3616. if ($unwrapped !== null) {
  3617. $fullContent = $unwrapped;
  3618. $chunkSize = 256;
  3619. $contentLength = mb_strlen($fullContent);
  3620. for ($offset = 0; $offset < $contentLength; $offset += $chunkSize) {
  3621. yield [
  3622. 'type' => 'content',
  3623. 'content' => mb_substr($fullContent, $offset, $chunkSize),
  3624. ];
  3625. }
  3626. } elseif ($pendingContent !== '') {
  3627. // 误判:补发暂缓内容,避免内容丢失
  3628. yield [
  3629. 'type' => 'content',
  3630. 'content' => $pendingContent,
  3631. ];
  3632. }
  3633. }
  3634. yield [
  3635. 'type' => 'done',
  3636. 'full_content' => $fullContent,
  3637. 'full_reasoning' => '',
  3638. 'usage' => $usage
  3639. ];
  3640. return;
  3641. } catch (\Exception $e) {
  3642. // 报错或长时间无返回时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  3643. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  3644. $usedLunaFallback = true;
  3645. $apiKey = $lunaApiKey;
  3646. dLog('deepseek')->warning('GPT 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  3647. continue;
  3648. }
  3649. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  3650. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  3651. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  3652. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  3653. throw $e;
  3654. }
  3655. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  3656. 'retry' => $attempt + 1,
  3657. 'max_retries' => $maxRetries,
  3658. 'error' => $e->getMessage()
  3659. ]);
  3660. sleep($interval);
  3661. $attempt++;
  3662. }
  3663. }
  3664. }
  3665. // 与推理模型对话
  3666. public function chatWithReasoner($data) {
  3667. // 文生文计费预检(normal 档)
  3668. $uid = Site::getUid();
  3669. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'normal'), $uid);
  3670. $content = getProp($data, 'content');
  3671. $model = getProp($data, 'model', 'r1');
  3672. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3673. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3674. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3675. if ($model == 'r1') {
  3676. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  3677. $thinkingMode = 'disabled';
  3678. } else {
  3679. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  3680. $thinkingMode = 'disabled';
  3681. }
  3682. // 获取可选情感(根据音色可支持情感选)
  3683. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  3684. $emotion_list = [];
  3685. foreach ($timbre_emotion as $emotion) {
  3686. $tmp = explode(',', $emotion);
  3687. $emotion_list = array_merge($emotion_list, $tmp);
  3688. }
  3689. $emotion_list = array_unique($emotion_list);
  3690. $emotion_str = implode('、', $emotion_list);
  3691. // // 获取可选情感
  3692. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  3693. // $emotion_str = implode('、', $emotion_list);
  3694. // 是否启用情感
  3695. $enable_emotion = getProp($data, 'enable_emotion', 0);
  3696. if ($enable_emotion) {
  3697. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  3698. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3699. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  3700. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  3701. }else {
  3702. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  3703. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3704. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  3705. }
  3706. $messages = [
  3707. [
  3708. 'role' => 'system',
  3709. 'content' => $sys_content
  3710. ],
  3711. [
  3712. 'role' => 'user',
  3713. 'content' => $content
  3714. ]
  3715. ];
  3716. $post_data = [
  3717. 'model' => $model,
  3718. 'messages' => $messages,
  3719. // 'max_tokens' => 8192,
  3720. 'temperature' => 1,
  3721. 'frequency_penalty' => 0,
  3722. 'presence_penalty' => 0,
  3723. 'thinking' => ['type' => $thinkingMode],
  3724. 'response_format' => [
  3725. 'type' => 'text'
  3726. ],
  3727. 'stream' => false
  3728. ];
  3729. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3730. // 根据模型类型选择调用方法
  3731. $fullContent = '';
  3732. $usage = [];
  3733. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  3734. if (is_array($chatResult)) {
  3735. $fullContent = $chatResult['fullContent'];
  3736. $usage = $chatResult['usage'];
  3737. }
  3738. // 处理获取到的剧本数据
  3739. $script_content = handleScriptWords($fullContent, $enable_emotion);
  3740. $result = [
  3741. 'origin_content' => $fullContent,
  3742. 'roles' => getProp($script_content, 'roles'),
  3743. 'words' => getProp($script_content, 'words'),
  3744. ];
  3745. // 文生文成功计费(normal 档):同时记录积分与 token 明细
  3746. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  3747. 'model' => $model,
  3748. 'source' => 'chatWithReasoner',
  3749. ], 'normal');
  3750. return $result;
  3751. }
  3752. public function resetParagraphAudio($data) {
  3753. $bid = getProp($data, 'bid');
  3754. $cid = getProp($data, 'cid');
  3755. $version_id = getProp($data, 'version_id');
  3756. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  3757. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  3758. 'generate_status' => '待制作',
  3759. 'updated_at' => date('Y-m-d H:i:s')
  3760. ]);
  3761. }
  3762. public function saveParagraphAudio($data) {
  3763. $bid = getProp($data, 'bid');
  3764. $cid = getProp($data, 'cid');
  3765. $version_id = getProp($data, 'version_id');
  3766. $sequence = getProp($data, 'sequence');
  3767. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  3768. // 获取所有情感
  3769. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3770. $emotion_list = array_flip($emotion_list);
  3771. // 获取音色支持情感
  3772. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  3773. $timbre_emotion = explode(',', $timbre_emotion);
  3774. $emotion = getProp($data, 'emotion');
  3775. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  3776. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3777. $list = [
  3778. 'bid' => $bid,
  3779. 'cid' => $cid,
  3780. 'version_id' => $version_id,
  3781. 'sequence' => $sequence,
  3782. 'role' => getProp($data, 'role'),
  3783. 'gender' => getProp($data, 'gender'),
  3784. 'text' => trim(getProp($data, 'text')),
  3785. 'emotion' => $emotion,
  3786. 'emotion_type' => $emotion_type,
  3787. 'voice_type' => getProp($data, 'voice_type'),
  3788. 'voice_name' => getProp($data, 'voice_name'),
  3789. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  3790. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  3791. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  3792. 'pitch' => getProp($data, 'pitch', 0),
  3793. // 'paragraph_audio_url' => '',
  3794. 'generate_status' => '制作中',
  3795. 'error_msg' => '',
  3796. 'updated_at' => date('Y-m-d H:i:s')
  3797. ];
  3798. $continue = false;
  3799. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  3800. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  3801. $list['generate_status'] = '制作成功';
  3802. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  3803. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  3804. $continue = true;
  3805. }
  3806. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  3807. if ($id) {
  3808. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  3809. }else {
  3810. $list['created_at'] = date('Y-m-d H:i:s');
  3811. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  3812. $boolen = $id ? true : false;
  3813. }
  3814. // 如果更新成功则加入查询队列
  3815. if ($boolen) {
  3816. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  3817. Redis::sadd($redis_key, $id);
  3818. }
  3819. if ($boolen && !$continue) {
  3820. $boolen = false;
  3821. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3822. // 根据ID通过API通知合成音频
  3823. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  3824. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  3825. $response = $result->getBody()->getContents();
  3826. $response_arr = json_decode($response, true);
  3827. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3828. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3829. Log::info('通知火山生成段落音频失败: '.$error_msg);
  3830. Utils::throwError('20003:通知火山生成段落音频失败');
  3831. }
  3832. $boolen = true;
  3833. }
  3834. return $boolen;
  3835. }
  3836. public function insertAudioEffect($data) {
  3837. $audio_id = getProp($data, 'audio_id');
  3838. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3839. $bid = getProp($chapter_audio, 'bid');
  3840. $version_id = getProp($chapter_audio, 'version_id');
  3841. $cid = getProp($chapter_audio, 'cid');
  3842. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3843. $audio_effect_json = getProp($data, 'audio_effect_json');
  3844. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  3845. try {
  3846. DB::beginTransaction();
  3847. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3848. if (!$count) {
  3849. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3850. }else {
  3851. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3852. }
  3853. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3854. 'audio_effect_status' => '添加中',
  3855. 'audio_effect_json' => $audio_effect_json,
  3856. 'updated_at' => date('Y-m-d H:i:s')
  3857. ]);
  3858. if (!$boolen1) {
  3859. DB::rollBack();
  3860. Utils::throwError('20003:更新生成数据失败');
  3861. }
  3862. $id = DB::table('mp_audio_tasks')->insertGetId([
  3863. 'audio_id' => $audio_id,
  3864. 'generate_status' => '执行中',
  3865. 'generate_json' => json_encode([], 256),
  3866. 'bid' => $bid,
  3867. 'book_name' => getProp($chapter_audio, 'book_name'),
  3868. 'version_id' => $version_id,
  3869. 'version_name' => getProp($chapter_audio, 'version_name'),
  3870. 'cid' => $cid,
  3871. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3872. 'task_name' => $task_name,
  3873. 'created_at' => date('Y-m-d H:i:s'),
  3874. 'updated_at' => date('Y-m-d H:i:s')
  3875. ]);
  3876. if (!$id) {
  3877. DB::rollBack();
  3878. Utils::throwError('20003:创建任务失败');
  3879. }
  3880. }catch (\Exception $e) {
  3881. DB::rollBack();
  3882. Utils::throwError('20003:'.$e->getMessage());
  3883. }
  3884. DB::commit();
  3885. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3886. // 根据ID通过API通知合成音频
  3887. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3888. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3889. $response = $result->getBody()->getContents();
  3890. $response_arr = json_decode($response, true);
  3891. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3892. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3893. Log::info('通知火山插入音效失败: '.$error_msg);
  3894. Utils::throwError('20003:通知火山插入音效失败');
  3895. }
  3896. return true;
  3897. }
  3898. public function insertBgm($data) {
  3899. $audio_id = getProp($data, 'audio_id');
  3900. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3901. $bid = getProp($chapter_audio, 'bid');
  3902. $version_id = getProp($chapter_audio, 'version_id');
  3903. $cid = getProp($chapter_audio, 'cid');
  3904. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3905. $bgm_json = getProp($data, 'bgm_json');
  3906. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3907. if (!$bgm_json) {
  3908. $bgm_json = getProp($data, 'audio_effect_json');
  3909. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3910. }
  3911. try {
  3912. DB::beginTransaction();
  3913. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3914. if (!$count) {
  3915. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3916. }else {
  3917. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3918. }
  3919. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3920. 'bgm_status' => '添加中',
  3921. 'bgm_json' => $bgm_json,
  3922. 'updated_at' => date('Y-m-d H:i:s')
  3923. ]);
  3924. if (!$boolen1) {
  3925. DB::rollBack();
  3926. Utils::throwError('20003:更新生成数据失败');
  3927. }
  3928. $id = DB::table('mp_audio_tasks')->insertGetId([
  3929. 'audio_id' => $audio_id,
  3930. 'generate_status' => '执行中',
  3931. 'generate_json' => json_encode([], 256),
  3932. 'bid' => $bid,
  3933. 'book_name' => getProp($chapter_audio, 'book_name'),
  3934. 'version_id' => $version_id,
  3935. 'version_name' => getProp($chapter_audio, 'version_name'),
  3936. 'cid' => $cid,
  3937. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3938. 'task_name' => $task_name,
  3939. 'created_at' => date('Y-m-d H:i:s'),
  3940. 'updated_at' => date('Y-m-d H:i:s')
  3941. ]);
  3942. if (!$id) {
  3943. DB::rollBack();
  3944. Utils::throwError('20003:创建任务失败');
  3945. }
  3946. }catch (\Exception $e) {
  3947. DB::rollBack();
  3948. Utils::throwError('20003:'.$e->getMessage());
  3949. }
  3950. DB::commit();
  3951. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3952. // 根据ID通过API通知合成音频
  3953. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3954. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3955. $response = $result->getBody()->getContents();
  3956. $response_arr = json_decode($response, true);
  3957. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3958. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3959. Log::info('通知火山插入bgm失败: '.$error_msg);
  3960. Utils::throwError('20003:通知火山插入bgm失败');
  3961. }
  3962. return true;
  3963. }
  3964. public function getParagraphAudios($data) {
  3965. $bid = getProp($data, 'bid');
  3966. $cid = getProp($data, 'cid');
  3967. $version_id = getProp($data, 'version_id');
  3968. $sequence = getProp($data, 'sequence');
  3969. // 获取已生成的音频
  3970. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  3971. if ($sequence) $query->where('sequence', $sequence);
  3972. $paragraph_audios = $query->orderBy('sequence')->get();
  3973. $result = [];
  3974. foreach($paragraph_audios as $item) {
  3975. $result[] = [
  3976. 'sequence' => getProp($item, 'sequence'),
  3977. 'role' => getProp($item, 'role'),
  3978. 'gender' => getProp($item, 'gender'),
  3979. 'text' => trim(getProp($item, 'text')),
  3980. 'emotion' => getProp($item, 'emotion'),
  3981. 'emotion_type' => getProp($item, 'emotion_type'),
  3982. 'voice_type' => getProp($item, 'voice_type'),
  3983. 'voice_name' => getProp($item, 'voice_name'),
  3984. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3985. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3986. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3987. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3988. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  3989. ];
  3990. }
  3991. return $result;
  3992. }
  3993. // 新增合成任务
  3994. public function addGenerateTask($data) {
  3995. $bid = getProp($data, 'bid');
  3996. $cid = getProp($data, 'cid');
  3997. $version_id = getProp($data, 'version_id');
  3998. $generate_json = getProp($data, 'generate_json');
  3999. // 获取已生成的音频
  4000. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  4001. $paragraph_list = [];
  4002. foreach($paragraph_audios as $item) {
  4003. $paragraph_list[getProp($item, 'sequence')] = [
  4004. 'role' => getProp($item, 'role'),
  4005. 'gender' => getProp($item, 'gender'),
  4006. 'text' => trim(getProp($item, 'text')),
  4007. 'emotion' => getProp($item, 'emotion'),
  4008. 'emotion_type' => getProp($item, 'emotion_type'),
  4009. 'voice_type' => getProp($item, 'voice_type'),
  4010. 'voice_name' => getProp($item, 'voice_name'),
  4011. 'speed_ratio' => getProp($item, 'speed_ratio'),
  4012. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  4013. 'emotion_scale' => getProp($item, 'emotion_scale'),
  4014. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  4015. ];
  4016. }
  4017. // 更新角色-音色信息
  4018. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  4019. $existed_role_info = json_decode($existed_role_info, true);
  4020. if (!$existed_role_info) $existed_role_info = [];
  4021. // 获取情感信息
  4022. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  4023. $emotion_list = array_flip($emotion_list);
  4024. // 获取音色对应情感组
  4025. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  4026. $timbre_emotion_list = [];
  4027. foreach($timbre_emotions as $item) {
  4028. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  4029. }
  4030. // 构造生成音频的json
  4031. $words = json_decode($generate_json, true);
  4032. // 最终合成前的参数组
  4033. $mp_chapter_paragraph_audios = [];
  4034. $sequence = 1;
  4035. $complete_paragraph_sequences = [];
  4036. foreach($words as &$word) {
  4037. 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:参数格式有误');
  4038. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  4039. $role = getProp($word, 'role');
  4040. $word['gender'] = (int)$word['gender'];
  4041. // 判断音色对应情感是否支持,不支持则调整为中性
  4042. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  4043. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  4044. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  4045. if (isset($emotion_list[getProp($word, 'emotion')])) {
  4046. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  4047. }else {
  4048. $word['emotion'] = '中性';
  4049. $word['emotion_type'] = 'neutral';
  4050. }
  4051. $existed_role_info[$role] = [
  4052. 'timbre_type' => $word['voice_type'],
  4053. 'timbre_name' => $word['voice_name'],
  4054. 'emotion' => $word['emotion'],
  4055. 'emotion_type' => $word['emotion_type'],
  4056. 'speed_ratio' => $word['speed_ratio'],
  4057. 'loudness_ratio'=> $word['loudness_ratio'],
  4058. 'emotion_scale' => $word['emotion_scale'],
  4059. 'pitch' => $word['pitch']
  4060. ];
  4061. $word['paragraph_audio_url'] = '';
  4062. // 判断生成参数是否相同,相同则直接使用已生成的音频
  4063. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  4064. // 如果音频存在并且参数都未改变则使用已生成的音频
  4065. if (getProp($paragraph, 'paragraph_audio_url')) {
  4066. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  4067. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  4068. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  4069. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  4070. // {
  4071. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  4072. // }
  4073. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  4074. }
  4075. $tmp = $word;
  4076. // 组装章节分句音频数据
  4077. // $tmp['sequence'] = getProp($word, 'sequence');
  4078. // $tmp['text'] = getProp($word, 'text');
  4079. // $tmp['emotion'] = getProp($word, 'emotion');
  4080. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  4081. // $tmp['voice_name'] = getProp($word, 'voice_name');
  4082. // $tmp['voice_type'] = getProp($word, 'voice_type');
  4083. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  4084. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  4085. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  4086. $tmp['bid'] = $bid;
  4087. $tmp['version_id'] = $version_id;
  4088. $tmp['cid'] = $cid;
  4089. $tmp['sequence'] = $sequence;
  4090. $tmp['created_at'] = date('Y-m-d H:i:s');
  4091. $tmp['updated_at'] = date('Y-m-d H:i:s');
  4092. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  4093. $mp_chapter_paragraph_audios[] = $tmp;
  4094. $complete_paragraph_sequences[] = $sequence;
  4095. $sequence++;
  4096. }
  4097. $generate_json = json_encode($words, 256);
  4098. // 判断是否有未生成字幕的段落
  4099. $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();
  4100. if ($no_subtitle_sequences) {
  4101. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  4102. }
  4103. try {
  4104. DB::beginTransaction();
  4105. $role_info = json_encode($existed_role_info, 256);
  4106. $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')]);
  4107. if (!$boolen) {
  4108. DB::rollBack();
  4109. Utils::throwError('20003:更新角色信息失败');
  4110. }
  4111. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  4112. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  4113. if (!$count) {
  4114. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  4115. }else {
  4116. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  4117. }
  4118. $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')]);
  4119. if (!$boolen1) {
  4120. DB::rollBack();
  4121. Utils::throwError('20003:更新生成数据失败');
  4122. }
  4123. $id = DB::table('mp_audio_tasks')->insertGetId([
  4124. 'audio_id' => getProp($chapter_audio, 'id'),
  4125. 'generate_status' => '执行中',
  4126. 'generate_json' => $generate_json,
  4127. 'bid' => $bid,
  4128. 'book_name' => getProp($chapter_audio, 'book_name'),
  4129. 'version_id' => $version_id,
  4130. 'version_name' => getProp($chapter_audio, 'version_name'),
  4131. 'cid' => $cid,
  4132. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  4133. 'task_name' => $task_name,
  4134. 'created_at' => date('Y-m-d H:i:s'),
  4135. 'updated_at' => date('Y-m-d H:i:s')
  4136. ]);
  4137. if (!$id) {
  4138. DB::rollBack();
  4139. Utils::throwError('20003:创建任务失败');
  4140. }
  4141. // 删除不在段落序号范围内的其他数据
  4142. if ($complete_paragraph_sequences) {
  4143. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  4144. }
  4145. // // 删除章节分句音频数据并重新插入
  4146. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  4147. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  4148. // if (!$boolen3) {
  4149. // DB::rollBack();
  4150. // Utils::throwError('20003:更新章节分句音频失败');
  4151. // }
  4152. } catch (\Exception $e) {
  4153. DB::rollBack();
  4154. Utils::throwError('20003:'.$e->getMessage());
  4155. }
  4156. DB::commit();
  4157. // 通知火山生成音频
  4158. $client = new Client(['timeout' => 1800, 'verify' => false]);
  4159. // 根据ID通过API通知合成音频
  4160. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  4161. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  4162. $response = $result->getBody()->getContents();
  4163. $response_arr = json_decode($response, true);
  4164. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4165. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4166. Log::info('通知火山生成音频失败: '.$error_msg);
  4167. Utils::throwError('20003:通知火山生成音频失败');
  4168. }
  4169. return true;
  4170. }
  4171. public function timbreList($data) {
  4172. $gender = getProp($data, 'gender');
  4173. $timbre_name = getProp($data, 'voice_name');
  4174. $category_id = getProp($data, 'category_id');
  4175. $age_stage = getProp($data, 'age_stage');
  4176. $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');
  4177. if ($gender) {
  4178. $query->where('gender', $gender);
  4179. }
  4180. if ($timbre_name) {
  4181. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  4182. }
  4183. if ($category_id) {
  4184. $query->where(function ($query) use ($category_id) {
  4185. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  4186. });
  4187. }
  4188. if ($age_stage) {
  4189. $query->where('age_stage', $age_stage);
  4190. }
  4191. $list = $query->get()->map(function ($value) {
  4192. $value = (array)$value;
  4193. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  4194. return $value;
  4195. })->toArray();
  4196. return $list;
  4197. }
  4198. // 生成火山临时token
  4199. public function setStsToken() {
  4200. // ************* 配置参数 *************
  4201. $method = 'GET';
  4202. $service = 'sts';
  4203. $host = 'open.volcengineapi.com';
  4204. $region = env('VOLC_REGION');
  4205. $endpoint = 'https://open.volcengineapi.com';
  4206. // $endpoint = 'https://tos-cn-beijing.volces.com';
  4207. $access_key = env('VOLC_AK');
  4208. $secret_key = env('VOLC_SK');
  4209. // 获取缓存中的token,如果没有则请求接口
  4210. $token = Redis::get('volc_sts_token');
  4211. if (!$token) {
  4212. // 查询参数
  4213. $query_parameters = [
  4214. 'Action' => 'AssumeRole',
  4215. 'RoleSessionName' => 'user@zw',
  4216. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  4217. 'Version' => '2018-01-01'
  4218. ];
  4219. // 生成URL编码的查询字符串
  4220. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  4221. // 获取签名头信息
  4222. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  4223. // 构建完整URL
  4224. $request_url = $endpoint . '?' . $request_parameters;
  4225. $client = new Client(['verify' => false]);
  4226. $response = $client->get($request_url, ['headers' => $headers]);
  4227. $response_arr = json_decode($response->getBody()->getContents(), true);
  4228. $result = [
  4229. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  4230. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  4231. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  4232. 'Region' => env('VOLC_REGION'),
  4233. 'Endpoint' => env('VOLC_END_POINT'),
  4234. 'Bucket' => env('VOLC_BUCKET'),
  4235. ];
  4236. // 缓存token
  4237. Redis::setex('volc_sts_token', 3000, json_encode($result));
  4238. return $result;
  4239. } else {
  4240. return json_decode($token, true);
  4241. }
  4242. // $response = $response['Response'];
  4243. // $access_key = $response['Credentials']['AccessKeyId'];
  4244. // $secret_key = $response['Credentials']['AccessKeySecret'];
  4245. // $security_token = $response['Credentials']['SecurityToken'];
  4246. // $expiration = $response['Credentials']['Expiration'];
  4247. // dd($response_arr);
  4248. }
  4249. public function emotionGroups($data) {
  4250. $id = getProp($data, 'group_id');
  4251. $group_name = getProp($data, 'group_name');
  4252. $voice_type = getProp($data, 'voice_type');
  4253. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  4254. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  4255. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  4256. if ($group_name) {
  4257. $query->where('group_name', 'like', "%{$group_name}%");
  4258. }
  4259. if ($id) {
  4260. $query->where('id', $id);
  4261. }
  4262. if ($voice_type) {
  4263. $query->where('voice_type', $voice_type);
  4264. }
  4265. return $query->orderBy('id')->get()->map(function ($value) {
  4266. return (array)$value;
  4267. })->toArray();
  4268. }
  4269. private function sign($key, $msg) {
  4270. return hash_hmac('sha256', $msg, $key, true);
  4271. }
  4272. // 生成签名密钥
  4273. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  4274. $kDate = $this->sign($key, $dateStamp);
  4275. $kRegion = $this->sign($kDate, $regionName);
  4276. $kService = $this->sign($kRegion, $serviceName);
  4277. $kSigning = $this->sign($kService, 'request');
  4278. return $kSigning;
  4279. }
  4280. // 获取签名头信息
  4281. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  4282. $contenttype = 'application/x-www-form-urlencoded';
  4283. $accept = 'application/json';
  4284. // 获取当前UTC时间
  4285. $t = new DateTime('now', new DateTimeZone('UTC'));
  4286. $xdate = $t->format('Ymd\THis\Z');
  4287. $datestamp = $t->format('Ymd');
  4288. // 1. 拼接规范请求串
  4289. $canonical_uri = '/';
  4290. $canonical_querystring = $request_parameters;
  4291. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  4292. $signed_headers = 'content-type;host;x-date';
  4293. // 空请求体的SHA256哈希
  4294. $payload_hash = hash('sha256', '');
  4295. $canonical_request = implode("\n", [
  4296. $method,
  4297. $canonical_uri,
  4298. $canonical_querystring,
  4299. $canonical_headers,
  4300. $signed_headers,
  4301. $payload_hash
  4302. ]);
  4303. // 2. 拼接待签名字符串
  4304. $algorithm = 'HMAC-SHA256';
  4305. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  4306. $hashed_canonical_request = hash('sha256', $canonical_request);
  4307. $string_to_sign = implode("\n", [
  4308. $algorithm,
  4309. $xdate,
  4310. $credential_scope,
  4311. $hashed_canonical_request
  4312. ]);
  4313. // 3. 计算签名
  4314. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  4315. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  4316. // 4. 添加签名到请求头
  4317. $authorization_header = sprintf(
  4318. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  4319. $algorithm,
  4320. $access_key,
  4321. $credential_scope,
  4322. $signed_headers,
  4323. $signature
  4324. );
  4325. return [
  4326. 'Accept' => $accept,
  4327. 'Content-Type' => $contenttype,
  4328. 'X-Date' => $xdate,
  4329. 'Authorization' => $authorization_header
  4330. ];
  4331. }
  4332. // 文字合成语音(火山引擎)
  4333. public function tts($data) {
  4334. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  4335. $headers = [
  4336. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  4337. 'Content-Type' => 'application/json; charset=UTF-8'
  4338. ];
  4339. $post_data = [
  4340. 'app' => [
  4341. 'appid' => env('VOLC_APPID'),
  4342. 'token' => env('VOLC_TOKEN'),
  4343. 'cluster' => 'volcano_tts'
  4344. ],
  4345. 'user' => [
  4346. 'uid' => 'mp_audio'
  4347. ],
  4348. // 'audio' => [
  4349. // 'voice_type' =>
  4350. // ],
  4351. ];
  4352. }
  4353. public function scriptList($data) {
  4354. $uid = Site::getUid();
  4355. $script_id = getProp($data, 'script_id');
  4356. $script_name = getProp($data, 'script_name');
  4357. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  4358. if ($script_id) {
  4359. $query->where('id', $script_id);
  4360. }
  4361. if ($script_name) {
  4362. $query->where('script_name', 'like', "%{$script_name}%");
  4363. }
  4364. return $query->orderBy('created_at', 'desc')->paginate(12);
  4365. }
  4366. public function scripts($data) {
  4367. $uid = Site::getUid();
  4368. $script_id = getProp($data, 'script_id');
  4369. $script_name = getProp($data, 'script_name');
  4370. $is_products = getProp($data, 'is_products');
  4371. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  4372. if ($script_id) {
  4373. $query->where('id', $script_id);
  4374. }
  4375. if ($is_products !== '') {
  4376. $query->where('is_products', $is_products);
  4377. }
  4378. if ($script_name) {
  4379. $query->where('script_name', 'like', "%{$script_name}%");
  4380. }
  4381. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  4382. return (array)$value;
  4383. })->toArray();
  4384. }
  4385. public function scriptInfo($data) {
  4386. $uid = Site::getUid();
  4387. $script_id = getProp($data, 'script_id');
  4388. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  4389. // ->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();
  4390. ->selectRaw('id as script_id, script_name')->first();
  4391. if (!$script) Utils::throwError('20003:该剧本不存在!');
  4392. $script = (array)$script;
  4393. // 获取分集组信息
  4394. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  4395. ->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')
  4396. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  4397. $value = (array)$value;
  4398. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  4399. return (array)$value;
  4400. })->toArray();
  4401. $script['group'] = $groups;
  4402. return $script;
  4403. }
  4404. public function createScript($data) {
  4405. $script_name = getProp($data, 'script_name');
  4406. $uid = Site::getUid(); // 获取当前用户ID
  4407. $cpid = Site::getCpid(); // 获取当前公司组ID
  4408. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  4409. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  4410. $script_name .= '_'.date('YmdHis');
  4411. }
  4412. return DB::table('mp_scripts')->insertGetId([
  4413. 'script_name' => $script_name,
  4414. 'user_id' => $uid,
  4415. 'cpid' => $cpid,
  4416. 'created_at' => date('Y-m-d H:i:s'),
  4417. 'updated_at' => date('Y-m-d H:i:s')
  4418. ]);
  4419. }
  4420. public function editScript($data) {
  4421. $script_id = getProp($data, 'script_id');
  4422. $script_name = getProp($data, 'script_name');
  4423. $uid = Site::getUid(); // 获取当前用户ID
  4424. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  4425. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  4426. if ($id && (int)$id !== (int)$script_id) {
  4427. $script_name .= '_'.date('YmdHis');
  4428. }
  4429. return DB::table('mp_scripts')->where('id', $script_id)->update([
  4430. 'script_name' => $script_name,
  4431. 'updated_at' => date('Y-m-d H:i:s')
  4432. ]);
  4433. }
  4434. public function delScript($data) {
  4435. $script_id = getProp($data, 'script_id');
  4436. $uid = Site::getUid(); // 获取当前用户ID
  4437. if (!$script_id) Utils::throwError('20003:请选择剧本');
  4438. return DB::table('mp_scripts')->where('id', $script_id)->update([
  4439. 'is_deleted' => 1,
  4440. 'updated_at' => date('Y-m-d H:i:s')
  4441. ]);
  4442. }
  4443. public function createEpisode($data) {
  4444. $script_id = getProp($data, 'script_id');
  4445. $group_name = getProp($data, 'group_name');
  4446. $remark = getProp($data, 'remark');
  4447. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  4448. $uid = Site::getUid(); // 获取当前用户ID
  4449. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  4450. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  4451. $group_name .= '_'.date('YmdHis');
  4452. }
  4453. return DB::table('mp_script_episode_group')->insertGetId([
  4454. 'script_id' => $script_id,
  4455. 'group_name' => $group_name,
  4456. 'user_id' => $uid,
  4457. 'remark' => $remark,
  4458. 'created_at' => date('Y-m-d H:i:s'),
  4459. 'updated_at' => date('Y-m-d H:i:s')
  4460. ]);
  4461. }
  4462. public function editEpisode($data) {
  4463. $group_id = getProp($data, 'group_id');
  4464. $start_episode_number = getProp($data, 'start_episode_number');
  4465. $end_episode_number = getProp($data, 'end_episode_number');
  4466. $group_name = getProp($data, 'group_name');
  4467. $uid = Site::getUid(); // 获取当前用户ID
  4468. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  4469. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  4470. if ($id && (int)$id !== (int)$group_id) {
  4471. $group_name .= '_'.date('YmdHis');
  4472. }
  4473. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4474. 'group_name' => $group_name,
  4475. 'start_episode_number' => $start_episode_number,
  4476. 'end_episode_number' => $end_episode_number,
  4477. 'updated_at' => date('Y-m-d H:i:s')
  4478. ]);
  4479. }
  4480. public function delEpisode($data) {
  4481. $group_id = getProp($data, 'group_id');
  4482. $uid = Site::getUid(); // 获取当前用户ID
  4483. if (!$group_id) Utils::throwError('20003:请选择分集');
  4484. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4485. 'is_deleted' => 1,
  4486. 'updated_at' => date('Y-m-d H:i:s')
  4487. ]);
  4488. }
  4489. /**
  4490. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4491. *
  4492. * @param array $data 包含以下参数:
  4493. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4494. * - question: 用户问题(可选)
  4495. * - model: 使用的模型(r1 或 v3,默认 v3)
  4496. * @return \Generator 返回生成器,用于流式输出
  4497. */
  4498. public function generateEpisodes($data) {
  4499. // 文生文计费预检(special 档,每次调用扣 10)
  4500. $uid = Site::getUid();
  4501. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  4502. $script_id = getProp($data, 'script_id');
  4503. $group_id = getProp($data, 'group_id');
  4504. // $file = getProp($data, 'file');
  4505. $file = '';
  4506. $content = getProp($data, 'content', '');
  4507. // $bid = getProp($data, 'bid', 0);
  4508. $bid = 0;
  4509. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4510. if (!$group) {
  4511. Utils::throwError('20003:剧本分集不存在');
  4512. }
  4513. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  4514. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  4515. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  4516. $prompt = getProp($data, 'prompt');
  4517. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  4518. $model = getProp($data, 'model');
  4519. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4520. Utils::throwError('20003:该模型不存在!');
  4521. }
  4522. // 检查是否存在重叠的剧集序号范围
  4523. $exists_groups = DB::table('mp_script_episode_group')
  4524. ->where('script_id', $script_id)
  4525. ->where('id', '<>', $group_id) // 排除当前组
  4526. ->where('is_deleted', 0)
  4527. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4528. // 检查新范围是否与现有范围重叠
  4529. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4530. // 新范围的开始在现有范围内
  4531. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4532. ->where('end_episode_number', '>=', $start_episode_sequence);
  4533. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4534. // 新范围的结束在现有范围内
  4535. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4536. ->where('end_episode_number', '>=', $end_episode_sequence);
  4537. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4538. // 新范围完全包含现有范围
  4539. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4540. ->where('end_episode_number', '<=', $end_episode_sequence);
  4541. });
  4542. })
  4543. ->select('start_episode_number', 'end_episode_number')
  4544. ->get();
  4545. if ($exists_groups->isNotEmpty()) {
  4546. $conflict_ranges = [];
  4547. foreach ($exists_groups as $group) {
  4548. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4549. }
  4550. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4551. }
  4552. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4553. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4554. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4555. if ($model === 'deepseek-chat') {
  4556. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4557. $model = 'deepseek-v4-flash';
  4558. $thinkingMode = 'disabled';
  4559. } elseif ($model === 'deepseek-reasoner') {
  4560. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4561. $model = 'deepseek-v4-flash';
  4562. $thinkingMode = 'enabled';
  4563. }
  4564. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4565. if (!$script) {
  4566. Utils::throwError('20003:剧本不存在');
  4567. }
  4568. $content = getProp($group, 'content');
  4569. if (!$file && !$content && !$bid) {
  4570. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4571. }
  4572. // 提取文件内容
  4573. if ($file) {
  4574. $content = $this->extractFileContent($file);
  4575. if (!$content) {
  4576. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4577. }
  4578. } elseif ($bid) {
  4579. $content = $this->getContentByBid($bid);
  4580. if (!$content) {
  4581. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4582. }
  4583. } elseif ($content) {
  4584. $content = filterContent($content);
  4585. } elseif ($prompt) {
  4586. $content = filterContent($prompt);
  4587. } else {
  4588. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4589. }
  4590. // 构建消息
  4591. $messages = [
  4592. $this->sys_message,
  4593. [
  4594. 'role' => 'user',
  4595. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4596. ]
  4597. ];
  4598. $post_data = [
  4599. 'model' => $model,
  4600. 'messages' => $messages,
  4601. // 'max_tokens' => 8192,
  4602. 'temperature' => 0.7,
  4603. 'frequency_penalty' => 0,
  4604. 'presence_penalty' => 0,
  4605. 'thinking' => ['type' => $thinkingMode],
  4606. 'response_format' => ['type' => 'text'],
  4607. 'stream' => true
  4608. ];
  4609. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4610. // 根据模型类型选择调用方法
  4611. $fullContent = '';
  4612. $fullReasoningContent = '';
  4613. $usage = [];
  4614. $streamGenerator = $this->dispatchStreamByModel($post_data);
  4615. // 处理流式输出
  4616. foreach ($streamGenerator as $chunk) {
  4617. if (isset($chunk['type'])) {
  4618. if ($chunk['type'] === 'done') {
  4619. // 最终结果
  4620. $fullContent = $chunk['full_content'];
  4621. $fullReasoningContent = $chunk['full_reasoning'];
  4622. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4623. } else {
  4624. // 逐块yield数据
  4625. yield $chunk;
  4626. }
  4627. }
  4628. }
  4629. dLog('deepseek')->info('完整内容: '.$fullContent);
  4630. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4631. // 处理完整内容并返回最终结果
  4632. $script_arr = [];
  4633. if ($fullContent) {
  4634. $script_arr = extractScriptContent($fullContent);
  4635. }
  4636. logDB('deepseek', 'info', '解析内容', $script_arr);
  4637. if (!$script_arr['episodes']) {
  4638. Utils::throwError('20003:未生成剧本相关信息');
  4639. // yield [
  4640. // 'type' => 'done',
  4641. // 'script' => $script_arr,
  4642. // 'msg' => '未生成剧本相关信息',
  4643. // 'answer' => $fullContent,
  4644. // 'reasoning' => $fullReasoningContent,
  4645. // 'usage' => $usage
  4646. // ];
  4647. // return ;
  4648. }
  4649. try {
  4650. DB::beginTransaction();
  4651. // // 返回前保存剧本内容
  4652. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4653. // 'content' => $content,
  4654. // 'updated_at' => date('Y-m-d H:i:s')
  4655. // ]);
  4656. // if (!$boolen) {
  4657. // Utils::throwError('20003:保存剧本内容失败');
  4658. // }
  4659. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4660. // 'start_episode_number' => $start_episode_sequence,
  4661. // 'end_episode_number' => $end_episode_sequence,
  4662. // 'updated_at' => date('Y-m-d H:i:s')
  4663. // ]);
  4664. // if (!$boolen1) {
  4665. // Utils::throwError('20003:保存分集失败');
  4666. // }
  4667. $episode_content = '';
  4668. $episodes = [];
  4669. foreach ($script_arr['episodes'] as $item) {
  4670. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  4671. // $episodes[] = [
  4672. // 'script_id' => $script_id,
  4673. // 'episode_number' => $item['episode_number'],
  4674. // 'episode_name' => $item['episode_name'],
  4675. // 'episode_content' => $item['episode_content'],
  4676. // 'created_at' => date('Y-m-d H:i:s'),
  4677. // 'updated_at' => date('Y-m-d H:i:s'),
  4678. // ];
  4679. }
  4680. if ($episode_content) {
  4681. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4682. 'episode_content' => $episode_content,
  4683. 'updated_at' => date('Y-m-d H:i:s')
  4684. ]);
  4685. if (!$boolen2) {
  4686. Utils::throwError('20003:保存分集内容失败');
  4687. }
  4688. }else {
  4689. Utils::throwError('20003:分集剧本解析失败');
  4690. }
  4691. // 文生文成功计费(special 档):与落库同事务
  4692. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  4693. 'model' => $model,
  4694. 'script_id' => $script_id,
  4695. 'group_id' => $group_id,
  4696. 'source' => 'generateEpisodes',
  4697. ]);
  4698. }catch (\Exception $e) {
  4699. DB::rollBack();
  4700. Utils::throwError('20003:'.$e->getMessage());
  4701. }
  4702. DB::commit();
  4703. yield [
  4704. 'type' => 'done',
  4705. 'script' => $script_arr,
  4706. 'episode_content' => $episode_content,
  4707. 'answer' => $fullContent,
  4708. 'reasoning' => $fullReasoningContent,
  4709. 'usage' => $usage
  4710. ];
  4711. }
  4712. public function chatWithFileStream($data) {
  4713. // 剧本解析资产表计费预检(special 档)
  4714. $uid = Site::getUid();
  4715. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  4716. $script_id = getProp($data, 'script_id');
  4717. $group_id = getProp($data, 'group_id');
  4718. $file = getProp($data, 'file');
  4719. $content = getProp($data, 'content', '');
  4720. $bid = getProp($data, 'bid', 0);
  4721. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4722. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4723. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  4724. $prompt = getProp($data, 'prompt');
  4725. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4726. if (!empty($prompt)) {
  4727. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4728. }
  4729. $question = getProp($data, 'question', $baseQuestion);
  4730. $model = getProp($data, 'model');
  4731. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4732. Utils::throwError('20003:该模型不存在!');
  4733. }
  4734. // 检查是否存在重叠的剧集序号范围
  4735. $exists_groups = DB::table('mp_script_episode_group')
  4736. ->where('script_id', $script_id)
  4737. ->where('id', '<>', $group_id)
  4738. ->where('is_deleted', 0)
  4739. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4740. // 检查新范围是否与现有范围重叠
  4741. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4742. // 新范围的开始在现有范围内
  4743. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4744. ->where('end_episode_number', '>=', $start_episode_sequence);
  4745. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4746. // 新范围的结束在现有范围内
  4747. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4748. ->where('end_episode_number', '>=', $end_episode_sequence);
  4749. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4750. // 新范围完全包含现有范围
  4751. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4752. ->where('end_episode_number', '<=', $end_episode_sequence);
  4753. });
  4754. })
  4755. ->select('start_episode_number', 'end_episode_number')
  4756. ->get();
  4757. if ($exists_groups->isNotEmpty()) {
  4758. $conflict_ranges = [];
  4759. foreach ($exists_groups as $group) {
  4760. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4761. }
  4762. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4763. }
  4764. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4765. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4766. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4767. if ($model === 'deepseek-chat') {
  4768. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4769. $model = 'deepseek-v4-flash';
  4770. $thinkingMode = 'disabled';
  4771. } elseif ($model === 'deepseek-reasoner') {
  4772. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4773. $model = 'deepseek-v4-flash';
  4774. $thinkingMode = 'enabled';
  4775. }
  4776. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4777. if (!$script) {
  4778. Utils::throwError('20003:剧本不存在');
  4779. }
  4780. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4781. if (!$group) {
  4782. Utils::throwError('20003:剧本分集不存在');
  4783. }
  4784. if (!$file && !$content && !$bid) {
  4785. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4786. }
  4787. // 提取文件内容
  4788. if ($file) {
  4789. $content = $this->extractFileContent($file);
  4790. if (!$content) {
  4791. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4792. }
  4793. } elseif ($bid) {
  4794. $content = $this->getContentByBid($bid);
  4795. if (!$content) {
  4796. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4797. }
  4798. } elseif ($content) {
  4799. $content = filterContent($content);
  4800. } elseif ($prompt) {
  4801. $content = filterContent($prompt);
  4802. } else {
  4803. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4804. }
  4805. // 构建消息
  4806. $messages = [
  4807. [
  4808. 'role' => 'system',
  4809. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4810. 强制要求:\n
  4811. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4812. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4813. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  4814. 普通要求:\n
  4815. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  4816. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  4817. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  4818. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  4819. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  4820. 示例如下:\n
  4821. ###剧本名:西昆仑
  4822. ###故事梗概
  4823. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4824. ###剧本亮点
  4825. 亮点1:绝境奇药,生死一线
  4826. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4827. 亮点2:结拜兄妹,化解尴尬
  4828. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4829. 亮点3:纤发夺命,情愫暗涌
  4830. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4831. ###人物关系
  4832. 阿雪与梁萧之间存在兄妹之情。
  4833. ###核心矛盾
  4834. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4835. ###主体列表
  4836. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  4837. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  4838. 阴阳球:天地异宝,能化生精气,救人于危难。
  4839. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  4840. ###美术风格
  4841. 基础画风风格词:厚涂古风
  4842. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4843. ###场景列表
  4844. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  4845. [
  4846. 'role' => 'user',
  4847. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4848. ]
  4849. ];
  4850. $post_data = [
  4851. 'model' => $model,
  4852. 'messages' => $messages,
  4853. // 'max_tokens' => 8192,
  4854. 'temperature' => 0.7,
  4855. 'frequency_penalty' => 0,
  4856. 'presence_penalty' => 0,
  4857. 'thinking' => ['type' => $thinkingMode],
  4858. 'response_format' => ['type' => 'text'],
  4859. 'stream' => true
  4860. ];
  4861. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4862. // 根据模型类型选择调用方法
  4863. $fullContent = '';
  4864. $fullReasoningContent = '';
  4865. $usage = [];
  4866. $streamGenerator = $this->dispatchStreamByModel($post_data);
  4867. // 处理流式输出
  4868. foreach ($streamGenerator as $chunk) {
  4869. if (isset($chunk['type'])) {
  4870. if ($chunk['type'] === 'done') {
  4871. // 最终结果
  4872. $fullContent = $chunk['full_content'];
  4873. $fullReasoningContent = $chunk['full_reasoning'];
  4874. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4875. } else {
  4876. // 逐块yield数据
  4877. yield $chunk;
  4878. }
  4879. }
  4880. }
  4881. dLog('deepseek')->info('完整内容: '.$fullContent);
  4882. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4883. // 处理完整内容并返回最终结果
  4884. $script_arr = [];
  4885. if ($fullContent) {
  4886. $script_arr = extractScriptContent($fullContent);
  4887. }
  4888. logDB('deepseek', 'info', '解析内容', $script_arr);
  4889. if (!$script_arr['roles']) {
  4890. Utils::throwError('20003:未生成剧本相关信息');
  4891. // yield [
  4892. // 'type' => 'done',
  4893. // 'script' => $script_arr,
  4894. // 'msg' => '未生成剧本相关信息',
  4895. // 'answer' => $fullContent,
  4896. // 'reasoning' => $fullReasoningContent,
  4897. // 'usage' => $usage
  4898. // ];
  4899. }
  4900. try {
  4901. DB::beginTransaction();
  4902. // // 返回前保存剧本内容
  4903. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4904. // 'content' => $content,
  4905. // 'status' => '解析完成',
  4906. // 'updated_at' => date('Y-m-d H:i:s')
  4907. // ]);
  4908. // if (!$boolen) {
  4909. // Utils::throwError('20003:保存剧本内容失败');
  4910. // }
  4911. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4912. 'start_episode_number' => $start_episode_sequence,
  4913. 'end_episode_number' => $end_episode_sequence,
  4914. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4915. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4916. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4917. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4918. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4919. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4920. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4921. 'status' => '解析完成',
  4922. 'content' => $content,
  4923. 'updated_at' => date('Y-m-d H:i:s')
  4924. ]);
  4925. if (!$boolen1) {
  4926. Utils::throwError('20003:保存分集失败');
  4927. }
  4928. // 剧本解析资产表成功计费(special 档):与落库同事务
  4929. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  4930. 'model' => $model,
  4931. 'script_id' => $script_id,
  4932. 'group_id' => $group_id,
  4933. 'source' => 'chatWithFileStream',
  4934. ], 'special');
  4935. // $episodes = [];
  4936. // foreach ($script_arr['episodes'] as $item) {
  4937. // $episodes[] = [
  4938. // 'script_id' => $script_id,
  4939. // 'episode_number' => $item['episode_number'],
  4940. // 'episode_name' => $item['episode_name'],
  4941. // 'episode_content' => $item['episode_content'],
  4942. // 'created_at' => date('Y-m-d H:i:s'),
  4943. // 'updated_at' => date('Y-m-d H:i:s'),
  4944. // ];
  4945. // }
  4946. // if ($episodes) {
  4947. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4948. // if (!$boolen2) {
  4949. // Utils::throwError('20003:保存分集内容失败');
  4950. // }
  4951. // }else {
  4952. // Utils::throwError('20003:分集剧本解析失败');
  4953. // }
  4954. }catch (\Exception $e) {
  4955. DB::rollBack();
  4956. Utils::throwError('20003:'.$e->getMessage());
  4957. }
  4958. DB::commit();
  4959. yield [
  4960. 'type' => 'done',
  4961. 'script' => $script_arr,
  4962. 'answer' => $fullContent,
  4963. 'reasoning' => $fullReasoningContent,
  4964. 'usage' => $usage
  4965. ];
  4966. }
  4967. /**
  4968. * 上传文件识别文字内容并与 DeepSeek 进行对话
  4969. *
  4970. * @param array $data 包含以下参数:
  4971. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4972. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  4973. * - model: 使用的模型(r1 或 v3,默认 v3)
  4974. * @return array
  4975. */
  4976. public function chatWithFile($data) {
  4977. // 剧本解析资产表计费预检(special 档)
  4978. $uid = Site::getUid();
  4979. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  4980. $script_id = getProp($data, 'script_id');
  4981. $file = getProp($data, 'file');
  4982. $content = getProp($data, 'content', '');
  4983. $bid = getProp($data, 'bid', 0);
  4984. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4985. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4986. $prompt = getProp($data, 'prompt');
  4987. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4988. if (!empty($prompt)) {
  4989. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4990. }
  4991. $question = getProp($data, 'question', $baseQuestion);
  4992. // 处理文本模型
  4993. $model = getProp($data, 'model');
  4994. if (!$model) {
  4995. // 用户没有输入,使用默认值
  4996. $model = 'doubao-seed-2-0-mini-260215';
  4997. }
  4998. // 验证模型是否在可用模型表中
  4999. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5000. $model = 'doubao-seed-2-0-mini-260215';
  5001. }
  5002. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5003. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5004. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5005. if ($model === 'deepseek-chat') {
  5006. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5007. $model = 'deepseek-v4-flash';
  5008. $thinkingMode = 'disabled';
  5009. } elseif ($model === 'deepseek-reasoner') {
  5010. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5011. $model = 'deepseek-v4-flash';
  5012. $thinkingMode = 'enabled';
  5013. }
  5014. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  5015. if (!$script) {
  5016. Utils::throwError('20003:剧本不存在');
  5017. }
  5018. if (!$file && !$content && !$bid) {
  5019. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5020. }
  5021. // 提取文件内容
  5022. if ($file) {
  5023. $content = $this->extractFileContent($file);
  5024. if (!$content) {
  5025. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5026. }
  5027. } elseif ($bid) {
  5028. $content = $this->getContentByBid($bid);
  5029. if (!$content) {
  5030. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5031. }
  5032. } elseif ($content) {
  5033. $content = filterContent($content);
  5034. } elseif ($prompt) {
  5035. $content = filterContent($prompt);
  5036. } else {
  5037. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5038. }
  5039. // 构建消息
  5040. $messages = [
  5041. $this->sys_message,
  5042. [
  5043. 'role' => 'user',
  5044. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  5045. ]
  5046. ];
  5047. $post_data = [
  5048. 'model' => $model,
  5049. 'messages' => $messages,
  5050. // 'max_tokens' => 8192,
  5051. 'temperature' => 0.7,
  5052. 'frequency_penalty' => 0,
  5053. 'presence_penalty' => 0,
  5054. 'thinking' => ['type' => $thinkingMode],
  5055. 'response_format' => ['type' => 'text'],
  5056. 'stream' => false
  5057. ];
  5058. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5059. // 根据模型类型选择调用方法
  5060. $fullContent = '';
  5061. $usage = [];
  5062. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  5063. if (is_array($chatResult)) {
  5064. $fullContent = $chatResult['fullContent'];
  5065. $usage = $chatResult['usage'];
  5066. }
  5067. $script_arr = [];
  5068. // 处理结果
  5069. if ($fullContent) {
  5070. $script_arr = extractScriptContent($fullContent);
  5071. }
  5072. // 返回前保存剧本内容
  5073. DB::table('mp_scripts')->where('id', $script_id)->update([
  5074. 'content' => $content,
  5075. 'updated_at' => date('Y-m-d H:i:s')
  5076. ]);
  5077. // 剧本解析资产表成功计费(special 档):同时记录积分与 token 明细
  5078. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5079. 'model' => $model,
  5080. 'script_id' => $script_id,
  5081. 'source' => 'chatWithFile',
  5082. ], 'special');
  5083. return [
  5084. 'script' => $script_arr,
  5085. 'answer' => $fullContent,
  5086. 'usage' => $usage
  5087. ];
  5088. }
  5089. public function getEpisodeContent($data) {
  5090. $group_id = getProp($data, 'group_id');
  5091. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  5092. }
  5093. public function saveEpisodeContent($data) {
  5094. $script_id = getProp($data, 'script_id');
  5095. $group_id = getProp($data, 'group_id');
  5096. $start_episode_sequence = getProp($data, 'start_episode_number');
  5097. $end_episode_sequence = getProp($data, 'end_episode_number');
  5098. // 检查是否存在重叠的剧集序号范围
  5099. $exists_groups = DB::table('mp_script_episode_group')
  5100. ->where('script_id', $script_id)
  5101. ->where('id', '<>', $group_id) // 排除当前组
  5102. ->where('is_deleted', 0)
  5103. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  5104. // 检查新范围是否与现有范围重叠
  5105. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5106. // 新范围的开始在现有范围内
  5107. $q->where('start_episode_number', '<=', $start_episode_sequence)
  5108. ->where('end_episode_number', '>=', $start_episode_sequence);
  5109. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5110. // 新范围的结束在现有范围内
  5111. $q->where('start_episode_number', '<=', $end_episode_sequence)
  5112. ->where('end_episode_number', '>=', $end_episode_sequence);
  5113. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5114. // 新范围完全包含现有范围
  5115. $q->where('start_episode_number', '>=', $start_episode_sequence)
  5116. ->where('end_episode_number', '<=', $end_episode_sequence);
  5117. });
  5118. })
  5119. ->select('start_episode_number', 'end_episode_number')
  5120. ->get();
  5121. if ($exists_groups->isNotEmpty()) {
  5122. $conflict_ranges = [];
  5123. foreach ($exists_groups as $group) {
  5124. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  5125. }
  5126. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  5127. }
  5128. $episode_content = getProp($data, 'episode_content');
  5129. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  5130. 'content' => $episode_content,
  5131. 'start_episode_number' => $start_episode_sequence,
  5132. 'end_episode_number' => $end_episode_sequence,
  5133. 'updated_at' => date('Y-m-d H:i:s')
  5134. ]);
  5135. $script_arr =getProp($data, 'script', []);
  5136. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  5137. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  5138. $script_id = getProp($data, 'script_id');
  5139. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  5140. try {
  5141. DB::beginTransaction();
  5142. $update_data = [
  5143. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5144. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5145. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5146. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5147. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5148. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5149. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5150. 'status' => 3,
  5151. 'start_episode_sequence' => $start_episode_sequence,
  5152. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  5153. 'episode_num' => count($script_arr['episodes']),
  5154. 'updated_at' => date('Y-m-d H:i:s')
  5155. ];
  5156. // 保存剧本内容
  5157. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  5158. if (!$boolen) {
  5159. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  5160. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  5161. Utils::throwError('20003:剧本内容保存失败');
  5162. }
  5163. // 保存分集内容
  5164. // 删除历史分集内容
  5165. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  5166. $episodes = [];
  5167. $sequence = 1;
  5168. foreach ($script_arr['episodes'] as $episode) {
  5169. $segment_number = 1;
  5170. foreach($episode['segments'] as $segment) {
  5171. $episodes[] = [
  5172. 'script_id' => $script_id,
  5173. 'episode_number' => $episode['episode_number'],
  5174. 'title' => $episode['title'],
  5175. // 'content' => $episode['content'],
  5176. 'content' => '',
  5177. 'segment_number' => $segment_number,
  5178. 'segment_content' => $segment['segment_content'],
  5179. 'sequence' => $sequence,
  5180. 'created_at' => date('Y-m-d H:i:s'),
  5181. 'updated_at' => date('Y-m-d H:i:s')
  5182. ];
  5183. $sequence++;
  5184. $segment_number++;
  5185. }
  5186. }
  5187. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  5188. if (!$boolen2) {
  5189. dLog('deepseek')->info('分集内容保存失败', $episodes);
  5190. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  5191. Utils::throwError('20003:分集内容保存失败');
  5192. }
  5193. } catch (\Exception $e) {
  5194. DB::rollBack();
  5195. Utils::throwError('20003:'.$e->getMessage());
  5196. }
  5197. DB::commit();
  5198. return true;
  5199. }
  5200. public function getBookContent($data) {
  5201. $bid = getProp($data, 'bid');
  5202. $start_sequence = getProp($data, 'start_sequence');
  5203. $end_sequence = getProp($data, 'end_sequence');
  5204. $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])
  5205. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  5206. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  5207. return $return_content;
  5208. }
  5209. public function exportScript($data) {
  5210. $filename = getProp($data, 'filename');
  5211. $script_id = getProp($data, 'script_id');
  5212. $group_id = getProp($data, 'group_id');
  5213. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  5214. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  5215. if (!$script) Utils::throwError('20003:该剧本不存在!');
  5216. $script = (array)$script;
  5217. // 获取分集组信息
  5218. if ($group_id) {
  5219. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  5220. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  5221. ->get()->map(function($value) {
  5222. return (array)$value;
  5223. })->toArray();
  5224. }else {
  5225. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  5226. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  5227. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  5228. return (array)$value;
  5229. })->toArray();
  5230. }
  5231. if (!$groups) Utils::throwError('20003:分集不存在');
  5232. $script['group'] = $groups;
  5233. $export_type = getProp($data, 'export_type', 'txt');
  5234. // 生成文件名
  5235. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  5236. // 根据导出类型生成不同格式的文件
  5237. switch ($export_type) {
  5238. case 'txt':
  5239. return $this->exportScriptAsTxt($script, $filename);
  5240. case 'pdf':
  5241. return $this->exportScriptAsPdf($script, $filename);
  5242. default:
  5243. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  5244. }
  5245. }
  5246. /**
  5247. * 导出剧本为TXT格式
  5248. */
  5249. private function exportScriptAsTxt($script, $filename) {
  5250. // 构建TXT内容
  5251. $content = $this->buildScriptContent($script);
  5252. // 设置响应头,直接下载
  5253. header('Content-Type: text/plain; charset=utf-8');
  5254. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  5255. header('Content-Length: ' . strlen($content));
  5256. // 输出内容并结束
  5257. echo $content;
  5258. exit();
  5259. }
  5260. /**
  5261. * 导出剧本为PDF格式
  5262. */
  5263. private function exportScriptAsPdf($script, $filename) {
  5264. // 使用HTML转PDF的方式来更好地支持中文
  5265. $htmlContent = $this->buildScriptHtmlForPdf($script);
  5266. // 创建PDF实例
  5267. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  5268. // 设置文档信息
  5269. $pdf->SetCreator('剧本导出系统');
  5270. $pdf->SetAuthor('系统');
  5271. $pdf->SetTitle($script['script_name']);
  5272. $pdf->SetSubject('剧本导出');
  5273. // 设置边距
  5274. $pdf->SetMargins(15, 15, 15);
  5275. $pdf->SetAutoPageBreak(TRUE, 15);
  5276. // 添加页面
  5277. $pdf->AddPage();
  5278. // 注册并使用 simsun.ttf 字体
  5279. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  5280. // 使用HTML内容生成PDF
  5281. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  5282. // 直接输出PDF文件供下载
  5283. header('Content-Type: application/pdf');
  5284. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  5285. // 直接输出PDF内容
  5286. $pdf->Output($filename . '.pdf', 'D');
  5287. exit();
  5288. }
  5289. /**
  5290. * 构建用于PDF的HTML内容
  5291. */
  5292. private function buildScriptHtmlForPdf($script) {
  5293. $html = '<style>
  5294. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  5295. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  5296. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  5297. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  5298. .info { margin-bottom: 8px; }
  5299. .group { margin-bottom: 30px; page-break-inside: avoid; }
  5300. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  5301. .segment { margin-bottom: 10px; margin-left: 20px; }
  5302. .episode-content { white-space: pre-wrap; }
  5303. </style>';
  5304. // 标题
  5305. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  5306. // 处理分组数据
  5307. if (!empty($script['group']) && is_array($script['group'])) {
  5308. $groups = (array)$script['group'];
  5309. foreach ($groups as $group) {
  5310. $html .= '<div class="group">';
  5311. // 分组标题
  5312. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  5313. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  5314. // 故事梗概
  5315. if (!empty($group['intro'])) {
  5316. $html .= '<h3>故事梗概</h3>';
  5317. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  5318. }
  5319. // 剧本亮点
  5320. if (!empty($group['highlights'])) {
  5321. $html .= '<h3>剧本亮点</h3>';
  5322. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  5323. }
  5324. // 人物关系
  5325. if (!empty($group['role_relationship'])) {
  5326. $html .= '<h3>人物关系</h3>';
  5327. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  5328. }
  5329. // 核心矛盾
  5330. if (!empty($group['core_contradiction'])) {
  5331. $html .= '<h3>核心矛盾</h3>';
  5332. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  5333. }
  5334. // 主体列表
  5335. if (!empty($group['roles']) && is_array($group['roles'])) {
  5336. $html .= '<h3>主体列表</h3>';
  5337. $html .= '<ul>';
  5338. foreach ($group['roles'] as $role) {
  5339. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  5340. }
  5341. $html .= '</ul>';
  5342. }
  5343. // 美术风格
  5344. if (!empty($group['art_style'])) {
  5345. $html .= '<h3>美术风格</h3>';
  5346. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  5347. }
  5348. // 场景列表
  5349. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  5350. $html .= '<h3>场景列表</h3>';
  5351. $html .= '<ul>';
  5352. foreach ($group['scenes'] as $scene) {
  5353. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  5354. }
  5355. $html .= '</ul>';
  5356. }
  5357. // 分集剧本
  5358. if (!empty($group['episode_content'])) {
  5359. $html .= '<h3>分集剧本</h3>';
  5360. // 去除零宽字符和其他不可见字符
  5361. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  5362. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  5363. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  5364. }
  5365. $html .= '</div>';
  5366. }
  5367. }
  5368. return $html;
  5369. }
  5370. /**
  5371. * 构建PDF内容
  5372. */
  5373. private function buildPdfContent($pdf, $script) {
  5374. // 标题
  5375. $pdf->SetFont('dejavusans', 'B', 18);
  5376. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  5377. $pdf->Ln(5);
  5378. // 基本信息
  5379. $pdf->SetFont('dejavusans', '', 12);
  5380. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  5381. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  5382. $pdf->Ln(5);
  5383. // 剧本简介
  5384. if (!empty($script['intro'])) {
  5385. $pdf->SetFont('dejavusans', 'B', 14);
  5386. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  5387. $pdf->SetFont('dejavusans', '', 12);
  5388. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  5389. $pdf->Ln(3);
  5390. }
  5391. // 亮点
  5392. if (!empty($script['highlights'])) {
  5393. $pdf->SetFont('dejavusans', 'B', 14);
  5394. $pdf->Cell(0, 10, '亮点', 0, 1);
  5395. $pdf->SetFont('dejavusans', '', 12);
  5396. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  5397. $pdf->Ln(3);
  5398. }
  5399. // 核心矛盾
  5400. if (!empty($script['core_contradiction'])) {
  5401. $pdf->SetFont('dejavusans', 'B', 14);
  5402. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  5403. $pdf->SetFont('dejavusans', '', 12);
  5404. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  5405. $pdf->Ln(3);
  5406. }
  5407. // 艺术风格
  5408. if (!empty($script['art_style'])) {
  5409. $pdf->SetFont('dejavusans', 'B', 14);
  5410. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  5411. $pdf->SetFont('dejavusans', '', 12);
  5412. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  5413. $pdf->Ln(3);
  5414. }
  5415. // 备注
  5416. if (!empty($script['remark'])) {
  5417. $pdf->SetFont('dejavusans', 'B', 14);
  5418. $pdf->Cell(0, 10, '备注', 0, 1);
  5419. $pdf->SetFont('dejavusans', '', 12);
  5420. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  5421. $pdf->Ln(3);
  5422. }
  5423. // 角色列表
  5424. if (!empty($script['roles']) && is_array($script['roles'])) {
  5425. $pdf->SetFont('dejavusans', 'B', 14);
  5426. $pdf->Cell(0, 10, '角色列表', 0, 1);
  5427. $pdf->SetFont('dejavusans', '', 12);
  5428. foreach ($script['roles'] as $index => $role) {
  5429. if (is_array($role) || is_object($role)) {
  5430. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  5431. } else {
  5432. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  5433. }
  5434. }
  5435. $pdf->Ln(3);
  5436. }
  5437. // 角色关系
  5438. if (!empty($script['role_relationship'])) {
  5439. $pdf->SetFont('dejavusans', 'B', 14);
  5440. $pdf->Cell(0, 10, '角色关系', 0, 1);
  5441. $pdf->SetFont('dejavusans', '', 12);
  5442. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  5443. $pdf->Ln(3);
  5444. }
  5445. // 场景列表
  5446. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  5447. $pdf->SetFont('dejavusans', 'B', 14);
  5448. $pdf->Cell(0, 10, '场景列表', 0, 1);
  5449. $pdf->SetFont('dejavusans', '', 12);
  5450. foreach ($script['scenes'] as $index => $scene) {
  5451. if (is_array($scene) || is_object($scene)) {
  5452. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  5453. } else {
  5454. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  5455. }
  5456. }
  5457. $pdf->Ln(5);
  5458. }
  5459. // 分集内容
  5460. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  5461. $pdf->SetFont('dejavusans', 'B', 16);
  5462. $pdf->Cell(0, 12, '分集内容', 0, 1);
  5463. $pdf->Ln(3);
  5464. foreach ($script['episodes'] as $episode) {
  5465. // 检查是否需要新页面
  5466. if ($pdf->GetY() > 250) {
  5467. $pdf->AddPage();
  5468. }
  5469. $pdf->SetFont('dejavusans', 'B', 14);
  5470. $episodeTitle = '第' . $episode['episode_number'] . '集';
  5471. if (!empty($episode['title'])) {
  5472. $episodeTitle .= ':' . $episode['title'];
  5473. }
  5474. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  5475. // 处理分段内容
  5476. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  5477. $pdf->SetFont('dejavusans', '', 12);
  5478. foreach ($episode['segments'] as $segment) {
  5479. if (!empty($segment['segment_content'])) {
  5480. // 如果有分段编号,显示分段标题
  5481. if (!empty($segment['segment_number'])) {
  5482. $pdf->SetFont('dejavusans', 'B', 12);
  5483. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  5484. $pdf->SetFont('dejavusans', '', 12);
  5485. }
  5486. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  5487. $pdf->Ln(2);
  5488. }
  5489. }
  5490. }
  5491. $pdf->Ln(5);
  5492. }
  5493. }
  5494. }
  5495. /**
  5496. * 构建剧本文本内容
  5497. */
  5498. private function buildScriptContent($script) {
  5499. $content = '';
  5500. $groups = $script['group'];
  5501. $groups = (array)$groups;
  5502. foreach ($groups as $group) {
  5503. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  5504. // 剧本基本信息
  5505. if (!empty($group['intro'])) {
  5506. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  5507. }
  5508. if (!empty($group['highlights'])) {
  5509. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  5510. }
  5511. if (!empty($group['role_relationship'])) {
  5512. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  5513. }
  5514. if (!empty($group['core_contradiction'])) {
  5515. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  5516. }
  5517. if (!empty($group['roles']) && is_array($group['roles'])) {
  5518. $content .= "###主体列表\n";
  5519. foreach ($group['roles'] as $role) {
  5520. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  5521. }
  5522. $content .= "\n\n";
  5523. }
  5524. if (!empty($group['art_style'])) {
  5525. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  5526. }
  5527. // 场景信息
  5528. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  5529. $content .= "###场景列表\n";
  5530. foreach ($group['scenes'] as $scene) {
  5531. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  5532. }
  5533. $content .= "\n\n";
  5534. }
  5535. // 分集内容
  5536. if (!empty($group['episode_content'])) {
  5537. $content .= "###分集剧本\n";
  5538. $content .= $group['episode_content'];
  5539. // foreach ($script['episodes'] as $episode) {
  5540. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  5541. // // if (!empty($episode['episode_name'])) {
  5542. // // $content .= ":" . $episode['episode_name'];
  5543. // // }
  5544. // // $content .= "\n";
  5545. // $content .= $episode['episode_content'] . "\n\n";
  5546. // }
  5547. }
  5548. }
  5549. return $content;
  5550. }
  5551. /**
  5552. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  5553. *
  5554. * @param array $data 包含以下参数:
  5555. * - file: 上传的文件(UploadedFile 对象)或文件路径
  5556. * - question: 用户问题(可选)
  5557. * - model: 使用的模型(r1 或 v3,默认 v3)
  5558. * @return \Generator 返回生成器,用于流式输出
  5559. */
  5560. public function addChat($data) {
  5561. $uid = Site::getUid();
  5562. $anime_id = getProp($data, 'anime_id');
  5563. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5564. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5565. if (!$anime) Utils::throwError('20003:对话不存在');
  5566. $file = getProp($data, 'file');
  5567. $content = getProp($data, 'content', '');
  5568. $bid = getProp($data, 'bid', 0);
  5569. $script_id = getProp($data, 'script_id', 0);
  5570. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5571. $prompt = getProp($data, 'prompt');
  5572. $user_anime_name = getProp($anime, 'anime_name');
  5573. // 处理文本模型
  5574. $model = getProp($data, 'model');
  5575. if (!$model) {
  5576. // 用户没有输入,从anime表获取
  5577. $model = getProp($anime, 'model');
  5578. if (!$model) {
  5579. // anime表也没有,使用默认值
  5580. $model = 'doubao-seed-2-0-mini-260215';
  5581. }
  5582. }
  5583. // 验证模型是否在可用模型表中
  5584. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5585. $model = 'doubao-seed-2-0-mini-260215';
  5586. }
  5587. $is_multi = getProp($anime, 'is_multi');
  5588. $is_single = (int)$is_multi !== 1;
  5589. // 积分余额预检(仅单剧集模式收费)
  5590. if ($is_single) {
  5591. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5592. }
  5593. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5594. if ($prompt) {
  5595. $question .= "本次修改要求如下:\n{$prompt}";
  5596. }
  5597. // if (!$file && !$content && !$bid) {
  5598. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5599. // }
  5600. // 提取文件内容
  5601. if ($file) {
  5602. $content = $this->extractFileContent($file);
  5603. if (!$content) {
  5604. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5605. }
  5606. } elseif ($script_id) {
  5607. $content = $this->getContentByScriptId($script_id);
  5608. if (!$content) {
  5609. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5610. }
  5611. } elseif ($bid) {
  5612. $content = $this->getContentByBid($bid);
  5613. if (!$content) {
  5614. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5615. }
  5616. } elseif ($content) {
  5617. $content = filterContent($content);
  5618. } else {
  5619. $content = getProp($anime, 'content');
  5620. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5621. $need_generate_content = true;
  5622. }
  5623. }
  5624. // 美术风格
  5625. $input_art_style = getProp($data, 'art_style');
  5626. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5627. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5628. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5629. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5630. 中年女:邻居阿姨
  5631. 老年男:幽默大爷
  5632. 老年女:婆婆
  5633. 萌娃:奶气萌娃";
  5634. // 判断是否需要生成原文内容
  5635. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5636. // 如果需要生成原文内容,添加额外的要求
  5637. $content_generation_requirement = $need_generate_content
  5638. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5639. : "";
  5640. // 美术风格
  5641. if (!$mappedArtStyle) {
  5642. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5643. }else {
  5644. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5645. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5646. }else {
  5647. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5648. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5649. }
  5650. }
  5651. $systemPrompt = $is_single
  5652. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5653. 强制要求:
  5654. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5655. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5656. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5657. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5658. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5659. 普通要求:
  5660. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5661. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5662. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  5663. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5664. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5665. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5666. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5667. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5668. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5669. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5670. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5671. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5672. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5673. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5674. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5675. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5676. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5677. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5678. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5679. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5680. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5681. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5682. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5683. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5684. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5685. 5.{$mappedArtStyle_prompt}\n\n
  5686. 示例如下:\n
  5687. ###剧本名:西昆仑
  5688. ###故事梗概
  5689. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5690. ###剧本亮点
  5691. 亮点1:绝境奇药,生死一线
  5692. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5693. 亮点2:结拜兄妹,化解尴尬
  5694. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5695. 亮点3:纤发夺命,情愫暗涌
  5696. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5697. ###人物关系
  5698. 阿雪与梁萧之间存在兄妹之情。
  5699. ###核心矛盾
  5700. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5701. ###主体列表
  5702. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5703. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5704. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5705. 姿态:站立。}{{甜心小美}}
  5706. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5707. 全景,正面拍摄,青年女性,亚洲人。
  5708. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5709. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5710. 姿态:站立。}{{阳光青年}}
  5711. ###美术风格
  5712. 基础画风风格词:厚涂古风
  5713. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5714. ###场景列表
  5715. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5716. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5717. 无人物。}
  5718. ###分镜剧本
  5719. ##第1幕:徐家老旧厨房 白天 室内
  5720. 分镜1
  5721. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5722. 场景:徐家老旧厨房
  5723. 构图设计:全景,低角度仰视
  5724. 运镜调度:手持拍摄
  5725. 配音角色:旁白
  5726. 出镜角色:许芸-校服装、徐母
  5727. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5728. 画面类型:普通画面
  5729. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5730. 分镜2
  5731. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5732. 场景:徐家老旧厨房
  5733. 构图设计:近景,徐母面部特写
  5734. 运镜调度:固定镜头
  5735. 配音角色:徐母
  5736. 出镜角色:徐母
  5737. 台词内容:问我夜不归宿死哪儿去了。
  5738. 画面类型:对口型
  5739. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5740. ##第2幕:徐家简陋客厅 黄昏 室内
  5741. 分镜3
  5742. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5743. 场景:徐家简陋客厅
  5744. 构图设计:全景,景深虚化
  5745. 运镜调度:固定镜头
  5746. 配音角色:旁白
  5747. 出镜角色:无
  5748. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5749. 画面类型:普通画面
  5750. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5751. 分镜4
  5752. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5753. 场景:徐家简陋客厅
  5754. 构图设计:特写,火车票
  5755. 运镜调度:固定镜头
  5756. 配音角色:旁白
  5757. 出镜角色:无
  5758. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5759. 画面类型:普通画面
  5760. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5761. "
  5762. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5763. 强制要求:\n
  5764. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5765. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5766. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5767. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5768. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5769. 普通要求:\n
  5770. 1.剧本名(必须生成)必须与文档内容高度相关
  5771. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5772. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5773. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5774. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5775. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5776. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5777. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5778. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5779. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5780. 4.{$mappedArtStyle_prompt}\n\n
  5781. 示例如下:\n
  5782. ###剧本名:西昆仑
  5783. ###故事梗概
  5784. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5785. ###剧本亮点
  5786. 亮点1:绝境奇药,生死一线
  5787. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5788. 亮点2:结拜兄妹,化解尴尬
  5789. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5790. 亮点3:纤发夺命,情愫暗涌
  5791. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5792. ###人物关系
  5793. 阿雪与梁萧之间存在兄妹之情。
  5794. ###核心矛盾
  5795. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5796. ###主体列表
  5797. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5798. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5799. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5800. 姿态:站立。}{{甜心小美}}
  5801. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5802. 全景,正面拍摄,青年女性,亚洲人。
  5803. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5804. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5805. 姿态:站立。}{{阳光青年}}
  5806. ###美术风格
  5807. 基础画风风格词:厚涂古风
  5808. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5809. ###场景列表
  5810. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5811. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5812. 无人物。}";
  5813. // 构建消息
  5814. $messages = [
  5815. [
  5816. 'role' => 'system',
  5817. 'content' => $systemPrompt
  5818. ],
  5819. [
  5820. 'role' => 'user',
  5821. 'content' => "以下是文档内容:
  5822. {$content}
  5823. 用户问题:
  5824. {$question}"
  5825. ]
  5826. ];
  5827. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5828. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5829. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5830. if ($model === 'deepseek-chat') {
  5831. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5832. $model = 'deepseek-v4-flash';
  5833. $thinkingMode = 'disabled';
  5834. } elseif ($model === 'deepseek-reasoner') {
  5835. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5836. $model = 'deepseek-v4-flash';
  5837. $thinkingMode = 'enabled';
  5838. }
  5839. $post_data = [
  5840. 'model' => $model,
  5841. 'messages' => $messages,
  5842. // 'max_tokens' => 8192,
  5843. 'temperature' => 0.7,
  5844. 'frequency_penalty' => 0,
  5845. 'presence_penalty' => 0,
  5846. 'response_format' => ['type' => 'text'],
  5847. 'thinking' => ['type'=>$thinkingMode],
  5848. 'stream' => true // 启用流式输出
  5849. ];
  5850. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5851. // 根据模型类型选择调用方法
  5852. $fullContent = '';
  5853. $fullReasoningContent = '';
  5854. $usage = [];
  5855. try {
  5856. $streamGenerator = $this->dispatchStreamByModel($post_data);
  5857. // 验证返回值类型
  5858. if (!is_iterable($streamGenerator)) {
  5859. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5860. dLog('deepseek')->error('addChat流式生成器无效', [
  5861. 'generator_type' => $errorType,
  5862. 'model' => $model,
  5863. 'anime_id' => $anime_id
  5864. ]);
  5865. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5866. 'type' => $errorType,
  5867. 'model' => $model
  5868. ]);
  5869. yield [
  5870. 'type' => 'error',
  5871. 'script' => [],
  5872. 'episode' => [],
  5873. 'answer' => '',
  5874. 'reasoning' => '',
  5875. 'usage' => [],
  5876. 'error' => '接口返回数据异常,请重新请求'
  5877. ];
  5878. return;
  5879. }
  5880. // 处理流式输出
  5881. foreach ($streamGenerator as $chunk) {
  5882. if (isset($chunk['type'])) {
  5883. if ($chunk['type'] === 'done') {
  5884. // 最终结果
  5885. $fullContent = $chunk['full_content'];
  5886. $fullReasoningContent = $chunk['full_reasoning'];
  5887. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5888. } else {
  5889. // 逐块yield数据
  5890. yield $chunk;
  5891. }
  5892. }
  5893. }
  5894. } catch (\Exception $e) {
  5895. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5896. 'model' => $model,
  5897. 'anime_id' => $anime_id,
  5898. 'trace' => $e->getTraceAsString()
  5899. ]);
  5900. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5901. 'error' => $e->getMessage(),
  5902. 'model' => $model
  5903. ]);
  5904. yield [
  5905. 'type' => 'error',
  5906. 'script' => [],
  5907. 'episode' => [],
  5908. 'answer' => '',
  5909. 'reasoning' => '',
  5910. 'usage' => [],
  5911. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5912. ];
  5913. return;
  5914. }
  5915. dLog('deepseek')->info('完整内容: '.$fullContent);
  5916. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5917. // 处理完整内容并返回最终结果
  5918. $script_arr = [];
  5919. if ($fullContent) {
  5920. $script_arr = handleScriptContent($fullContent);
  5921. dLog('deepseek')->info('解析内容', $script_arr);
  5922. logDB('deepseek', 'info', '解析内容', $script_arr);
  5923. }
  5924. if (empty($script_arr['roles'])) {
  5925. // 未生成剧本相关内容,保存对话记录并返回提示
  5926. dLog('deepseek')->info('未生成剧本相关的内容');
  5927. try {
  5928. DB::beginTransaction();
  5929. $now = date('Y-m-d H:i:s');
  5930. // 保存对话记录
  5931. $records = [
  5932. [
  5933. 'uid' => $uid,
  5934. 'anime_id' => $anime_id,
  5935. 'sequence' => 0,
  5936. 'role' => 'user',
  5937. 'content' => $prompt,
  5938. 'created_at' => $now,
  5939. 'updated_at' => $now
  5940. ],
  5941. [
  5942. 'uid' => $uid,
  5943. 'anime_id' => $anime_id,
  5944. 'sequence' => 0,
  5945. 'role' => 'assistant',
  5946. // 'content' => $fullContent,
  5947. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5948. 'created_at' => $now,
  5949. 'updated_at' => $now
  5950. ]
  5951. ];
  5952. DB::table('mp_anime_records')->insert($records);
  5953. DB::commit();
  5954. } catch (\Exception $e) {
  5955. DB::rollBack();
  5956. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5957. }
  5958. yield [
  5959. 'type' => 'done',
  5960. 'script' => [],
  5961. 'episode' => [],
  5962. 'answer' => $fullContent,
  5963. 'reasoning' => $fullReasoningContent,
  5964. 'usage' => $usage,
  5965. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5966. ];
  5967. return;
  5968. }
  5969. // 如果需要生成原文内容,从script_arr中提取
  5970. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5971. $content = $script_arr['content'];
  5972. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5973. if (!$content) {
  5974. yield [
  5975. 'type' => 'done',
  5976. 'script' => [],
  5977. 'episode' => [],
  5978. 'answer' => $fullContent,
  5979. 'reasoning' => $fullReasoningContent,
  5980. 'usage' => $usage,
  5981. 'error' => '未生成剧本内容,请调整提示词再试'
  5982. ];
  5983. return;
  5984. }
  5985. }
  5986. // 替换美术风格
  5987. if ($mappedArtStyle !== '') {
  5988. $script_arr['art_style'] = $mappedArtStyle;
  5989. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5990. }
  5991. // 新建动漫
  5992. if ($user_anime_name == '新剧本策划') {
  5993. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5994. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5995. // if (!$anime_name) {
  5996. // // 未识别到剧本名,保存对话记录并返回提示
  5997. // dLog('deepseek')->info('未能识别到剧本名称');
  5998. // try {
  5999. // DB::beginTransaction();
  6000. // $now = date('Y-m-d H:i:s');
  6001. // // 保存对话记录
  6002. // $records = [
  6003. // [
  6004. // 'uid' => $uid,
  6005. // 'anime_id' => $anime_id,
  6006. // 'sequence' => 0,
  6007. // 'role' => 'user',
  6008. // 'content' => $prompt,
  6009. // 'created_at' => $now,
  6010. // 'updated_at' => $now
  6011. // ],
  6012. // [
  6013. // 'uid' => $uid,
  6014. // 'anime_id' => $anime_id,
  6015. // 'sequence' => 0,
  6016. // 'role' => 'assistant',
  6017. // 'content' => '未能生成剧本名称,请重试',
  6018. // 'created_at' => $now,
  6019. // 'updated_at' => $now
  6020. // ]
  6021. // ];
  6022. // DB::table('mp_anime_records')->insert($records);
  6023. // DB::commit();
  6024. // } catch (\Exception $e) {
  6025. // DB::rollBack();
  6026. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6027. // }
  6028. // yield [
  6029. // 'type' => 'done',
  6030. // 'script' => [],
  6031. // 'episode' => [],
  6032. // 'answer' => $fullContent,
  6033. // 'reasoning' => $fullReasoningContent,
  6034. // 'usage' => $usage,
  6035. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  6036. // ];
  6037. // return;
  6038. // }
  6039. // 确认对话名称唯一性
  6040. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6041. $anime_name = $anime_name . '_' . date('YmdHis');
  6042. }
  6043. }else {
  6044. $anime_name = $user_anime_name;
  6045. }
  6046. $table_data = [
  6047. 'user_id' => $uid,
  6048. 'anime_name' => $anime_name,
  6049. 'model' => $model,
  6050. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6051. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6052. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6053. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6054. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6055. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6056. 'art_style_type' => $input_art_style,
  6057. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6058. 'status' => '解析完成',
  6059. 'content' => $content,
  6060. 'is_multi' => $is_multi,
  6061. 'ace_mode' => $ace_mode,
  6062. 'generate_status' => '待执行',
  6063. 'updated_at' => date('Y-m-d H:i:s')
  6064. ];
  6065. if ($table_data['content']) {
  6066. $chapters = splitContent($table_data['content']);
  6067. $chapter_count = count($chapters);
  6068. if ($chapter_count > 0) {
  6069. $table_data['start_episode_sequence'] = 1;
  6070. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6071. }
  6072. }
  6073. // 如果有剧本ID则进行绑定
  6074. if ($script_id) {
  6075. $table_data['script_id'] = $script_id;
  6076. }
  6077. $single_episode = [];
  6078. try {
  6079. DB::beginTransaction();
  6080. $now = date('Y-m-d H:i:s');
  6081. // 更新动漫大纲
  6082. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6083. if (!$boolen) {
  6084. dLog('deepseek')->info('动漫保存失败', $table_data);
  6085. Utils::throwError('20003:动漫保存失败');
  6086. }
  6087. // 保存对话记录
  6088. $records = [
  6089. [
  6090. 'uid' => $uid,
  6091. 'anime_id' => $anime_id,
  6092. 'sequence' => 0,
  6093. 'role' => 'user',
  6094. 'content' => $prompt,
  6095. 'created_at' => date('Y-m-d H:i:s'),
  6096. 'updated_at' => date('Y-m-d H:i:s')
  6097. ],
  6098. [
  6099. 'uid' => $uid,
  6100. 'anime_id' => $anime_id,
  6101. 'sequence' => 0,
  6102. 'role' => 'assistant',
  6103. 'content' => $fullContent,
  6104. 'created_at' => date('Y-m-d H:i:s'),
  6105. 'updated_at' => date('Y-m-d H:i:s')
  6106. ]
  6107. ];
  6108. // 保存对话记录
  6109. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6110. if (!$boolen3) {
  6111. Utils::throwError('20003:对话记录保存失败');
  6112. }
  6113. if ($is_single) {
  6114. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6115. if (empty($episode_arr['acts'])) {
  6116. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6117. }
  6118. $saveResult = $this->saveEpisodeVersionData(
  6119. $anime_id,
  6120. 1,
  6121. $episode_arr,
  6122. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6123. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6124. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6125. null,
  6126. null,
  6127. false,
  6128. $content,
  6129. $now
  6130. );
  6131. $single_episode = $saveResult['episode'];
  6132. $episode_id = $saveResult['episode_id'];
  6133. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6134. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6135. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6136. 'props' => json_encode($saveResult['merged_props'], 256),
  6137. 'updated_at' => $now
  6138. ]);
  6139. if ($boolen5 === false) {
  6140. Utils::throwError('20003:单剧集主表资源同步失败');
  6141. }
  6142. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6143. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6144. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6145. $episode_record_content = '确认分镜大纲';
  6146. if ($content !== '') {
  6147. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6148. }
  6149. $episode_records = [
  6150. [
  6151. 'uid' => $uid,
  6152. 'anime_id' => $anime_id,
  6153. 'role' => 'user',
  6154. 'content' => $episode_record_content,
  6155. 'sequence' => 1,
  6156. 'episode_id' => $episode_id,
  6157. 'created_at' => $now,
  6158. 'updated_at' => $now
  6159. ],
  6160. [
  6161. 'uid' => $uid,
  6162. 'anime_id' => $anime_id,
  6163. 'role' => 'assistant',
  6164. 'content' => $fullContent,
  6165. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6166. 'sequence' => 1,
  6167. 'episode_id' => $episode_id,
  6168. 'created_at' => $now,
  6169. 'updated_at' => $now
  6170. ]
  6171. ];
  6172. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6173. if (!$boolen4) {
  6174. Utils::throwError('20003:单剧集分镜记录保存失败');
  6175. }
  6176. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6177. if ($is_single && !empty($single_episode)) {
  6178. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6179. 'anime_id' => $anime_id,
  6180. 'episode_id' => $episode_id ?? 0,
  6181. 'model' => $model,
  6182. 'source' => 'addChat',
  6183. ]);
  6184. }
  6185. }
  6186. }catch (\Exception $e) {
  6187. DB::rollBack();
  6188. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6189. yield [
  6190. 'type' => 'done',
  6191. 'answer' => $fullContent,
  6192. 'reasoning' => $fullReasoningContent,
  6193. 'usage' => $usage,
  6194. 'error' => $e->getMessage(),
  6195. ];
  6196. return;
  6197. }
  6198. DB::commit();
  6199. dLog('deepseek')->info('保存完毕');
  6200. if ($is_single && !empty($single_episode)) {
  6201. // $this->batchSetGlobalRoleImg([
  6202. // 'anime_id' => $anime_id,
  6203. // ]);
  6204. // $this->batchSetGlobalSceneImg([
  6205. // 'anime_id' => $anime_id,
  6206. // ]);
  6207. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6208. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6209. }
  6210. $table_data['anime_id'] = $anime_id;
  6211. $table_data['roles'] = json_decode($table_data['roles'], true);
  6212. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6213. // $table_data['episodes'] = $script_arr['episodes'];
  6214. unset($table_data['created_at']);
  6215. unset($table_data['updated_at']);
  6216. unset($table_data['status']);
  6217. dLog('deepseek')->info('开始返回');
  6218. yield [
  6219. 'type' => 'done',
  6220. 'script' => $table_data,
  6221. 'episode' => $single_episode,
  6222. 'answer' => $fullContent,
  6223. 'reasoning' => $fullReasoningContent,
  6224. 'usage' => $usage
  6225. ];
  6226. }
  6227. public function reGenerateAnime($data) {
  6228. $uid = Site::getUid();
  6229. $file = getProp($data, 'file');
  6230. $content = getProp($data, 'content', '');
  6231. $bid = getProp($data, 'bid', 0);
  6232. $script_id = getProp($data, 'script_id', 0);
  6233. $anime_id = getProp($data, 'anime_id');
  6234. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6235. if (!$anime) {
  6236. Utils::throwError('20003:该对话不存在');
  6237. }
  6238. $user_anime_name = getProp($anime, 'anime_name');
  6239. $prompt = getProp($data, 'prompt');
  6240. // 处理文本模型
  6241. $model = getProp($data, 'model');
  6242. if (!$model) {
  6243. // 用户没有输入,从anime表获取
  6244. $model = getProp($anime, 'model');
  6245. if (!$model) {
  6246. // anime表也没有,使用默认值
  6247. $model = 'doubao-seed-2-0-mini-260215';
  6248. }
  6249. }
  6250. // 验证模型是否在可用模型表中
  6251. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6252. $model = 'doubao-seed-2-0-mini-260215';
  6253. }
  6254. $is_multi = getProp($anime, 'is_multi', 1);
  6255. $is_single = (int)$is_multi !== 1;
  6256. // 积分余额预检(仅单剧集模式收费)
  6257. if ($is_single) {
  6258. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  6259. }
  6260. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  6261. if ($is_single) {
  6262. $episode_exists = DB::table('mp_anime_episodes')
  6263. ->where('anime_id', $anime_id)
  6264. ->where('sequence', 1)
  6265. ->exists();
  6266. if ($episode_exists) {
  6267. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  6268. }
  6269. }
  6270. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  6271. if ($prompt) {
  6272. $question .= "本次修改要求如下:\n{$prompt}";
  6273. }
  6274. // 提取文件内容
  6275. if ($file) {
  6276. $content = $this->extractFileContent($file);
  6277. if (!$content) {
  6278. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6279. }
  6280. } elseif ($script_id) {
  6281. $content = $this->getContentByScriptId($script_id);
  6282. if (!$content) {
  6283. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6284. }
  6285. } elseif ($bid) {
  6286. $content = $this->getContentByBid($bid);
  6287. if (!$content) {
  6288. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6289. }
  6290. } elseif ($content) {
  6291. $content = filterContent($content);
  6292. }else {
  6293. $content = filterContent(getProp($anime, 'content'));
  6294. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6295. $need_generate_content = true;
  6296. }
  6297. }
  6298. // 判断是否需要生成原文内容
  6299. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6300. // 如果需要生成原文内容,添加额外的要求
  6301. $content_generation_requirement = $need_generate_content
  6302. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6303. : "";
  6304. // 美术风格
  6305. $input_art_style = getProp($anime, 'art_style');
  6306. if (!$input_art_style) {
  6307. $input_art_style = getProp($data, 'art_style');
  6308. }
  6309. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6310. // 美术风格
  6311. if (!$mappedArtStyle) {
  6312. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6313. }else {
  6314. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6315. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6316. }else {
  6317. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6318. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6319. }
  6320. }
  6321. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  6322. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  6323. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  6324. 中年女:邻居阿姨
  6325. 老年男:幽默大爷
  6326. 老年女:婆婆
  6327. 萌娃:奶气萌娃";
  6328. $system_message = ['role'=>'system', 'content'=>$is_single
  6329. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6330. 强制要求:
  6331. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6332. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6333. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6334. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6335. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6336. 普通要求:
  6337. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6338. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6339. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6340. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6341. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6342. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6343. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6344. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6345. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6346. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6347. 3.$mappedArtStyle_prompt\n\n
  6348. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6349. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6350. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6351. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  6352. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  6353. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6354. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6355. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6356. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6357. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6358. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6359. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6360. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6361. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6362. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\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. 姿态:站立。}{{甜心小美}}
  6383. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6384. 全景,正面拍摄,青年女性,亚洲人。
  6385. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6386. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6387. 姿态:站立。}{{阳光青年}}
  6388. ###美术风格
  6389. 基础画风风格词:厚涂古风
  6390. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6391. ###场景列表
  6392. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6393. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6394. 无人物。}
  6395. ###分镜剧本
  6396. ##第1幕:徐家老旧厨房 白天 室内
  6397. 分镜1
  6398. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6399. 场景:徐家老旧厨房
  6400. 构图设计:全景,低角度仰视
  6401. 运镜调度:手持拍摄
  6402. 配音角色:旁白
  6403. 出镜角色:许芸-校服装、徐母
  6404. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6405. 画面类型:普通画面
  6406. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6407. 分镜2
  6408. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6409. 场景:徐家老旧厨房
  6410. 构图设计:近景,徐母面部特写
  6411. 运镜调度:固定镜头
  6412. 配音角色:徐母
  6413. 出镜角色:徐母
  6414. 台词内容:问我夜不归宿死哪儿去了。
  6415. 画面类型:对口型
  6416. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6417. ##第2幕:徐家简陋客厅 黄昏 室内
  6418. 分镜3
  6419. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6420. 场景:徐家简陋客厅
  6421. 构图设计:全景,景深虚化
  6422. 运镜调度:固定镜头
  6423. 配音角色:旁白
  6424. 出镜角色:无
  6425. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6426. 画面类型:普通画面
  6427. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6428. 分镜4
  6429. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6430. 场景:徐家简陋客厅
  6431. 构图设计:特写,火车票
  6432. 运镜调度:固定镜头
  6433. 配音角色:旁白
  6434. 出镜角色:无
  6435. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6436. 画面类型:普通画面
  6437. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  6438. "
  6439. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6440. 强制要求:\n
  6441. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6442. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6443. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6444. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6445. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6446. 普通要求:\n
  6447. 1.剧本名(必须生成)必须与文档内容高度相关
  6448. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6449. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6450. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6451. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6452. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6453. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6454. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6455. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6456. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6457. 4.$mappedArtStyle_prompt\n\n
  6458. 示例如下:\n
  6459. ###剧本名:西昆仑
  6460. ###故事梗概
  6461. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6462. ###剧本亮点
  6463. 亮点1:绝境奇药,生死一线
  6464. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6465. 亮点2:结拜兄妹,化解尴尬
  6466. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6467. 亮点3:纤发夺命,情愫暗涌
  6468. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6469. ###人物关系
  6470. 阿雪与梁萧之间存在兄妹之情。
  6471. ###核心矛盾
  6472. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6473. ###主体列表
  6474. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6475. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6476. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6477. 姿态:站立。}{{甜心小美}}
  6478. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6479. 全景,正面拍摄,青年女性,亚洲人。
  6480. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6481. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6482. 姿态:站立。}{{阳光青年}}
  6483. ###美术风格
  6484. 基础画风风格词:厚涂古风
  6485. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6486. ###场景列表
  6487. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6488. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6489. 无人物。}"];
  6490. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6491. $episode_count = $this->extractEpisodeNumber($prompt);
  6492. if ((int)getProp($anime, 'is_multi') !== 1) {
  6493. yield [
  6494. 'type' => 'done',
  6495. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6496. 'reasoning' => '',
  6497. 'usage' => []
  6498. ];
  6499. return;
  6500. }
  6501. if ($episode_count) {
  6502. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6503. $system_message = [
  6504. 'role' => 'system',
  6505. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6506. 强制要求:\n
  6507. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6508. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6509. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6510. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6511. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6512. 普通要求:\n
  6513. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6514. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6515. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6516. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6517. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6518. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6519. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6520. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6521. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6522. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6523. 示例如下:\n
  6524. ###剧本名:西昆仑
  6525. ###故事梗概
  6526. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6527. ###剧本亮点
  6528. 亮点1:绝境奇药,生死一线
  6529. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6530. 亮点2:结拜兄妹,化解尴尬
  6531. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6532. 亮点3:纤发夺命,情愫暗涌
  6533. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6534. ###人物关系
  6535. 阿雪与梁萧之间存在兄妹之情。
  6536. ###核心矛盾
  6537. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6538. ###主体列表
  6539. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6540. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6541. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6542. 姿态:站立。}{{甜心小美}}
  6543. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6544. 全景,正面拍摄,青年女性,亚洲人。
  6545. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6546. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6547. 姿态:站立。}{{阳光青年}}
  6548. ###美术风格
  6549. 基础画风风格词:厚涂古风
  6550. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6551. ###场景列表
  6552. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6553. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6554. 无人物。}
  6555. ###分集详细内容
  6556. ##第1章 重生
  6557. 我重生了。
  6558. 源于一个男人偏执的暗恋。
  6559. ##第2章 相救
  6560. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6561. 我眼睛扫向站在锅炉后的卞大伟。"
  6562. ];
  6563. // 构建消息
  6564. $messages = [
  6565. $system_message,
  6566. [
  6567. 'role' => 'user',
  6568. 'content' => "以下是文档内容:
  6569. {$content}
  6570. 用户问题:
  6571. {$question}"
  6572. ]
  6573. ];
  6574. }else {
  6575. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6576. // 构建消息
  6577. $messages = [
  6578. $system_message,
  6579. [
  6580. 'role' => 'user',
  6581. 'content' => "以下是文档内容:
  6582. {$content}
  6583. 用户问题:
  6584. {$question}"
  6585. ]
  6586. ];
  6587. }else {
  6588. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6589. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6590. return (array)$value;
  6591. })->toArray();
  6592. array_unshift($messages, $system_message);
  6593. $messages[] = [
  6594. 'role' => 'user',
  6595. 'content' => $prompt
  6596. ];
  6597. }
  6598. }
  6599. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6600. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6601. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6602. if ($model === 'deepseek-chat') {
  6603. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6604. $model = 'deepseek-v4-flash';
  6605. $thinkingMode = 'disabled';
  6606. } elseif ($model === 'deepseek-reasoner') {
  6607. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6608. $model = 'deepseek-v4-flash';
  6609. $thinkingMode = 'enabled';
  6610. }
  6611. $post_data = [
  6612. 'model' => $model,
  6613. 'messages' => $messages,
  6614. // 'max_tokens' => 8192,
  6615. 'temperature' => 0.7,
  6616. 'frequency_penalty' => 0,
  6617. 'presence_penalty' => 0,
  6618. 'response_format' => ['type' => 'text'],
  6619. 'thinking' => ['type' => $thinkingMode],
  6620. 'stream' => true // 启用流式输出
  6621. ];
  6622. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6623. // 根据模型类型选择调用方法
  6624. $fullContent = '';
  6625. $fullReasoningContent = '';
  6626. $usage = [];
  6627. // dd($post_data);
  6628. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6629. try {
  6630. $streamGenerator = $this->dispatchStreamByModel($post_data);
  6631. // 验证返回值类型
  6632. if (!is_iterable($streamGenerator)) {
  6633. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6634. dLog('deepseek')->error('方法名流式生成器无效', [
  6635. 'generator_type' => $errorType,
  6636. 'model' => $model,
  6637. // 添加其他上下文信息
  6638. ]);
  6639. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6640. 'type' => $errorType,
  6641. 'model' => $model
  6642. ]);
  6643. yield [
  6644. 'type' => 'error',
  6645. // 根据方法返回相应的空数据结构
  6646. 'answer' => '',
  6647. 'reasoning' => '',
  6648. 'usage' => [],
  6649. 'error' => '接口返回数据异常,请重新请求'
  6650. ];
  6651. return;
  6652. }
  6653. // 处理流式输出
  6654. foreach ($streamGenerator as $chunk) {
  6655. if (isset($chunk['type'])) {
  6656. if ($chunk['type'] === 'done') {
  6657. $fullContent = $chunk['full_content'];
  6658. $fullReasoningContent = $chunk['full_reasoning'];
  6659. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6660. } else {
  6661. yield $chunk;
  6662. }
  6663. }
  6664. }
  6665. } catch (\Exception $e) {
  6666. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6667. 'model' => $model,
  6668. 'trace' => $e->getTraceAsString()
  6669. ]);
  6670. logDB('deepseek', 'error', '方法名流式处理失败', [
  6671. 'error' => $e->getMessage(),
  6672. 'model' => $model
  6673. ]);
  6674. yield [
  6675. 'type' => 'error',
  6676. // 根据方法返回相应的空数据结构
  6677. 'answer' => '',
  6678. 'reasoning' => '',
  6679. 'usage' => [],
  6680. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6681. ];
  6682. return;
  6683. }
  6684. dLog('deepseek')->info('完整内容: '.$fullContent);
  6685. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6686. // 处理完整内容并返回最终结果
  6687. $script_arr = [];
  6688. if ($fullContent) {
  6689. $script_arr = handleScriptContent($fullContent);
  6690. dLog('deepseek')->info('解析内容', $script_arr);
  6691. logDB('deepseek', 'info', '解析内容', $script_arr);
  6692. }
  6693. if (empty($script_arr['roles'])) {
  6694. // 未生成剧本相关内容,保存对话记录并返回提示
  6695. dLog('deepseek')->info('未生成剧本相关的内容');
  6696. try {
  6697. $now = date('Y-m-d H:i:s');
  6698. // 保存对话记录
  6699. $records = [
  6700. [
  6701. 'uid' => $uid,
  6702. 'anime_id' => $anime_id,
  6703. 'sequence' => 0,
  6704. 'role' => 'user',
  6705. 'content' => $prompt,
  6706. 'created_at' => $now,
  6707. 'updated_at' => $now
  6708. ],
  6709. [
  6710. 'uid' => $uid,
  6711. 'anime_id' => $anime_id,
  6712. 'sequence' => 0,
  6713. 'role' => 'assistant',
  6714. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6715. 'created_at' => $now,
  6716. 'updated_at' => $now
  6717. ]
  6718. ];
  6719. DB::table('mp_anime_records')->insert($records);
  6720. } catch (\Exception $e) {
  6721. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6722. }
  6723. yield [
  6724. 'type' => 'done',
  6725. 'script' => [],
  6726. 'episode' => [],
  6727. 'answer' => $fullContent,
  6728. 'reasoning' => $fullReasoningContent,
  6729. 'usage' => $usage,
  6730. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6731. ];
  6732. return;
  6733. }
  6734. // 替换美术风格
  6735. if ($mappedArtStyle !== '') {
  6736. $script_arr['art_style'] = $mappedArtStyle;
  6737. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6738. }
  6739. if ($user_anime_name != '新剧本策划') {
  6740. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6741. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6742. // 确认对话名称唯一性
  6743. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6744. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6745. }
  6746. }else {
  6747. $anime_name = $user_anime_name;
  6748. }
  6749. $table_data = [
  6750. 'user_id' => $uid,
  6751. 'model' => $model,
  6752. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6753. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6754. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6755. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6756. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6757. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6758. 'art_style_type' => $input_art_style,
  6759. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6760. 'status' => '解析完成',
  6761. 'generate_status' => '待执行',
  6762. 'updated_at' => date('Y-m-d H:i:s')
  6763. ];
  6764. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6765. // 如果是修改集数,则将content内容更新(会改变原文)
  6766. if (isset($episode_count) && $episode_count > 0) {
  6767. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6768. $table_data['start_episode_sequence'] = 1;
  6769. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6770. }else {
  6771. // 如果需要生成原文内容,从script_arr中提取
  6772. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6773. $table_data['content'] = $script_arr['content'];
  6774. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6775. if (!$table_data['content']) {
  6776. yield [
  6777. 'type' => 'done',
  6778. 'script' => [],
  6779. 'episode' => [],
  6780. 'answer' => $fullContent,
  6781. 'reasoning' => $fullReasoningContent,
  6782. 'usage' => $usage,
  6783. 'error' => '未生成剧本内容,请调整提示词再试'
  6784. ];
  6785. return;
  6786. }
  6787. }
  6788. if (isset($table_data['content']) && $table_data['content']) {
  6789. $chapters = splitContent($table_data['content']);
  6790. $chapter_count = count($chapters);
  6791. if ($chapter_count > 0) {
  6792. $table_data['start_episode_sequence'] = 1;
  6793. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6794. }
  6795. }
  6796. }
  6797. $single_episode = [];
  6798. try {
  6799. DB::beginTransaction();
  6800. $now = date('Y-m-d H:i:s');
  6801. // 更新动漫大纲
  6802. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6803. if (!$boolen) {
  6804. dLog('deepseek')->info('对话修改失败', $table_data);
  6805. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6806. Utils::throwError('20003:对话修改失败');
  6807. }
  6808. // 保存对话记录
  6809. $records = [
  6810. [
  6811. 'uid' => $uid,
  6812. 'anime_id' => $anime_id,
  6813. 'sequence' => 0,
  6814. 'role' => 'user',
  6815. 'content' => $prompt,
  6816. 'created_at' => $now,
  6817. 'updated_at' => $now
  6818. ],
  6819. [
  6820. 'uid' => $uid,
  6821. 'anime_id' => $anime_id,
  6822. 'sequence' => 0,
  6823. 'role' => 'assistant',
  6824. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6825. 'content' => $fullContent,
  6826. 'created_at' => $now,
  6827. 'updated_at' => $now
  6828. ]
  6829. ];
  6830. // 保存对话记录
  6831. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6832. if (!$boolen3) {
  6833. Utils::throwError('20003:对话记录保存失败');
  6834. }
  6835. // 单剧集模式:生成并保存剧集信息
  6836. if ($is_single) {
  6837. $anime_name = getProp($anime, 'anime_name', '未命名');
  6838. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6839. if (empty($episode_arr['acts'])) {
  6840. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6841. }
  6842. $saveResult = $this->saveEpisodeVersionData(
  6843. $anime_id,
  6844. 1,
  6845. $episode_arr,
  6846. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6847. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6848. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6849. null,
  6850. null,
  6851. false,
  6852. $content,
  6853. $now
  6854. );
  6855. $single_episode = $saveResult['episode'];
  6856. $episode_id = $saveResult['episode_id'];
  6857. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6858. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6859. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6860. 'props' => json_encode($saveResult['merged_props'], 256),
  6861. 'updated_at' => $now
  6862. ]);
  6863. if ($boolen5 === false) {
  6864. Utils::throwError('20003:单剧集主表资源同步失败');
  6865. }
  6866. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6867. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6868. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6869. $episode_record_content = '确认分镜大纲';
  6870. if ($content !== '') {
  6871. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6872. }
  6873. $episode_records = [
  6874. [
  6875. 'uid' => $uid,
  6876. 'anime_id' => $anime_id,
  6877. 'role' => 'user',
  6878. 'content' => $episode_record_content,
  6879. 'sequence' => 1,
  6880. 'episode_id' => $episode_id,
  6881. 'created_at' => $now,
  6882. 'updated_at' => $now
  6883. ],
  6884. [
  6885. 'uid' => $uid,
  6886. 'anime_id' => $anime_id,
  6887. 'role' => 'assistant',
  6888. 'content' => $fullContent,
  6889. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6890. 'sequence' => 1,
  6891. 'episode_id' => $episode_id,
  6892. 'created_at' => $now,
  6893. 'updated_at' => $now
  6894. ]
  6895. ];
  6896. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6897. if (!$boolen4) {
  6898. Utils::throwError('20003:单剧集分镜记录保存失败');
  6899. }
  6900. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6901. if ($is_single && !empty($single_episode)) {
  6902. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6903. 'anime_id' => $anime_id,
  6904. 'episode_id' => $episode_id ?? 0,
  6905. 'model' => $model,
  6906. 'source' => 'reGenerateAnime',
  6907. ]);
  6908. }
  6909. }
  6910. }catch (\Exception $e) {
  6911. DB::rollBack();
  6912. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  6913. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  6914. yield [
  6915. 'type' => 'done',
  6916. 'answer' => $fullContent,
  6917. 'reasoning' => $fullReasoningContent,
  6918. 'usage' => $usage,
  6919. 'error' => $e->getMessage(),
  6920. ];
  6921. return;
  6922. }
  6923. DB::commit();
  6924. dLog('deepseek')->info('保存完毕');
  6925. if ($is_single && !empty($single_episode)) {
  6926. // $this->batchSetGlobalRoleImg([
  6927. // 'anime_id' => $anime_id,
  6928. // ]);
  6929. // $this->batchSetGlobalSceneImg([
  6930. // 'anime_id' => $anime_id,
  6931. // ]);
  6932. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6933. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6934. }
  6935. $table_data['anime_id'] = $anime_id;
  6936. $table_data['roles'] = json_decode($table_data['roles'], true);
  6937. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6938. unset($table_data['updated_at']);
  6939. unset($table_data['status']);
  6940. yield [
  6941. 'type' => 'done',
  6942. 'script' => $table_data,
  6943. 'episode' => $single_episode,
  6944. 'answer' => $fullContent,
  6945. 'reasoning' => $fullReasoningContent,
  6946. 'usage' => $usage
  6947. ];
  6948. }
  6949. public function chat($data) {
  6950. $uid = Site::getUid();
  6951. // 积分余额预检(不足直接报错)
  6952. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  6953. $anime_id = getProp($data, 'anime_id');
  6954. $file = getProp($data, 'file');
  6955. $content = getProp($data, 'content', '');
  6956. $bid = getProp($data, 'bid', 0);
  6957. $script_id = getProp($data, 'script_id', 0);
  6958. $episode_number = getProp($data, 'episode_number', 1);
  6959. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6960. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6961. if (!$anime) Utils::throwError('20003:该对话不存在!');
  6962. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  6963. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  6964. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  6965. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  6966. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  6967. $roles = is_array($roles) ? $roles : [];
  6968. $scenes = is_array($scenes) ? $scenes : [];
  6969. // 获取最后一集序号
  6970. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  6971. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  6972. // 转换主体列表和场景列表的格式
  6973. // 获取参考主体或场景
  6974. if ((int)$episode_number === 1) {
  6975. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  6976. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  6977. }else {
  6978. $prev_episode_number = $episode_number - 1;
  6979. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  6980. }
  6981. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  6982. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  6983. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  6984. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  6985. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  6986. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  6987. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  6988. 中年女:邻居阿姨
  6989. 老年男:幽默大爷
  6990. 老年女:婆婆
  6991. 萌娃:奶气萌娃";
  6992. if ($roles_content) {
  6993. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  6994. 主体范围:\n {$roles_content}\n
  6995. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  6996. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6997. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6998. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6999. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  7000. }else {
  7001. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7002. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  7003. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7004. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7005. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  7006. }
  7007. if ($scenes_content) {
  7008. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7009. 场景范围:\n {$scenes_content}\n
  7010. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  7011. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7012. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7013. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  7014. }else {
  7015. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7016. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7017. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7018. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  7019. }
  7020. // 提取文件内容
  7021. if ($file) {
  7022. $uploaded_content = $this->extractFileContent($file);
  7023. if (!$uploaded_content) {
  7024. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7025. }
  7026. } elseif ($script_id) {
  7027. $uploaded_content = $this->getContentByScriptId($script_id);
  7028. if (!$uploaded_content) {
  7029. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7030. }
  7031. } elseif ($bid) {
  7032. $uploaded_content = $this->getContentByBid($bid);
  7033. if (!$uploaded_content) {
  7034. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7035. }
  7036. } elseif ($content) {
  7037. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  7038. }
  7039. // elseif ($prompt) {
  7040. // $uploaded_content = filterContent($prompt);
  7041. // }
  7042. else {
  7043. $uploaded_content = '';
  7044. }
  7045. $input_art_style = getProp($anime, 'art_style');
  7046. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7047. // 美术风格
  7048. if (!$mappedArtStyle) {
  7049. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7050. }else {
  7051. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7052. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7053. }else {
  7054. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7055. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7056. }
  7057. }
  7058. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7059. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7060. // 强制要求:
  7061. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7062. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7063. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7064. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  7065. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  7066. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  7067. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  7068. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  7069. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  7070. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  7071. // - 分镜要和场景列表、人物主体保持一致\n
  7072. // 普通要求:
  7073. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7074. // {$role_demo}
  7075. // {$scene_demo}
  7076. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  7077. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  7078. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  7079. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  7080. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  7081. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  7082. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  7083. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  7084. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  7085. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  7086. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  7087. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  7088. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  7089. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  7090. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  7091. // 5.$mappedArtStyle_prompt\n\n
  7092. // 示例格式:\n
  7093. // 第1集:隐形的守护者
  7094. // ###故事梗概
  7095. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7096. // ###美术风格
  7097. // 基础画风风格词:韩漫二次元
  7098. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  7099. // ###主体列表
  7100. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  7101. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  7102. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  7103. // ###场景列表
  7104. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  7105. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7106. // 无人物。}
  7107. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  7108. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  7109. // 无人物。}
  7110. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  7111. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  7112. // 无人物。}
  7113. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  7114. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  7115. // 无人物。}
  7116. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  7117. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  7118. // 无人物。}
  7119. // ###分镜剧本
  7120. // ##第1幕:徐家老旧厨房 白天 室内
  7121. // 分镜1
  7122. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  7123. // 场景:徐家老旧厨房
  7124. // 构图设计:全景,低角度仰视
  7125. // 运镜调度:手持拍摄
  7126. // 配音角色:旁白
  7127. // 出镜角色:许芸-校服装、徐母
  7128. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  7129. // 画面类型:普通画面
  7130. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  7131. // 分镜2
  7132. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  7133. // 场景:徐家老旧厨房
  7134. // 构图设计:近景,徐母面部特写
  7135. // 运镜调度:固定镜头
  7136. // 配音角色:徐母
  7137. // 出镜角色:徐母
  7138. // 台词内容:问我夜不归宿死哪儿去了。
  7139. // 画面类型:对口型
  7140. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  7141. // ##第2幕:徐家简陋客厅 黄昏 室内
  7142. // 分镜3
  7143. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  7144. // 场景:徐家简陋客厅
  7145. // 构图设计:全景,景深虚化
  7146. // 运镜调度:固定镜头
  7147. // 配音角色:旁白
  7148. // 出镜角色:无
  7149. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  7150. // 画面类型:普通画面
  7151. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  7152. // 分镜4
  7153. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  7154. // 场景:徐家简陋客厅
  7155. // 构图设计:特写,火车票
  7156. // 运镜调度:固定镜头
  7157. // 配音角色:旁白
  7158. // 出镜角色:无
  7159. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  7160. // 画面类型:普通画面
  7161. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  7162. // \n\n";
  7163. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7164. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7165. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  7166. 普通要求:
  7167. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7168. {$role_demo}
  7169. {$scene_demo}
  7170. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  7171. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  7172. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  7173. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7174. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  7175. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  7176. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  7177. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  7178. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  7179. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  7180. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  7181. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  7182. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  7183. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  7184. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  7185. 5.$mappedArtStyle_prompt
  7186. 6.《情绪-视听语言映射表》:
  7187. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7188. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7189. -----|---------|------------|----------------
  7190. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7191. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7192. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7193. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7194. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7195. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7196. -----|---------|------------|----------------
  7197. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7198. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7199. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7200. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7201. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7202. --------|---------|--------------|-------------
  7203. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7204. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7205. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7206. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7207. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7208. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7209. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7210. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7211. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7212. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7213. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7214. -----|---------|------------|------------
  7215. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7216. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7217. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7218. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7219. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7220. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7221. --------|---------|--------------|----------
  7222. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7223. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7224. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7225. 6.6 声音设计与潜意识影响 (Soundscape)
  7226. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7227. -----|---------|------------|------------------
  7228. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7229. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7230. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7231. 理论基石:
  7232. - The Five C's of Cinematography by Joseph V. Mascelli
  7233. - Film Art: An Introduction by David Bordwell
  7234. - Sight, Sound, Motion by Herbert Zettl
  7235. - Notes on the Cinematograph by Robert Bresson
  7236. \n\n
  7237. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  7238. 示例格式:\n
  7239. 第1集:隐形的守护者
  7240. ###故事梗概
  7241. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7242. ###美术风格
  7243. 基础画风风格词:韩漫二次元
  7244. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  7245. ###主体列表
  7246. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  7247. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  7248. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  7249. ###场景列表
  7250. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  7251. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7252. 无人物。}
  7253. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  7254. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  7255. 无人物。}
  7256. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  7257. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  7258. 无人物。}
  7259. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  7260. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  7261. 无人物。}
  7262. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  7263. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  7264. 无人物。}
  7265. ###分镜剧本
  7266. ##第1幕:徐家老旧厨房 白天 室内
  7267. 分镜1
  7268. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  7269. 场景:徐家老旧厨房
  7270. 构图设计:全景,低角度仰视
  7271. 运镜调度:手持拍摄
  7272. 配音角色:旁白
  7273. 出镜角色:许芸-校服装、徐母
  7274. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  7275. 画面类型:普通画面
  7276. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  7277. 分镜2
  7278. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  7279. 场景:徐家老旧厨房
  7280. 构图设计:近景,徐母面部特写
  7281. 运镜调度:固定镜头
  7282. 配音角色:徐母
  7283. 出镜角色:徐母
  7284. 台词内容:问我夜不归宿死哪儿去了。
  7285. 画面类型:对口型
  7286. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  7287. ##第2幕:徐家简陋客厅 黄昏 室内
  7288. 分镜3
  7289. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  7290. 场景:徐家简陋客厅
  7291. 构图设计:全景,景深虚化
  7292. 运镜调度:固定镜头
  7293. 配音角色:旁白
  7294. 出镜角色:无
  7295. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  7296. 画面类型:普通画面
  7297. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  7298. 分镜4
  7299. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  7300. 场景:徐家简陋客厅
  7301. 构图设计:特写,火车票
  7302. 运镜调度:固定镜头
  7303. 配音角色:旁白
  7304. 出镜角色:无
  7305. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  7306. 画面类型:普通画面
  7307. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  7308. \n\n";
  7309. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7310. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  7311. $is_regenerate_version = true;
  7312. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7313. $prompt = $origin_prompt;
  7314. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7315. // 获取章节内容
  7316. $full_content = getProp($anime, 'content');
  7317. if ($uploaded_content) {
  7318. $full_content = $uploaded_content;
  7319. }
  7320. // 根据章节内容拆分章节
  7321. $chapters = splitContent($full_content);
  7322. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7323. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7324. $messages = [];
  7325. if ($prompt == '确认分镜大纲') {
  7326. // 暂时保留
  7327. $content = $chapter_content;
  7328. if ($is_single) $content = $full_content; // 单剧集使用全文
  7329. if (!$content) {
  7330. Utils::throwError('20003:章节内容无法获取,请确认');
  7331. }
  7332. $question = $is_single
  7333. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7334. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7335. // 构建消息
  7336. $messages[] =
  7337. [
  7338. 'role' => 'user',
  7339. 'content' => $question
  7340. ];
  7341. }else if ($prompt == '继续策划下一集') {
  7342. if ($is_single) {
  7343. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7344. }
  7345. $content = $chapter_content;
  7346. if (!$content) {
  7347. Utils::throwError('20003:章节内容无法获取,请确认');
  7348. }
  7349. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7350. // 获取上一集最后记录
  7351. $prev_sequence = $episode_number - 1;
  7352. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7353. // 构建消息
  7354. $messages[] =
  7355. [
  7356. 'role' => 'user',
  7357. 'content' => $question
  7358. ];
  7359. }else {
  7360. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7361. if (!$content) {
  7362. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7363. }
  7364. if (!$content) {
  7365. Utils::throwError('20003:章节内容无法获取,请确认');
  7366. }
  7367. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7368. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7369. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7370. if ($origin_prompt) {
  7371. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  7372. }
  7373. $messages[] =
  7374. [
  7375. 'role' => 'user',
  7376. 'content' => $question
  7377. ];
  7378. }
  7379. // 处理文本模型
  7380. $model = getProp($data, 'model');
  7381. if (!$model) {
  7382. // 用户没有输入,从anime表获取
  7383. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7384. $model = getProp($anime, 'model');
  7385. if (!$model) {
  7386. // anime表也没有,使用默认值
  7387. $model = 'doubao-seed-2-0-mini-260215';
  7388. }
  7389. }
  7390. // 验证模型是否在可用模型表中
  7391. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7392. $model = 'doubao-seed-2-0-mini-260215';
  7393. }
  7394. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7395. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7396. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7397. if ($model === 'deepseek-chat') {
  7398. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7399. $model = 'deepseek-v4-flash';
  7400. $thinkingMode = 'disabled';
  7401. } elseif ($model === 'deepseek-reasoner') {
  7402. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7403. $model = 'deepseek-v4-flash';
  7404. $thinkingMode = 'enabled';
  7405. }
  7406. $post_data = [
  7407. 'model' => $model,
  7408. 'messages' => $messages,
  7409. // 'max_tokens' => 8192,
  7410. 'temperature' => 0.2,
  7411. 'frequency_penalty' => 0,
  7412. 'presence_penalty' => 0,
  7413. 'response_format' => ['type' => 'text'],
  7414. 'thinking' => ['type' => $thinkingMode],
  7415. 'stream' => true // 启用流式输出
  7416. ];
  7417. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7418. // 根据模型类型选择调用方法
  7419. $fullContent = '';
  7420. $fullReasoningContent = '';
  7421. $usage = [];
  7422. try {
  7423. $streamGenerator = $this->dispatchStreamByModel($post_data);
  7424. // 验证返回值类型
  7425. if (!is_iterable($streamGenerator)) {
  7426. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7427. dLog('deepseek')->error('chat流式生成器无效', [
  7428. 'generator_type' => $errorType,
  7429. 'model' => $model,
  7430. 'anime_id' => $anime_id,
  7431. 'episode_number' => $episode_number
  7432. ]);
  7433. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7434. 'type' => $errorType,
  7435. 'model' => $model
  7436. ]);
  7437. yield [
  7438. 'type' => 'error',
  7439. 'episode' => [],
  7440. 'answer' => '',
  7441. 'reasoning' => '',
  7442. 'usage' => [],
  7443. 'error' => '接口返回数据异常,请重新请求'
  7444. ];
  7445. return;
  7446. }
  7447. // 处理流式输出
  7448. foreach ($streamGenerator as $chunk) {
  7449. if (isset($chunk['type'])) {
  7450. if ($chunk['type'] === 'done') {
  7451. // 最终结果
  7452. $fullContent = $chunk['full_content'];
  7453. $fullReasoningContent = $chunk['full_reasoning'];
  7454. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7455. } else {
  7456. // 逐块yield数据
  7457. yield $chunk;
  7458. }
  7459. }
  7460. }
  7461. } catch (\Exception $e) {
  7462. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7463. 'model' => $model,
  7464. 'anime_id' => $anime_id,
  7465. 'episode_number' => $episode_number,
  7466. 'trace' => $e->getTraceAsString()
  7467. ]);
  7468. logDB('deepseek', 'error', 'chat流式处理失败', [
  7469. 'error' => $e->getMessage(),
  7470. 'model' => $model
  7471. ]);
  7472. yield [
  7473. 'type' => 'error',
  7474. 'episode' => [],
  7475. 'answer' => '',
  7476. 'reasoning' => '',
  7477. 'usage' => [],
  7478. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7479. ];
  7480. return;
  7481. }
  7482. dLog('deepseek')->info('完整内容: '.$fullContent);
  7483. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7484. // 处理完整内容并返回最终结果
  7485. $episode_arr = handleEpisodeContent($fullContent);
  7486. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7487. if (empty($episode_arr['acts'])) {
  7488. // 未生成剧本相关内容,保存对话记录并返回提示
  7489. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  7490. try {
  7491. $now = date('Y-m-d H:i:s');
  7492. // 保存对话记录
  7493. $records = [
  7494. [
  7495. 'uid' => $uid,
  7496. 'anime_id' => $anime_id,
  7497. 'sequence' => $episode_number,
  7498. 'role' => 'user',
  7499. 'content' => $prompt,
  7500. 'created_at' => $now,
  7501. 'updated_at' => $now
  7502. ],
  7503. [
  7504. 'uid' => $uid,
  7505. 'anime_id' => $anime_id,
  7506. 'sequence' => $episode_number,
  7507. 'role' => 'assistant',
  7508. 'content' => $fullContent,
  7509. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7510. 'created_at' => $now,
  7511. 'updated_at' => $now
  7512. ]
  7513. ];
  7514. DB::table('mp_anime_records')->insert($records);
  7515. } catch (\Exception $e) {
  7516. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7517. }
  7518. yield [
  7519. 'type' => 'done',
  7520. 'episode' => [],
  7521. 'answer' => $fullContent,
  7522. 'reasoning' => $fullReasoningContent,
  7523. 'usage' => $usage,
  7524. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  7525. ];
  7526. return;
  7527. }
  7528. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  7529. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  7530. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  7531. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  7532. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  7533. $existing_props = is_array($existing_props) ? $existing_props : [];
  7534. $now = date('Y-m-d H:i:s');
  7535. try {
  7536. DB::beginTransaction();
  7537. $saveResult = $this->saveEpisodeVersionData(
  7538. $anime_id,
  7539. $episode_number,
  7540. $episode_arr,
  7541. $existing_roles,
  7542. $existing_scenes,
  7543. $existing_props,
  7544. $current_episode,
  7545. $base_episode,
  7546. $is_regenerate_version,
  7547. $content,
  7548. $now
  7549. );
  7550. $episode = $saveResult['episode'];
  7551. $episode_id = $saveResult['episode_id'];
  7552. $merged_roles = $saveResult['merged_roles'];
  7553. $merged_scenes = $saveResult['merged_scenes'];
  7554. $merged_props = $saveResult['merged_props'];
  7555. $record_content = $origin_prompt;
  7556. if ($uploaded_content !== '') {
  7557. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  7558. }
  7559. $records = [
  7560. [
  7561. 'uid' => $uid,
  7562. 'anime_id' => $anime_id,
  7563. 'role' => 'user',
  7564. 'content' => $record_content,
  7565. 'sequence' => $episode_number,
  7566. 'episode_id' => $episode_id,
  7567. 'created_at' => $now,
  7568. 'updated_at' => $now
  7569. ],
  7570. [
  7571. 'uid' => $uid,
  7572. 'anime_id' => $anime_id,
  7573. 'role' => 'assistant',
  7574. 'content' => $fullContent,
  7575. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7576. 'sequence' => $episode_number,
  7577. 'episode_id' => $episode_id,
  7578. 'created_at' => $now,
  7579. 'updated_at' => $now
  7580. ]
  7581. ];
  7582. $boolen4 = DB::table('mp_anime_records')->insert($records);
  7583. if (!$boolen4) {
  7584. Utils::throwError('20003:对话记录保存失败');
  7585. }
  7586. // 保存模型和内容到anime表
  7587. $update_anime_data = [
  7588. 'model' => $model,
  7589. 'updated_at' => $now
  7590. ];
  7591. if ($uploaded_content) {
  7592. $update_anime_data['content'] = $uploaded_content;
  7593. }
  7594. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  7595. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7596. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7597. 'anime_id' => $anime_id,
  7598. 'episode_number' => $episode_number,
  7599. 'model' => $model,
  7600. 'source' => 'chat',
  7601. ]);
  7602. }catch (\Exception $e) {
  7603. DB::rollBack();
  7604. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7605. yield [
  7606. 'type' => 'done',
  7607. 'answer' => $fullContent,
  7608. 'reasoning' => $fullReasoningContent,
  7609. 'usage' => $usage,
  7610. 'error' => $e->getMessage(),
  7611. ];
  7612. return;
  7613. }
  7614. DB::commit();
  7615. if ($is_global_generate_pics) {
  7616. // // 批量生成全局角色图片
  7617. // $this->batchSetGlobalRoleImg([
  7618. // 'anime_id' => $anime_id,
  7619. // ], true);
  7620. // // 批量生成全局场景图片
  7621. // $this->batchSetGlobalSceneImg([
  7622. // 'anime_id' => $anime_id,
  7623. // ], true);
  7624. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7625. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7626. }
  7627. $episode['episode_id'] = $episode_id;
  7628. $episode['roles'] = $merged_roles;
  7629. $episode['scenes'] = $merged_scenes;
  7630. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  7631. yield [
  7632. 'type' => 'done',
  7633. 'episode' => $episode,
  7634. 'answer' => $fullContent,
  7635. 'reasoning' => $fullReasoningContent,
  7636. 'usage' => $usage
  7637. ];
  7638. }
  7639. public function addChatForAce($data) {
  7640. $uid = Site::getUid();
  7641. $anime_id = getProp($data, 'anime_id');
  7642. if (!$anime_id) Utils::throwError('20003:请选择对话');
  7643. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  7644. if (!$anime) Utils::throwError('20003:对话不存在');
  7645. $file = getProp($data, 'file');
  7646. $content = getProp($data, 'content', '');
  7647. $bid = getProp($data, 'bid', 0);
  7648. $script_id = getProp($data, 'script_id', 0);
  7649. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  7650. $prompt = getProp($data, 'prompt');
  7651. $is_multi = getProp($anime, 'is_multi');
  7652. $is_single = (int)$is_multi !== 1;
  7653. // 积分余额预检(仅单剧集模式收费)
  7654. if ($is_single) {
  7655. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  7656. }
  7657. $extra_products = getProp($data, 'products', []);
  7658. if (!$extra_products) {
  7659. $extra_products = getProp($anime, 'extra_products');
  7660. if ($extra_products) {
  7661. $extra_products = json_decode($extra_products, true);
  7662. }else {
  7663. $extra_products = [];
  7664. }
  7665. }else {
  7666. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7667. }
  7668. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7669. $anime_script_id = getProp($anime, 'script_id');
  7670. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  7671. $cpid = Site::getCpid();
  7672. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7673. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7674. ->where('mapping.script_id', $anime_script_id)
  7675. ->where('product.cpid', $cpid)
  7676. ->where('product.is_deleted', 0);
  7677. $mappings = $script_products_mappings->select(
  7678. 'mapping.product_id',
  7679. 'mapping.episode_number',
  7680. 'product.product_name',
  7681. 'product.type',
  7682. 'product.product',
  7683. 'product.pic_prompt',
  7684. 'product.url',
  7685. 'product.pic_task_id',
  7686. 'product.pic_task_status',
  7687. 'product.three_view_image_url'
  7688. )
  7689. ->get();
  7690. // 按 product_id 分组,合并 episode_number
  7691. $productMap = [];
  7692. foreach ($mappings as $item) {
  7693. $product_id = $item->product_id;
  7694. $product_name = $item->product_name;
  7695. // 处理product_name两边的符号
  7696. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7697. if (!isset($productMap[$product_id])) {
  7698. $productMap[$product_id] = [
  7699. 'product_id' => $product_id,
  7700. 'product_name' => $product_name,
  7701. 'type' => (int)$item->type,
  7702. 'product' => (int)$item->product,
  7703. 'pic_prompt' => $item->pic_prompt,
  7704. 'url' => $item->url,
  7705. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7706. 'pic_task_id' => $item->pic_task_id,
  7707. 'pic_task_status' => $item->pic_task_status,
  7708. 'episode_numbers' => [],
  7709. ];
  7710. }
  7711. // 添加 episode_number(去重)
  7712. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7713. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7714. }
  7715. }
  7716. // 将查询到的剧本资产合并到extra_products中
  7717. // 先构建extra_products的索引(以product_id为key,用于去重)
  7718. $extraProductsMap = [];
  7719. foreach ($extra_products as $item) {
  7720. $key = getProp($item, 'product_id');
  7721. if ($key) {
  7722. $extraProductsMap[$key] = $item;
  7723. }
  7724. }
  7725. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7726. foreach ($productMap as $product) {
  7727. $product_id = $product['product_id'];
  7728. // 如果不存在则添加(不带episode_number信息)
  7729. if (!isset($extraProductsMap[$product_id])) {
  7730. $extraProductsMap[$product_id] = [
  7731. 'product_id' => $product['product_id'],
  7732. 'product_name' => $product['product_name'],
  7733. 'type' => $product['type'],
  7734. 'product' => $product['product'],
  7735. 'pic_prompt' => $product['pic_prompt'],
  7736. 'url' => $product['url'],
  7737. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  7738. 'pic_task_id' => $product['pic_task_id'],
  7739. 'pic_task_status' => $product['pic_task_status'],
  7740. ];
  7741. }
  7742. }
  7743. // 重新赋值给extra_products
  7744. $extra_products = array_values($extraProductsMap);
  7745. }
  7746. $user_anime_name = getProp($anime, 'anime_name');
  7747. // 处理提示词
  7748. if ($prompt && $extra_products) {
  7749. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7750. foreach($extra_products as $item) {
  7751. $product_name = getProp($item, 'product_name');
  7752. if ($product_name) {
  7753. // 替换 {product_name} 为 product_name
  7754. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7755. }
  7756. }
  7757. }
  7758. // 处理文本模型
  7759. $model = getProp($data, 'model');
  7760. if (!$model) {
  7761. // 用户没有输入,从anime表获取
  7762. $model = getProp($anime, 'model');
  7763. if (!$model) {
  7764. // anime表也没有,使用默认值
  7765. $model = 'deepseek-v4-pro';
  7766. }
  7767. }
  7768. // 验证模型是否在可用模型表中
  7769. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7770. $model = 'deepseek-v4-pro';
  7771. }
  7772. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7773. if ($prompt) {
  7774. $question .= "本次修改要求如下:\n{$prompt}";
  7775. }
  7776. // if (!$file && !$content && !$bid) {
  7777. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  7778. // }
  7779. // 提取文件内容
  7780. if ($file) {
  7781. $content = $this->extractFileContent($file);
  7782. if (!$content) {
  7783. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7784. }
  7785. } elseif ($script_id) {
  7786. $content = $this->getContentByScriptId($script_id);
  7787. if (!$content) {
  7788. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7789. }
  7790. } elseif ($bid) {
  7791. $content = $this->getContentByBid($bid);
  7792. if (!$content) {
  7793. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7794. }
  7795. } elseif ($content) {
  7796. $content = filterContent($content);
  7797. } else {
  7798. $content = getProp($anime, 'content');
  7799. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7800. $need_generate_content = true;
  7801. }
  7802. }
  7803. // 美术风格
  7804. $input_art_style = getProp($data, 'art_style');
  7805. if (!$input_art_style) {
  7806. $mappedArtStyle = getProp($anime, 'art_style');
  7807. }else {
  7808. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7809. }
  7810. // 判断是否需要生成原文内容
  7811. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7812. // 如果需要生成原文内容,添加额外的要求
  7813. $content_generation_requirement = $need_generate_content
  7814. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7815. : "";
  7816. // 美术风格
  7817. if (!$mappedArtStyle) {
  7818. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7819. }else {
  7820. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7821. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7822. }else {
  7823. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7824. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7825. }
  7826. }
  7827. // 构建主体、场景和道具提示词
  7828. $extra_role_prompt = "\n";
  7829. $extra_scene_prompt = "\n";
  7830. $extra_prop_prompt = "\n";
  7831. $extra_roles = [];
  7832. $extra_scenes = [];
  7833. $extra_props = [];
  7834. $ref_products = []; // 参考资产
  7835. if ($extra_products) {
  7836. foreach($extra_products as $item) {
  7837. $product = getProp($item, 'product');
  7838. $product_name = getProp($item, 'product_name');
  7839. if ($product_name == '旁白') continue;
  7840. $ref_products[$product_name] = $item;
  7841. $pic_prompt = getProp($item, 'pic_prompt');
  7842. if ((int)$product === 1) {
  7843. // 拼接角色信息
  7844. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7845. $extra_roles[$product_name] = [
  7846. 'role' => $product_name,
  7847. 'pic_prompt' => $pic_prompt,
  7848. 'url' => getProp($item, 'url', ''),
  7849. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7850. ];
  7851. } elseif ((int)$product === 2) {
  7852. // 拼接场景信息
  7853. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7854. $extra_scenes[$product_name] = [
  7855. 'scene' => $product_name,
  7856. 'pic_prompt' => $pic_prompt,
  7857. 'url' => getProp($item, 'url', ''),
  7858. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7859. ];
  7860. } elseif ((int)$product === 3) {
  7861. // 拼接道具信息
  7862. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7863. $extra_props[$product_name] = [
  7864. 'prop' => $product_name,
  7865. 'pic_prompt' => $pic_prompt,
  7866. 'url' => getProp($item, 'url', ''),
  7867. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7868. ];
  7869. }
  7870. }
  7871. // 优化提示词,融入剧本
  7872. if (!empty(trim($extra_role_prompt))) {
  7873. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7874. }
  7875. if (!empty(trim($extra_scene_prompt))) {
  7876. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7877. }
  7878. if (!empty(trim($extra_prop_prompt))) {
  7879. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7880. }
  7881. }
  7882. if ($anime_script_id && $is_single) {
  7883. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7884. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7885. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7886. }else {
  7887. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7888. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7889. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7890. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7891. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7892. {$extra_role_prompt}";
  7893. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7894. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7895. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7896. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7897. {$extra_scene_prompt}";
  7898. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7899. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7900. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7901. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7902. {$extra_prop_prompt}";
  7903. }
  7904. $systemPrompt = $is_single
  7905. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7906. 强制要求:
  7907. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7908. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7909. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7910. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7911. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7912. 普通要求:
  7913. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7914. $role_demo
  7915. $scene_demo
  7916. $prop_demo
  7917. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7918. 5.1片段分割逻辑(优先级从高到低):
  7919. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7920. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7921. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7922. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7923. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7924. - 片段数量格式为: 片段数量:8
  7925. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7926. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7927. 5.3分镜结构:每个分镜包含以下字段:
  7928. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  7929. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7930. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7931. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7932. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7933. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7934. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7935. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7936. - 运镜:场景+画面描述+运镜
  7937. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7938. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7939. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7940. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7941. 6.《情绪-视听语言映射表》:
  7942. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7943. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7944. -----|---------|------------|----------------
  7945. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7946. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7947. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7948. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7949. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7950. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7951. -----|---------|------------|----------------
  7952. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7953. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7954. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7955. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7956. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7957. --------|---------|--------------|-------------
  7958. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7959. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7960. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7961. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7962. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7963. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7964. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7965. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7966. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7967. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7968. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7969. -----|---------|------------|------------
  7970. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7971. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7972. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7973. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7974. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7975. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7976. --------|---------|--------------|----------
  7977. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7978. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7979. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7980. 6.6 声音设计与潜意识影响 (Soundscape)
  7981. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7982. -----|---------|------------|------------------
  7983. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7984. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7985. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7986. 理论基石:
  7987. - The Five C's of Cinematography by Joseph V. Mascelli
  7988. - Film Art: An Introduction by David Bordwell
  7989. - Sight, Sound, Motion by Herbert Zettl
  7990. - Notes on the Cinematograph by Robert Bresson
  7991. \n\n
  7992. 7.{$mappedArtStyle_prompt}\n\n
  7993. 示例如下:\n
  7994. ###剧本名:西昆仑
  7995. ###故事梗概
  7996. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7997. ###剧本亮点
  7998. 亮点1:绝境奇药,生死一线
  7999. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8000. 亮点2:结拜兄妹,化解尴尬
  8001. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8002. 亮点3:纤发夺命,情愫暗涌
  8003. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8004. ###人物关系
  8005. 阿雪与梁萧之间存在兄妹之情。
  8006. ###核心矛盾
  8007. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8008. ###主体列表
  8009. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8010. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8011. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8012. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8013. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8014. 全景,正面拍摄,青年女性,亚洲人。
  8015. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8016. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8017. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8018. ###美术风格
  8019. 基础画风风格词:厚涂古风
  8020. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8021. ###场景列表
  8022. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8023. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8024. 无人物。}
  8025. ###分段剧本
  8026. 片段数量:8
  8027. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8028. ##片段1
  8029. 时长:12s
  8030. 分镜1
  8031. 出场角色:刀疤脸
  8032. 场景:边境小镇街道
  8033. 出场道具:酒杯-高脚杯
  8034. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8035. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8036. 配音台词:
  8037. 背景音效:
  8038. 分镜2
  8039. 出场角色:刀疤脸
  8040. 场景:悦来酒馆
  8041. 出场道具:酒杯-高脚杯
  8042. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8043. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8044. 配音台词:
  8045. 背景音效:
  8046. 分镜3
  8047. 出场角色:刀疤脸
  8048. 场景:悦来酒馆
  8049. 出场道具:酒杯-高脚杯
  8050. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8051. 运镜:从中景推向令牌特写。
  8052. 配音台词:
  8053. 背景音效:
  8054. 分镜4
  8055. 出场角色:刀疤脸
  8056. 场景:悦来酒馆
  8057. 出场道具:酒杯-高脚杯
  8058. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8059. 运镜:极速推向酒水溅起的瞬间。
  8060. 配音台词:
  8061. 背景音效:
  8062. 分镜5
  8063. 出场角色:刀疤脸
  8064. 场景:悦来酒馆
  8065. 出场道具:酒杯-高脚杯
  8066. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8067. 运镜:固定机位,利用倾斜构图制造压迫感。
  8068. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8069. 背景音效:
  8070. \n\n"
  8071. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8072. 强制要求:\n
  8073. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8074. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8075. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8076. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8077. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8078. 普通要求:\n
  8079. 1.剧本名(必须生成)必须与文档内容高度相关
  8080. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8081. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8082. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8083. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8084. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8085. {$extra_role_prompt}
  8086. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8087. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  8088. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8089. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8090. {$extra_scene_prompt}
  8091. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8092. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  8093. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8094. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  8095. {$extra_prop_prompt}
  8096. 5.{$mappedArtStyle_prompt}\n\n
  8097. 示例如下:\n
  8098. ###剧本名:西昆仑
  8099. ###故事梗概
  8100. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8101. ###剧本亮点
  8102. 亮点1:绝境奇药,生死一线
  8103. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8104. 亮点2:结拜兄妹,化解尴尬
  8105. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8106. 亮点3:纤发夺命,情愫暗涌
  8107. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8108. ###人物关系
  8109. 阿雪与梁萧之间存在兄妹之情。
  8110. ###核心矛盾
  8111. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8112. ###主体列表
  8113. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8114. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8115. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8116. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8117. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8118. 全景,正面拍摄,青年女性,亚洲人。
  8119. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8120. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8121. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8122. ###美术风格
  8123. 基础画风风格词:厚涂古风
  8124. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8125. ###场景列表
  8126. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8127. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8128. 无人物。}
  8129. ###道具列表
  8130. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  8131. // 构建消息
  8132. $messages = [
  8133. [
  8134. 'role' => 'system',
  8135. 'content' => $systemPrompt
  8136. ],
  8137. [
  8138. 'role' => 'user',
  8139. 'content' => "以下是文档内容:
  8140. {$content}
  8141. 用户问题:
  8142. {$question}"
  8143. ]
  8144. ];
  8145. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8146. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  8147. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8148. if ($model === 'deepseek-chat') {
  8149. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8150. $model = 'deepseek-v4-flash';
  8151. $thinkingMode = 'disabled';
  8152. } elseif ($model === 'deepseek-reasoner') {
  8153. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8154. $model = 'deepseek-v4-flash';
  8155. $thinkingMode = 'enabled';
  8156. }
  8157. $post_data = [
  8158. 'model' => $model,
  8159. 'messages' => $messages,
  8160. // 'max_tokens' => 8192,
  8161. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8162. 'frequency_penalty' => 0,
  8163. 'presence_penalty' => 0,
  8164. 'response_format' => ['type' => 'text'],
  8165. 'thinking' => ['type'=>$thinkingMode],
  8166. 'stream' => true // 启用流式输出
  8167. ];
  8168. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8169. // 根据模型类型选择调用方法
  8170. $fullContent = '';
  8171. $fullReasoningContent = '';
  8172. $usage = [];
  8173. try {
  8174. $streamGenerator = $this->dispatchStreamByModel($post_data);
  8175. // 验证返回值类型
  8176. if (!is_iterable($streamGenerator)) {
  8177. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8178. dLog('deepseek')->error('addChat流式生成器无效', [
  8179. 'generator_type' => $errorType,
  8180. 'model' => $model,
  8181. 'anime_id' => $anime_id
  8182. ]);
  8183. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  8184. 'type' => $errorType,
  8185. 'model' => $model
  8186. ]);
  8187. yield [
  8188. 'type' => 'error',
  8189. 'script' => [],
  8190. 'episode' => [],
  8191. 'answer' => '',
  8192. 'reasoning' => '',
  8193. 'usage' => [],
  8194. 'error' => '接口返回数据异常,请重新请求'
  8195. ];
  8196. return;
  8197. }
  8198. // 处理流式输出
  8199. foreach ($streamGenerator as $chunk) {
  8200. if (isset($chunk['type'])) {
  8201. if ($chunk['type'] === 'done') {
  8202. // 最终结果
  8203. $fullContent = $chunk['full_content'];
  8204. $fullReasoningContent = $chunk['full_reasoning'];
  8205. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8206. } else {
  8207. // 逐块yield数据
  8208. yield $chunk;
  8209. }
  8210. }
  8211. }
  8212. } catch (\Exception $e) {
  8213. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  8214. 'model' => $model,
  8215. 'anime_id' => $anime_id,
  8216. 'trace' => $e->getTraceAsString()
  8217. ]);
  8218. logDB('deepseek', 'error', 'addChat流式处理失败', [
  8219. 'error' => $e->getMessage(),
  8220. 'model' => $model
  8221. ]);
  8222. yield [
  8223. 'type' => 'error',
  8224. 'script' => [],
  8225. 'episode' => [],
  8226. 'answer' => '',
  8227. 'reasoning' => '',
  8228. 'usage' => [],
  8229. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8230. ];
  8231. return;
  8232. }
  8233. dLog('deepseek')->info('完整内容: '.$fullContent);
  8234. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8235. // 处理完整内容并返回最终结果
  8236. $script_arr = [];
  8237. if ($fullContent) {
  8238. $script_arr = handleScriptContentForAce($fullContent);
  8239. dLog('deepseek')->info('解析内容', $script_arr);
  8240. logDB('deepseek', 'info', '解析内容', $script_arr);
  8241. }
  8242. if (empty($script_arr['roles'])) {
  8243. // 未生成剧本相关内容,保存对话记录并返回提示
  8244. dLog('deepseek')->info('未生成剧本相关的内容');
  8245. try {
  8246. DB::beginTransaction();
  8247. $now = date('Y-m-d H:i:s');
  8248. // 保存对话记录
  8249. $records = [
  8250. [
  8251. 'uid' => $uid,
  8252. 'anime_id' => $anime_id,
  8253. 'sequence' => 0,
  8254. 'role' => 'user',
  8255. 'content' => $prompt,
  8256. 'created_at' => $now,
  8257. 'updated_at' => $now
  8258. ],
  8259. [
  8260. 'uid' => $uid,
  8261. 'anime_id' => $anime_id,
  8262. 'sequence' => 0,
  8263. 'role' => 'assistant',
  8264. // 'content' => $fullContent,
  8265. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  8266. 'created_at' => $now,
  8267. 'updated_at' => $now
  8268. ]
  8269. ];
  8270. DB::table('mp_anime_records')->insert($records);
  8271. DB::commit();
  8272. } catch (\Exception $e) {
  8273. DB::rollBack();
  8274. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8275. }
  8276. yield [
  8277. 'type' => 'done',
  8278. 'script' => [],
  8279. 'episode' => [],
  8280. 'answer' => $fullContent,
  8281. 'reasoning' => $fullReasoningContent,
  8282. 'usage' => $usage,
  8283. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  8284. ];
  8285. return;
  8286. }
  8287. // 如果需要生成原文内容,从script_arr中提取
  8288. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  8289. $content = $script_arr['content'];
  8290. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  8291. if (!$content) {
  8292. yield [
  8293. 'type' => 'done',
  8294. 'script' => [],
  8295. 'episode' => [],
  8296. 'answer' => $fullContent,
  8297. 'reasoning' => $fullReasoningContent,
  8298. 'usage' => $usage,
  8299. 'error' => '未生成剧本内容,请调整提示词再试'
  8300. ];
  8301. return;
  8302. }
  8303. }
  8304. // 替换美术风格
  8305. if ($mappedArtStyle !== '') {
  8306. $script_arr['art_style'] = $mappedArtStyle;
  8307. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8308. }
  8309. // 新建动漫
  8310. if ($user_anime_name == '新剧本策划') {
  8311. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  8312. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  8313. // if (!$anime_name) {
  8314. // // 未识别到剧本名,保存对话记录并返回提示
  8315. // dLog('deepseek')->info('未能识别到剧本名称');
  8316. // try {
  8317. // DB::beginTransaction();
  8318. // $now = date('Y-m-d H:i:s');
  8319. // // 保存对话记录
  8320. // $records = [
  8321. // [
  8322. // 'uid' => $uid,
  8323. // 'anime_id' => $anime_id,
  8324. // 'sequence' => 0,
  8325. // 'role' => 'user',
  8326. // 'content' => $prompt,
  8327. // 'created_at' => $now,
  8328. // 'updated_at' => $now
  8329. // ],
  8330. // [
  8331. // 'uid' => $uid,
  8332. // 'anime_id' => $anime_id,
  8333. // 'sequence' => 0,
  8334. // 'role' => 'assistant',
  8335. // 'content' => '未能生成剧本名称,请重试',
  8336. // 'created_at' => $now,
  8337. // 'updated_at' => $now
  8338. // ]
  8339. // ];
  8340. // DB::table('mp_anime_records')->insert($records);
  8341. // DB::commit();
  8342. // } catch (\Exception $e) {
  8343. // DB::rollBack();
  8344. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8345. // }
  8346. // yield [
  8347. // 'type' => 'done',
  8348. // 'script' => [],
  8349. // 'episode' => [],
  8350. // 'answer' => $fullContent,
  8351. // 'reasoning' => $fullReasoningContent,
  8352. // 'usage' => $usage,
  8353. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  8354. // ];
  8355. // return;
  8356. // }
  8357. // 确认对话名称唯一性
  8358. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  8359. $anime_name = $anime_name . '_' . date('YmdHis');
  8360. }
  8361. }else {
  8362. $anime_name = $user_anime_name;
  8363. }
  8364. // 单剧集模式:按 chatForAce 逻辑校验并重试生成剧集与分段剧本
  8365. if ($is_single) {
  8366. $max_retries = 3;
  8367. $retry_count = 0;
  8368. $validation_failed = false;
  8369. $validation_error_msg = '';
  8370. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8371. // 首次校验
  8372. if ($anime_script_id) {
  8373. if (empty($episode_arr['acts'])) {
  8374. $validation_failed = true;
  8375. $validation_error_msg = '未生成分镜剧本相关的内容';
  8376. } else {
  8377. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8378. $generated_roles = array_filter($generated_roles, function($role) {
  8379. return $role !== '旁白';
  8380. });
  8381. if (empty($generated_roles)) {
  8382. $validation_failed = true;
  8383. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8384. }
  8385. if (!$validation_failed && !empty($extra_roles)) {
  8386. $expected_roles = array_keys($extra_roles);
  8387. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8388. if (!empty($invalid_roles)) {
  8389. $validation_failed = true;
  8390. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8391. }
  8392. }
  8393. if (!$validation_failed && !empty($extra_scenes)) {
  8394. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  8395. $expected_scenes = array_keys($extra_scenes);
  8396. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8397. if (!empty($invalid_scenes)) {
  8398. $validation_failed = true;
  8399. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8400. }
  8401. }
  8402. if (!$validation_failed && !empty($extra_props)) {
  8403. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8404. $expected_props = array_keys($extra_props);
  8405. $invalid_props = array_diff($generated_props, $expected_props);
  8406. if (!empty($invalid_props)) {
  8407. $validation_failed = true;
  8408. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8409. }
  8410. }
  8411. }
  8412. } else {
  8413. if (empty($episode_arr['acts'])) {
  8414. $validation_failed = true;
  8415. $validation_error_msg = '未生成分镜剧本相关的内容';
  8416. } else {
  8417. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8418. $generated_roles = array_filter($generated_roles, function($role) {
  8419. return $role !== '旁白';
  8420. });
  8421. if (empty($generated_roles)) {
  8422. $validation_failed = true;
  8423. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8424. }
  8425. }
  8426. }
  8427. // 重试循环
  8428. while ($validation_failed && $retry_count < $max_retries) {
  8429. $retry_count++;
  8430. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  8431. 'reason' => $validation_error_msg,
  8432. 'anime_id' => $anime_id,
  8433. 'episode_number' => 1
  8434. ]);
  8435. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  8436. 'reason' => $validation_error_msg,
  8437. 'anime_id' => $anime_id
  8438. ]);
  8439. yield [
  8440. 'type' => 'retry',
  8441. 'retry_count' => $retry_count,
  8442. 'reason' => $validation_error_msg
  8443. ];
  8444. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  8445. if ($anime_script_id) {
  8446. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  8447. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  8448. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  8449. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  8450. } else {
  8451. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  8452. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  8453. }
  8454. $messages[] = [
  8455. 'role' => 'assistant',
  8456. 'content' => $fullContent
  8457. ];
  8458. $messages[] = [
  8459. 'role' => 'user',
  8460. 'content' => $retry_prompt
  8461. ];
  8462. $post_data['messages'] = $messages;
  8463. try {
  8464. $streamGenerator = $this->dispatchStreamByModel($post_data);
  8465. $fullContent = '';
  8466. $fullReasoningContent = '';
  8467. foreach ($streamGenerator as $chunk) {
  8468. if (isset($chunk['type'])) {
  8469. if ($chunk['type'] === 'done') {
  8470. $fullContent = $chunk['full_content'];
  8471. $fullReasoningContent = $chunk['full_reasoning'];
  8472. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8473. } else {
  8474. yield $chunk;
  8475. }
  8476. }
  8477. }
  8478. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  8479. // 重试接口未返回有效内容时直接失败,避免空内容被兼容放行后保存
  8480. if ($fullContent === '') {
  8481. dLog('deepseek')->error("第{$retry_count}次重试接口未返回有效内容");
  8482. yield [
  8483. 'type' => 'done',
  8484. 'script' => [],
  8485. 'episode' => [],
  8486. 'answer' => '',
  8487. 'reasoning' => $fullReasoningContent,
  8488. 'usage' => $usage,
  8489. 'error' => '生成接口未返回有效内容,请稍后重试'
  8490. ];
  8491. return;
  8492. }
  8493. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  8494. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  8495. $script_arr = handleScriptContentForAce($fullContent);
  8496. if ($mappedArtStyle !== '') {
  8497. $script_arr['art_style'] = $mappedArtStyle;
  8498. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8499. }
  8500. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8501. $validation_failed = false;
  8502. $validation_error_msg = '';
  8503. if ($anime_script_id) {
  8504. if (empty($episode_arr['acts'])) {
  8505. $validation_failed = true;
  8506. $validation_error_msg = '未生成分镜剧本相关的内容';
  8507. } else {
  8508. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8509. $generated_roles = array_filter($generated_roles, function($role) {
  8510. return $role !== '旁白';
  8511. });
  8512. if (empty($generated_roles)) {
  8513. $validation_failed = true;
  8514. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8515. }
  8516. if (!$validation_failed && !empty($extra_roles)) {
  8517. $expected_roles = array_keys($extra_roles);
  8518. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8519. if (!empty($invalid_roles)) {
  8520. $validation_failed = true;
  8521. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8522. }
  8523. }
  8524. if (!$validation_failed && !empty($extra_scenes)) {
  8525. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  8526. $expected_scenes = array_keys($extra_scenes);
  8527. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8528. if (!empty($invalid_scenes)) {
  8529. $validation_failed = true;
  8530. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8531. }
  8532. }
  8533. if (!$validation_failed && !empty($extra_props)) {
  8534. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8535. $expected_props = array_keys($extra_props);
  8536. $invalid_props = array_diff($generated_props, $expected_props);
  8537. if (!empty($invalid_props)) {
  8538. $validation_failed = true;
  8539. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8540. }
  8541. }
  8542. }
  8543. } else {
  8544. if (empty($episode_arr['acts'])) {
  8545. $validation_failed = true;
  8546. $validation_error_msg = '未生成分镜剧本相关的内容';
  8547. } else {
  8548. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8549. $generated_roles = array_filter($generated_roles, function($role) {
  8550. return $role !== '旁白';
  8551. });
  8552. if (empty($generated_roles)) {
  8553. $validation_failed = true;
  8554. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8555. }
  8556. }
  8557. }
  8558. } catch (\Exception $e) {
  8559. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  8560. 'trace' => $e->getTraceAsString()
  8561. ]);
  8562. break;
  8563. }
  8564. }
  8565. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存
  8566. if ($validation_failed && $retry_count >= $max_retries) {
  8567. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  8568. 'retry_count' => $retry_count,
  8569. 'last_error' => $validation_error_msg
  8570. ]);
  8571. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  8572. 'error' => $validation_error_msg,
  8573. 'anime_id' => $anime_id
  8574. ]);
  8575. $validation_failed = false;
  8576. $validation_error_msg = '';
  8577. }
  8578. // 如果重试后仍然失败
  8579. if ($validation_failed) {
  8580. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  8581. 'retry_count' => $retry_count,
  8582. 'last_error' => $validation_error_msg
  8583. ]);
  8584. try {
  8585. $now = date('Y-m-d H:i:s');
  8586. $records = [
  8587. [
  8588. 'uid' => $uid,
  8589. 'anime_id' => $anime_id,
  8590. 'sequence' => 1,
  8591. 'role' => 'user',
  8592. 'content' => $prompt,
  8593. 'created_at' => $now,
  8594. 'updated_at' => $now
  8595. ],
  8596. [
  8597. 'uid' => $uid,
  8598. 'anime_id' => $anime_id,
  8599. 'sequence' => 1,
  8600. 'role' => 'assistant',
  8601. 'content' => $fullContent,
  8602. 'created_at' => $now,
  8603. 'updated_at' => $now
  8604. ]
  8605. ];
  8606. DB::table('mp_anime_records')->insert($records);
  8607. } catch (\Exception $e) {
  8608. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8609. }
  8610. yield [
  8611. 'type' => 'done',
  8612. 'script' => [],
  8613. 'episode' => [],
  8614. 'answer' => $fullContent,
  8615. 'reasoning' => $fullReasoningContent,
  8616. 'usage' => $usage,
  8617. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  8618. ];
  8619. return;
  8620. }
  8621. // 验证成功,记录日志
  8622. if ($retry_count > 0) {
  8623. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  8624. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  8625. }
  8626. }
  8627. $table_data = [
  8628. 'user_id' => $uid,
  8629. 'anime_name' => $anime_name,
  8630. 'model' => $model,
  8631. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  8632. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  8633. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  8634. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  8635. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  8636. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  8637. 'art_style_type' => $input_art_style,
  8638. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  8639. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  8640. 'status' => '解析完成',
  8641. 'content' => $content,
  8642. 'is_multi' => $is_multi,
  8643. 'ace_mode' => $ace_mode,
  8644. 'generate_status' => '待执行',
  8645. 'updated_at' => date('Y-m-d H:i:s')
  8646. ];
  8647. if ($table_data['content']) {
  8648. $chapters = splitContent($table_data['content']);
  8649. $chapter_count = count($chapters);
  8650. if ($chapter_count > 0) {
  8651. $table_data['start_episode_sequence'] = 1;
  8652. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  8653. }
  8654. }
  8655. if ($extra_products) {
  8656. $table_data['extra_products'] = json_encode($extra_products, 256);
  8657. }
  8658. // 如果有剧本ID则进行绑定
  8659. if ($script_id) {
  8660. $table_data['script_id'] = $script_id;
  8661. }
  8662. $single_episode = [];
  8663. try {
  8664. DB::beginTransaction();
  8665. $now = date('Y-m-d H:i:s');
  8666. // 更新动漫大纲
  8667. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  8668. if (!$boolen) {
  8669. dLog('deepseek')->info('动漫保存失败', $table_data);
  8670. Utils::throwError('20003:动漫保存失败');
  8671. }
  8672. // 保存对话记录
  8673. $records = [
  8674. [
  8675. 'uid' => $uid,
  8676. 'anime_id' => $anime_id,
  8677. 'sequence' => 0,
  8678. 'role' => 'user',
  8679. 'content' => $prompt,
  8680. 'created_at' => date('Y-m-d H:i:s'),
  8681. 'updated_at' => date('Y-m-d H:i:s')
  8682. ],
  8683. [
  8684. 'uid' => $uid,
  8685. 'anime_id' => $anime_id,
  8686. 'sequence' => 0,
  8687. 'role' => 'assistant',
  8688. 'content' => $fullContent,
  8689. 'created_at' => date('Y-m-d H:i:s'),
  8690. 'updated_at' => date('Y-m-d H:i:s')
  8691. ]
  8692. ];
  8693. // 保存对话记录
  8694. $boolen3 = DB::table('mp_anime_records')->insert($records);
  8695. if (!$boolen3) {
  8696. Utils::throwError('20003:对话记录保存失败');
  8697. }
  8698. if ($is_single) {
  8699. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8700. if (empty($episode_arr['acts'])) {
  8701. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  8702. }
  8703. $saveResult = $this->saveEpisodeVersionData(
  8704. $anime_id,
  8705. 1,
  8706. $episode_arr,
  8707. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8708. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8709. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  8710. null,
  8711. null,
  8712. false,
  8713. $content,
  8714. $now,
  8715. $ref_products
  8716. );
  8717. $single_episode = $saveResult['episode'];
  8718. $episode_id = $saveResult['episode_id'];
  8719. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  8720. 'roles' => json_encode($saveResult['merged_roles'], 256),
  8721. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  8722. 'props' => json_encode($saveResult['merged_props'], 256),
  8723. 'updated_at' => $now
  8724. ]);
  8725. if ($boolen5 === false) {
  8726. Utils::throwError('20003:单剧集主表资源同步失败');
  8727. }
  8728. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  8729. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  8730. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  8731. $episode_record_content = '确认分镜大纲';
  8732. if ($content !== '') {
  8733. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  8734. }
  8735. $episode_records = [
  8736. [
  8737. 'uid' => $uid,
  8738. 'anime_id' => $anime_id,
  8739. 'role' => 'user',
  8740. 'content' => $episode_record_content,
  8741. 'sequence' => 1,
  8742. 'episode_id' => $episode_id,
  8743. 'created_at' => $now,
  8744. 'updated_at' => $now
  8745. ],
  8746. [
  8747. 'uid' => $uid,
  8748. 'anime_id' => $anime_id,
  8749. 'role' => 'assistant',
  8750. 'content' => $fullContent,
  8751. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8752. 'sequence' => 1,
  8753. 'episode_id' => $episode_id,
  8754. 'created_at' => $now,
  8755. 'updated_at' => $now
  8756. ]
  8757. ];
  8758. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  8759. if (!$boolen4) {
  8760. Utils::throwError('20003:单剧集分镜记录保存失败');
  8761. }
  8762. }
  8763. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8764. if ($is_single && !empty($single_episode)) {
  8765. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8766. 'anime_id' => $anime_id,
  8767. 'episode_id' => $episode_id ?? 0,
  8768. 'model' => $model,
  8769. 'source' => 'addChatForAce',
  8770. ]);
  8771. }
  8772. }catch (\Exception $e) {
  8773. DB::rollBack();
  8774. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  8775. yield [
  8776. 'type' => 'done',
  8777. 'answer' => $fullContent,
  8778. 'reasoning' => $fullReasoningContent,
  8779. 'usage' => $usage,
  8780. 'error' => $e->getMessage(),
  8781. ];
  8782. return;
  8783. }
  8784. DB::commit();
  8785. dLog('deepseek')->info('保存完毕');
  8786. if ($is_single && !empty($single_episode)) {
  8787. // $this->batchSetGlobalRoleImg([
  8788. // 'anime_id' => $anime_id,
  8789. // ]);
  8790. // $this->batchSetGlobalSceneImg([
  8791. // 'anime_id' => $anime_id,
  8792. // ]);
  8793. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8794. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8795. }
  8796. $table_data['anime_id'] = $anime_id;
  8797. $table_data['roles'] = json_decode($table_data['roles'], true);
  8798. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8799. // $table_data['episodes'] = $script_arr['episodes'];
  8800. unset($table_data['created_at']);
  8801. unset($table_data['updated_at']);
  8802. unset($table_data['status']);
  8803. dLog('deepseek')->info('开始返回');
  8804. yield [
  8805. 'type' => 'done',
  8806. 'script' => $table_data,
  8807. 'episode' => $single_episode,
  8808. 'answer' => $fullContent,
  8809. 'reasoning' => $fullReasoningContent,
  8810. 'usage' => $usage
  8811. ];
  8812. }
  8813. public function reGenerateAnimeForAce($data) {
  8814. $uid = Site::getUid();
  8815. $file = getProp($data, 'file');
  8816. $content = getProp($data, 'content', '');
  8817. $bid = getProp($data, 'bid', 0);
  8818. $script_id = getProp($data, 'script_id', 0);
  8819. $anime_id = getProp($data, 'anime_id');
  8820. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8821. if (!$anime) {
  8822. Utils::throwError('20003:该对话不存在');
  8823. }
  8824. $is_multi = getProp($anime, 'is_multi', 1);
  8825. $is_single = (int)$is_multi !== 1;
  8826. // 积分余额预检(仅单剧集模式收费)
  8827. if ($is_single) {
  8828. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  8829. }
  8830. $extra_products = getProp($data, 'products', []);
  8831. if (!$extra_products) {
  8832. $extra_products = getProp($anime, 'extra_products');
  8833. if ($extra_products) {
  8834. $extra_products = json_decode($extra_products, true);
  8835. }else {
  8836. $extra_products = [];
  8837. }
  8838. }else {
  8839. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  8840. }
  8841. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  8842. $anime_script_id = getProp($anime, 'script_id');
  8843. if ($anime_script_id && $is_single) {
  8844. $cpid = Site::getCpid();
  8845. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  8846. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8847. ->where('mapping.script_id', $anime_script_id)
  8848. ->where('product.cpid', $cpid)
  8849. ->where('product.is_deleted', 0);
  8850. $mappings = $script_products_mappings->select(
  8851. 'mapping.product_id',
  8852. 'mapping.episode_number',
  8853. 'product.product_name',
  8854. 'product.type',
  8855. 'product.product',
  8856. 'product.pic_prompt',
  8857. 'product.url',
  8858. 'product.pic_task_id',
  8859. 'product.pic_task_status',
  8860. 'product.three_view_image_url'
  8861. )
  8862. ->get();
  8863. // 按 product_id 分组,合并 episode_number
  8864. $productMap = [];
  8865. foreach ($mappings as $item) {
  8866. $product_id = $item->product_id;
  8867. $product_name = $item->product_name;
  8868. // 处理product_name两边的符号
  8869. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8870. if (!isset($productMap[$product_id])) {
  8871. $productMap[$product_id] = [
  8872. 'product_id' => $product_id,
  8873. 'product_name' => $product_name,
  8874. 'type' => (int)$item->type,
  8875. 'product' => (int)$item->product,
  8876. 'pic_prompt' => $item->pic_prompt,
  8877. 'url' => $item->url,
  8878. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  8879. 'pic_task_id' => $item->pic_task_id,
  8880. 'pic_task_status' => $item->pic_task_status,
  8881. 'episode_numbers' => [],
  8882. ];
  8883. }
  8884. // 添加 episode_number(去重)
  8885. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8886. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8887. }
  8888. }
  8889. // 将查询到的剧本资产合并到extra_products中
  8890. // 先构建extra_products的索引(以product_id为key,用于去重)
  8891. $extraProductsMap = [];
  8892. foreach ($extra_products as $item) {
  8893. $key = getProp($item, 'product_id');
  8894. if ($key) {
  8895. $extraProductsMap[$key] = $item;
  8896. }
  8897. }
  8898. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  8899. foreach ($productMap as $product) {
  8900. $product_id = $product['product_id'];
  8901. // 如果不存在则添加(不带episode_number信息)
  8902. if (!isset($extraProductsMap[$product_id])) {
  8903. $extraProductsMap[$product_id] = [
  8904. 'product_id' => $product['product_id'],
  8905. 'product_name' => $product['product_name'],
  8906. 'type' => $product['type'],
  8907. 'product' => $product['product'],
  8908. 'pic_prompt' => $product['pic_prompt'],
  8909. 'url' => $product['url'],
  8910. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  8911. 'pic_task_id' => $product['pic_task_id'],
  8912. 'pic_task_status' => $product['pic_task_status'],
  8913. ];
  8914. }
  8915. }
  8916. // 重新赋值给extra_products
  8917. $extra_products = array_values($extraProductsMap);
  8918. }
  8919. $user_anime_name = getProp($anime, 'anime_name');
  8920. $prompt = getProp($data, 'prompt');
  8921. // 处理提示词
  8922. if ($prompt && $extra_products) {
  8923. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8924. foreach($extra_products as $item) {
  8925. $product_name = getProp($item, 'product_name');
  8926. if ($product_name) {
  8927. // 替换 {product_name} 为 product_name
  8928. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8929. }
  8930. }
  8931. }
  8932. // 处理文本模型
  8933. $model = getProp($data, 'model');
  8934. if (!$model) {
  8935. // 用户没有输入,从anime表获取
  8936. $model = getProp($anime, 'model');
  8937. if (!$model) {
  8938. // anime表也没有,使用默认值
  8939. $model = 'deepseek-v4-pro';
  8940. }
  8941. }
  8942. // 验证模型是否在可用模型表中
  8943. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8944. $model = 'deepseek-v4-pro';
  8945. }
  8946. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  8947. if ($is_single) {
  8948. $episode_exists = DB::table('mp_anime_episodes')
  8949. ->where('anime_id', $anime_id)
  8950. ->where('sequence', 1)
  8951. ->exists();
  8952. if ($episode_exists) {
  8953. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  8954. }
  8955. }
  8956. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  8957. if ($prompt) {
  8958. $question .= "本次修改要求如下:\n{$prompt}";
  8959. }
  8960. // 提取文件内容
  8961. if ($file) {
  8962. $content = $this->extractFileContent($file);
  8963. if (!$content) {
  8964. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8965. }
  8966. } elseif ($script_id) {
  8967. $content = $this->getContentByScriptId($script_id);
  8968. if (!$content) {
  8969. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  8970. }
  8971. } elseif ($bid) {
  8972. $content = $this->getContentByBid($bid);
  8973. if (!$content) {
  8974. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  8975. }
  8976. } elseif ($content) {
  8977. $content = filterContent($content);
  8978. }else {
  8979. $content = filterContent(getProp($anime, 'content'));
  8980. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  8981. $need_generate_content = true;
  8982. }
  8983. }
  8984. // 判断是否需要生成原文内容
  8985. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  8986. // 如果需要生成原文内容,添加额外的要求
  8987. $content_generation_requirement = $need_generate_content
  8988. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  8989. : "";
  8990. // 美术风格
  8991. $input_art_style = getProp($data, 'art_style');
  8992. if (!$input_art_style) {
  8993. $mappedArtStyle = getProp($anime, 'art_style');
  8994. }else {
  8995. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  8996. }
  8997. if (!$mappedArtStyle) {
  8998. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  8999. }else {
  9000. if (strstr($mappedArtStyle, '基础画风风格词')) {
  9001. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  9002. }else {
  9003. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  9004. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  9005. }
  9006. }
  9007. // 构建主体、场景和道具提示词
  9008. $extra_role_prompt = "\n";
  9009. $extra_scene_prompt = "\n";
  9010. $extra_prop_prompt = "\n";
  9011. $extra_roles = [];
  9012. $extra_scenes = [];
  9013. $extra_props = [];
  9014. $ref_products = []; // 参考资产
  9015. if ($extra_products) {
  9016. foreach($extra_products as $item) {
  9017. $product = getProp($item, 'product');
  9018. $product_name = getProp($item, 'product_name');
  9019. if ($product_name == '旁白') continue;
  9020. $ref_products[$product_name] = $item;
  9021. $pic_prompt = getProp($item, 'pic_prompt');
  9022. if ((int)$product === 1) {
  9023. // 拼接角色信息
  9024. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9025. $extra_roles[$product_name] = [
  9026. 'role' => $product_name,
  9027. 'pic_prompt' => $pic_prompt,
  9028. 'url' => getProp($item, 'url', ''),
  9029. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9030. ];
  9031. } elseif ((int)$product === 2) {
  9032. // 拼接场景信息
  9033. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9034. $extra_scenes[$product_name] = [
  9035. 'scene' => $product_name,
  9036. 'pic_prompt' => $pic_prompt,
  9037. 'url' => getProp($item, 'url', ''),
  9038. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9039. ];
  9040. } elseif ((int)$product === 3) {
  9041. // 拼接道具信息
  9042. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9043. $extra_props[$product_name] = [
  9044. 'prop' => $product_name,
  9045. 'pic_prompt' => $pic_prompt,
  9046. 'url' => getProp($item, 'url', ''),
  9047. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9048. ];
  9049. }
  9050. }
  9051. // 优化提示词,融入剧本
  9052. if (!empty(trim($extra_role_prompt))) {
  9053. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  9054. }
  9055. if (!empty(trim($extra_scene_prompt))) {
  9056. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  9057. }
  9058. if (!empty(trim($extra_prop_prompt))) {
  9059. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  9060. }
  9061. }
  9062. if ($anime_script_id && $is_single) {
  9063. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  9064. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  9065. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  9066. }else {
  9067. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  9068. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9069. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  9070. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9071. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9072. {$extra_role_prompt}";
  9073. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9074. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  9075. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9076. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  9077. {$extra_scene_prompt}";
  9078. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9079. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  9080. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  9081. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  9082. {$extra_prop_prompt}";
  9083. }
  9084. $system_message = ['role'=>'system', 'content'=>$is_single
  9085. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  9086. 强制要求:
  9087. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9088. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9089. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9090. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9091. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9092. 普通要求:
  9093. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  9094. $role_demo
  9095. $scene_demo
  9096. $prop_demo
  9097. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9098. 5.1片段分割逻辑(优先级从高到低):
  9099. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9100. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9101. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9102. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9103. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9104. - 片段数量格式为: 片段数量:8
  9105. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9106. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9107. 5.3分镜结构:每个分镜包含以下字段:
  9108. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  9109. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  9110. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9111. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9112. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9113. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9114. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9115. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9116. - 运镜:场景+画面描述+运镜
  9117. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  9118. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  9119. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9120. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  9121. 6.《情绪-视听语言映射表》:
  9122. 6.1 场景空间与时间心理学 (Scene & Temporality)
  9123. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9124. -----|---------|------------|----------------
  9125. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  9126. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  9127. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  9128. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  9129. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  9130. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9131. -----|---------|------------|----------------
  9132. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  9133. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  9134. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  9135. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  9136. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  9137. --------|---------|--------------|-------------
  9138. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  9139. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  9140. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  9141. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  9142. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  9143. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  9144. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  9145. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  9146. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  9147. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  9148. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  9149. -----|---------|------------|------------
  9150. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  9151. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  9152. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  9153. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  9154. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  9155. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  9156. --------|---------|--------------|----------
  9157. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  9158. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  9159. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  9160. 6.6 声音设计与潜意识影响 (Soundscape)
  9161. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  9162. -----|---------|------------|------------------
  9163. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  9164. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  9165. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  9166. 理论基石:
  9167. - The Five C's of Cinematography by Joseph V. Mascelli
  9168. - Film Art: An Introduction by David Bordwell
  9169. - Sight, Sound, Motion by Herbert Zettl
  9170. - Notes on the Cinematograph by Robert Bresson
  9171. \n\n
  9172. 7.{$mappedArtStyle_prompt}\n\n
  9173. 示例如下:\n
  9174. ###剧本名:西昆仑
  9175. ###故事梗概
  9176. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9177. ###剧本亮点
  9178. 亮点1:绝境奇药,生死一线
  9179. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9180. 亮点2:结拜兄妹,化解尴尬
  9181. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9182. 亮点3:纤发夺命,情愫暗涌
  9183. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9184. ###人物关系
  9185. 阿雪与梁萧之间存在兄妹之情。
  9186. ###核心矛盾
  9187. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9188. ###主体列表
  9189. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9190. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9191. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9192. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9193. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9194. 全景,正面拍摄,青年女性,亚洲人。
  9195. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9196. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9197. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9198. ###美术风格
  9199. 基础画风风格词:厚涂古风
  9200. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9201. ###场景列表
  9202. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9203. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9204. 无人物。}
  9205. ###分段剧本
  9206. 片段数量:8
  9207. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9208. ##片段1
  9209. 时长:12s
  9210. 分镜1
  9211. 出场角色:刀疤脸
  9212. 场景:边境小镇街道
  9213. 出场道具:酒杯-高脚杯
  9214. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9215. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9216. 配音台词:
  9217. 背景音效:
  9218. 分镜2
  9219. 出场角色:刀疤脸
  9220. 场景:悦来酒馆
  9221. 出场道具:酒杯-高脚杯
  9222. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9223. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9224. 配音台词:
  9225. 背景音效:
  9226. 分镜3
  9227. 出场角色:刀疤脸
  9228. 场景:悦来酒馆
  9229. 出场道具:酒杯-高脚杯
  9230. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9231. 运镜:从中景推向令牌特写。
  9232. 配音台词:
  9233. 背景音效:
  9234. 分镜4
  9235. 出场角色:刀疤脸
  9236. 场景:悦来酒馆
  9237. 出场道具:酒杯-高脚杯
  9238. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9239. 运镜:极速推向酒水溅起的瞬间。
  9240. 配音台词:
  9241. 背景音效:
  9242. 分镜5
  9243. 出场角色:刀疤脸
  9244. 场景:悦来酒馆
  9245. 出场道具:酒杯-高脚杯
  9246. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9247. 运镜:固定机位,利用倾斜构图制造压迫感。
  9248. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9249. 背景音效:
  9250. \n\n"
  9251. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  9252. 强制要求:\n
  9253. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9254. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9255. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9256. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9257. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9258. 普通要求:\n
  9259. 1.剧本名(必须生成)必须与文档内容高度相关
  9260. $role_demo
  9261. $scene_demo
  9262. $prop_demo
  9263. 5.{$mappedArtStyle_prompt}\n\n
  9264. 示例如下:\n
  9265. ###剧本名:西昆仑
  9266. ###故事梗概
  9267. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9268. ###剧本亮点
  9269. 亮点1:绝境奇药,生死一线
  9270. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9271. 亮点2:结拜兄妹,化解尴尬
  9272. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9273. 亮点3:纤发夺命,情愫暗涌
  9274. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9275. ###人物关系
  9276. 阿雪与梁萧之间存在兄妹之情。
  9277. ###核心矛盾
  9278. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9279. ###主体列表
  9280. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9281. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9282. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9283. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9284. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9285. 全景,正面拍摄,青年女性,亚洲人。
  9286. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9287. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9288. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9289. ###美术风格
  9290. 基础画风风格词:厚涂古风
  9291. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9292. ###场景列表
  9293. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9294. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9295. 无人物。}
  9296. ###道具列表
  9297. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  9298. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  9299. $episode_count = $this->extractEpisodeNumber($prompt);
  9300. if ((int)getProp($anime, 'is_multi') !== 1) {
  9301. yield [
  9302. 'type' => 'done',
  9303. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  9304. 'reasoning' => '',
  9305. 'usage' => []
  9306. ];
  9307. return;
  9308. }
  9309. if ($episode_count) {
  9310. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  9311. $system_message = [
  9312. 'role' => 'system',
  9313. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  9314. 强制要求:\n
  9315. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9316. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9317. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9318. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9319. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9320. 普通要求:\n
  9321. 1.<故事梗概>控制在200-300字左右
  9322. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  9323. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9324. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  9325. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9326. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9327. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9328. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  9329. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9330. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  9331. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  9332. 示例如下:\n
  9333. ###剧本名:西昆仑
  9334. ###故事梗概
  9335. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9336. ###剧本亮点
  9337. 亮点1:绝境奇药,生死一线
  9338. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9339. 亮点2:结拜兄妹,化解尴尬
  9340. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9341. 亮点3:纤发夺命,情愫暗涌
  9342. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9343. ###人物关系
  9344. 阿雪与梁萧之间存在兄妹之情。
  9345. ###核心矛盾
  9346. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9347. ###主体列表
  9348. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9349. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9350. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9351. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9352. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9353. 全景,正面拍摄,青年女性,亚洲人。
  9354. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9355. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9356. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9357. ###美术风格
  9358. 基础画风风格词:厚涂古风
  9359. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9360. ###场景列表
  9361. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9362. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9363. 无人物。}
  9364. ###分集详细内容
  9365. ##第1章 重生
  9366. 我重生了。
  9367. 源于一个男人偏执的暗恋。
  9368. ##第2章 相救
  9369. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  9370. 我眼睛扫向站在锅炉后的卞大伟。"
  9371. ];
  9372. // 构建消息
  9373. $messages = [
  9374. $system_message,
  9375. [
  9376. 'role' => 'user',
  9377. 'content' => "以下是文档内容:
  9378. {$content}
  9379. 用户问题:
  9380. {$question}"
  9381. ]
  9382. ];
  9383. }else {
  9384. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  9385. // 构建消息
  9386. $messages = [
  9387. $system_message,
  9388. [
  9389. 'role' => 'user',
  9390. 'content' => "以下是文档内容:
  9391. {$content}
  9392. 用户问题:
  9393. {$question}"
  9394. ]
  9395. ];
  9396. }else {
  9397. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  9398. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  9399. return (array)$value;
  9400. })->toArray();
  9401. array_unshift($messages, $system_message);
  9402. $messages[] = [
  9403. 'role' => 'user',
  9404. 'content' => $prompt
  9405. ];
  9406. }
  9407. }
  9408. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  9409. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  9410. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  9411. if ($model === 'deepseek-chat') {
  9412. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  9413. $model = 'deepseek-v4-flash';
  9414. $thinkingMode = 'disabled';
  9415. } elseif ($model === 'deepseek-reasoner') {
  9416. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  9417. $model = 'deepseek-v4-flash';
  9418. $thinkingMode = 'enabled';
  9419. }
  9420. $post_data = [
  9421. 'model' => $model,
  9422. 'messages' => $messages,
  9423. // 'max_tokens' => 8192,
  9424. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9425. 'frequency_penalty' => 0,
  9426. 'presence_penalty' => 0,
  9427. 'response_format' => ['type' => 'text'],
  9428. 'thinking' => ['type' => $thinkingMode],
  9429. 'stream' => true // 启用流式输出
  9430. ];
  9431. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9432. // 根据模型类型选择调用方法
  9433. $fullContent = '';
  9434. $fullReasoningContent = '';
  9435. $usage = [];
  9436. // dd($post_data);
  9437. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  9438. try {
  9439. $streamGenerator = $this->dispatchStreamByModel($post_data);
  9440. // 验证返回值类型
  9441. if (!is_iterable($streamGenerator)) {
  9442. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  9443. dLog('deepseek')->error('方法名流式生成器无效', [
  9444. 'generator_type' => $errorType,
  9445. 'model' => $model,
  9446. // 添加其他上下文信息
  9447. ]);
  9448. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  9449. 'type' => $errorType,
  9450. 'model' => $model
  9451. ]);
  9452. yield [
  9453. 'type' => 'error',
  9454. // 根据方法返回相应的空数据结构
  9455. 'answer' => '',
  9456. 'reasoning' => '',
  9457. 'usage' => [],
  9458. 'error' => '接口返回数据异常,请重新请求'
  9459. ];
  9460. return;
  9461. }
  9462. // 处理流式输出
  9463. foreach ($streamGenerator as $chunk) {
  9464. if (isset($chunk['type'])) {
  9465. if ($chunk['type'] === 'done') {
  9466. $fullContent = $chunk['full_content'];
  9467. $fullReasoningContent = $chunk['full_reasoning'];
  9468. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9469. } else {
  9470. yield $chunk;
  9471. }
  9472. }
  9473. }
  9474. } catch (\Exception $e) {
  9475. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  9476. 'model' => $model,
  9477. 'trace' => $e->getTraceAsString()
  9478. ]);
  9479. logDB('deepseek', 'error', '方法名流式处理失败', [
  9480. 'error' => $e->getMessage(),
  9481. 'model' => $model
  9482. ]);
  9483. yield [
  9484. 'type' => 'error',
  9485. // 根据方法返回相应的空数据结构
  9486. 'answer' => '',
  9487. 'reasoning' => '',
  9488. 'usage' => [],
  9489. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  9490. ];
  9491. return;
  9492. }
  9493. dLog('deepseek')->info('完整内容: '.$fullContent);
  9494. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  9495. // 处理完整内容并返回最终结果
  9496. $script_arr = [];
  9497. if ($fullContent) {
  9498. $script_arr = handleScriptContentForAce($fullContent);
  9499. dLog('deepseek')->info('解析内容', $script_arr);
  9500. logDB('deepseek', 'info', '解析内容', $script_arr);
  9501. }
  9502. if (empty($script_arr['roles'])) {
  9503. // 未生成剧本相关内容,保存对话记录并返回提示
  9504. dLog('deepseek')->info('未生成剧本相关的内容');
  9505. try {
  9506. $now = date('Y-m-d H:i:s');
  9507. // 保存对话记录
  9508. $records = [
  9509. [
  9510. 'uid' => $uid,
  9511. 'anime_id' => $anime_id,
  9512. 'sequence' => 0,
  9513. 'role' => 'user',
  9514. 'content' => $prompt,
  9515. 'created_at' => $now,
  9516. 'updated_at' => $now
  9517. ],
  9518. [
  9519. 'uid' => $uid,
  9520. 'anime_id' => $anime_id,
  9521. 'sequence' => 0,
  9522. 'role' => 'assistant',
  9523. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  9524. 'created_at' => $now,
  9525. 'updated_at' => $now
  9526. ]
  9527. ];
  9528. DB::table('mp_anime_records')->insert($records);
  9529. } catch (\Exception $e) {
  9530. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9531. }
  9532. yield [
  9533. 'type' => 'done',
  9534. 'script' => [],
  9535. 'episode' => [],
  9536. 'answer' => $fullContent,
  9537. 'reasoning' => $fullReasoningContent,
  9538. 'usage' => $usage,
  9539. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  9540. ];
  9541. return;
  9542. }
  9543. // 替换美术风格
  9544. if ($mappedArtStyle !== '') {
  9545. $script_arr['art_style'] = $mappedArtStyle;
  9546. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  9547. }
  9548. if ($user_anime_name != '新剧本策划') {
  9549. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  9550. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  9551. // 确认对话名称唯一性
  9552. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  9553. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  9554. }
  9555. }else {
  9556. $anime_name = $user_anime_name;
  9557. }
  9558. // 单剧集模式:按 chatForAce 逻辑校验并重试生成剧集与分段剧本
  9559. if ($is_single) {
  9560. $max_retries = 3;
  9561. $retry_count = 0;
  9562. $validation_failed = false;
  9563. $validation_error_msg = '';
  9564. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9565. // 首次校验
  9566. if ($anime_script_id) {
  9567. if (empty($episode_arr['acts'])) {
  9568. $validation_failed = true;
  9569. $validation_error_msg = '未生成分镜剧本相关的内容';
  9570. } else {
  9571. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9572. $generated_roles = array_filter($generated_roles, function($role) {
  9573. return $role !== '旁白';
  9574. });
  9575. if (empty($generated_roles)) {
  9576. $validation_failed = true;
  9577. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9578. }
  9579. if (!$validation_failed && !empty($extra_roles)) {
  9580. $expected_roles = array_keys($extra_roles);
  9581. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9582. if (!empty($invalid_roles)) {
  9583. $validation_failed = true;
  9584. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9585. }
  9586. }
  9587. if (!$validation_failed && !empty($extra_scenes)) {
  9588. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  9589. $expected_scenes = array_keys($extra_scenes);
  9590. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9591. if (!empty($invalid_scenes)) {
  9592. $validation_failed = true;
  9593. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9594. }
  9595. }
  9596. if (!$validation_failed && !empty($extra_props)) {
  9597. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9598. $expected_props = array_keys($extra_props);
  9599. $invalid_props = array_diff($generated_props, $expected_props);
  9600. if (!empty($invalid_props)) {
  9601. $validation_failed = true;
  9602. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9603. }
  9604. }
  9605. }
  9606. } else {
  9607. if (empty($episode_arr['acts'])) {
  9608. $validation_failed = true;
  9609. $validation_error_msg = '未生成分镜剧本相关的内容';
  9610. } else {
  9611. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9612. $generated_roles = array_filter($generated_roles, function($role) {
  9613. return $role !== '旁白';
  9614. });
  9615. if (empty($generated_roles)) {
  9616. $validation_failed = true;
  9617. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9618. }
  9619. }
  9620. }
  9621. // 重试循环
  9622. while ($validation_failed && $retry_count < $max_retries) {
  9623. $retry_count++;
  9624. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  9625. 'reason' => $validation_error_msg,
  9626. 'anime_id' => $anime_id,
  9627. 'episode_number' => 1
  9628. ]);
  9629. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  9630. 'reason' => $validation_error_msg,
  9631. 'anime_id' => $anime_id
  9632. ]);
  9633. yield [
  9634. 'type' => 'retry',
  9635. 'retry_count' => $retry_count,
  9636. 'reason' => $validation_error_msg
  9637. ];
  9638. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  9639. if ($anime_script_id) {
  9640. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  9641. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9642. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  9643. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  9644. } else {
  9645. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9646. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  9647. }
  9648. $messages[] = [
  9649. 'role' => 'assistant',
  9650. 'content' => $fullContent
  9651. ];
  9652. $messages[] = [
  9653. 'role' => 'user',
  9654. 'content' => $retry_prompt
  9655. ];
  9656. $post_data['messages'] = $messages;
  9657. try {
  9658. $streamGenerator = $this->dispatchStreamByModel($post_data);
  9659. $fullContent = '';
  9660. $fullReasoningContent = '';
  9661. foreach ($streamGenerator as $chunk) {
  9662. if (isset($chunk['type'])) {
  9663. if ($chunk['type'] === 'done') {
  9664. $fullContent = $chunk['full_content'];
  9665. $fullReasoningContent = $chunk['full_reasoning'];
  9666. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9667. } else {
  9668. yield $chunk;
  9669. }
  9670. }
  9671. }
  9672. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9673. // 重试接口未返回有效内容时直接失败,避免空内容被兼容放行后保存
  9674. if ($fullContent === '') {
  9675. dLog('deepseek')->error("第{$retry_count}次重试接口未返回有效内容");
  9676. yield [
  9677. 'type' => 'done',
  9678. 'script' => [],
  9679. 'episode' => [],
  9680. 'answer' => '',
  9681. 'reasoning' => $fullReasoningContent,
  9682. 'usage' => $usage,
  9683. 'error' => '生成接口未返回有效内容,请稍后重试'
  9684. ];
  9685. return;
  9686. }
  9687. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  9688. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  9689. $script_arr = handleScriptContentForAce($fullContent);
  9690. if ($mappedArtStyle !== '') {
  9691. $script_arr['art_style'] = $mappedArtStyle;
  9692. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  9693. }
  9694. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9695. $validation_failed = false;
  9696. $validation_error_msg = '';
  9697. if ($anime_script_id) {
  9698. if (empty($episode_arr['acts'])) {
  9699. $validation_failed = true;
  9700. $validation_error_msg = '未生成分镜剧本相关的内容';
  9701. } else {
  9702. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9703. $generated_roles = array_filter($generated_roles, function($role) {
  9704. return $role !== '旁白';
  9705. });
  9706. if (empty($generated_roles)) {
  9707. $validation_failed = true;
  9708. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9709. }
  9710. if (!$validation_failed && !empty($extra_roles)) {
  9711. $expected_roles = array_keys($extra_roles);
  9712. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9713. if (!empty($invalid_roles)) {
  9714. $validation_failed = true;
  9715. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9716. }
  9717. }
  9718. if (!$validation_failed && !empty($extra_scenes)) {
  9719. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  9720. $expected_scenes = array_keys($extra_scenes);
  9721. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9722. if (!empty($invalid_scenes)) {
  9723. $validation_failed = true;
  9724. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9725. }
  9726. }
  9727. if (!$validation_failed && !empty($extra_props)) {
  9728. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9729. $expected_props = array_keys($extra_props);
  9730. $invalid_props = array_diff($generated_props, $expected_props);
  9731. if (!empty($invalid_props)) {
  9732. $validation_failed = true;
  9733. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9734. }
  9735. }
  9736. }
  9737. } else {
  9738. if (empty($episode_arr['acts'])) {
  9739. $validation_failed = true;
  9740. $validation_error_msg = '未生成分镜剧本相关的内容';
  9741. } else {
  9742. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9743. $generated_roles = array_filter($generated_roles, function($role) {
  9744. return $role !== '旁白';
  9745. });
  9746. if (empty($generated_roles)) {
  9747. $validation_failed = true;
  9748. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9749. }
  9750. }
  9751. }
  9752. } catch (\Exception $e) {
  9753. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  9754. 'trace' => $e->getTraceAsString()
  9755. ]);
  9756. break;
  9757. }
  9758. }
  9759. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存
  9760. if ($validation_failed && $retry_count >= $max_retries) {
  9761. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  9762. 'retry_count' => $retry_count,
  9763. 'last_error' => $validation_error_msg
  9764. ]);
  9765. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  9766. 'error' => $validation_error_msg,
  9767. 'anime_id' => $anime_id
  9768. ]);
  9769. $validation_failed = false;
  9770. $validation_error_msg = '';
  9771. }
  9772. // 如果重试后仍然失败
  9773. if ($validation_failed) {
  9774. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  9775. 'retry_count' => $retry_count,
  9776. 'last_error' => $validation_error_msg
  9777. ]);
  9778. try {
  9779. $now = date('Y-m-d H:i:s');
  9780. $records = [
  9781. [
  9782. 'uid' => $uid,
  9783. 'anime_id' => $anime_id,
  9784. 'sequence' => 1,
  9785. 'role' => 'user',
  9786. 'content' => $prompt,
  9787. 'created_at' => $now,
  9788. 'updated_at' => $now
  9789. ],
  9790. [
  9791. 'uid' => $uid,
  9792. 'anime_id' => $anime_id,
  9793. 'sequence' => 1,
  9794. 'role' => 'assistant',
  9795. 'content' => $fullContent,
  9796. 'created_at' => $now,
  9797. 'updated_at' => $now
  9798. ]
  9799. ];
  9800. DB::table('mp_anime_records')->insert($records);
  9801. } catch (\Exception $e) {
  9802. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9803. }
  9804. yield [
  9805. 'type' => 'done',
  9806. 'script' => [],
  9807. 'episode' => [],
  9808. 'answer' => $fullContent,
  9809. 'reasoning' => $fullReasoningContent,
  9810. 'usage' => $usage,
  9811. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  9812. ];
  9813. return;
  9814. }
  9815. // 验证成功,记录日志
  9816. if ($retry_count > 0) {
  9817. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  9818. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  9819. }
  9820. }
  9821. $table_data = [
  9822. 'user_id' => $uid,
  9823. 'model' => $model,
  9824. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  9825. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  9826. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  9827. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  9828. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  9829. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  9830. 'art_style_type' => $input_art_style,
  9831. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  9832. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  9833. 'status' => '解析完成',
  9834. 'generate_status' => '待执行',
  9835. 'updated_at' => date('Y-m-d H:i:s')
  9836. ];
  9837. if ($anime_name) $table_data['anime_name'] = $anime_name;
  9838. // 如果是修改集数,则将content内容更新(会改变原文)
  9839. if (isset($episode_count) && $episode_count > 0) {
  9840. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  9841. $table_data['start_episode_sequence'] = 1;
  9842. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  9843. }else {
  9844. // 如果需要生成原文内容,从script_arr中提取
  9845. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  9846. $table_data['content'] = $script_arr['content'];
  9847. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  9848. if (!$table_data['content']) {
  9849. yield [
  9850. 'type' => 'done',
  9851. 'script' => [],
  9852. 'episode' => [],
  9853. 'answer' => $fullContent,
  9854. 'reasoning' => $fullReasoningContent,
  9855. 'usage' => $usage,
  9856. 'error' => '未生成剧本内容,请调整提示词再试'
  9857. ];
  9858. return;
  9859. }
  9860. }
  9861. if (isset($table_data['content']) && $table_data['content']) {
  9862. $chapters = splitContent($table_data['content']);
  9863. $chapter_count = count($chapters);
  9864. if ($chapter_count > 0) {
  9865. $table_data['start_episode_sequence'] = 1;
  9866. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  9867. }
  9868. }
  9869. }
  9870. if ($extra_products) {
  9871. $table_data['extra_products'] = json_encode($extra_products, 256);
  9872. }
  9873. $single_episode = [];
  9874. try {
  9875. DB::beginTransaction();
  9876. $now = date('Y-m-d H:i:s');
  9877. // 更新动漫大纲
  9878. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  9879. if (!$boolen) {
  9880. dLog('deepseek')->info('对话修改失败', $table_data);
  9881. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  9882. Utils::throwError('20003:对话修改失败');
  9883. }
  9884. // 保存对话记录
  9885. $records = [
  9886. [
  9887. 'uid' => $uid,
  9888. 'anime_id' => $anime_id,
  9889. 'sequence' => 0,
  9890. 'role' => 'user',
  9891. 'content' => $prompt,
  9892. 'created_at' => $now,
  9893. 'updated_at' => $now
  9894. ],
  9895. [
  9896. 'uid' => $uid,
  9897. 'anime_id' => $anime_id,
  9898. 'sequence' => 0,
  9899. 'role' => 'assistant',
  9900. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  9901. 'content' => $fullContent,
  9902. 'created_at' => $now,
  9903. 'updated_at' => $now
  9904. ]
  9905. ];
  9906. // 保存对话记录
  9907. $boolen3 = DB::table('mp_anime_records')->insert($records);
  9908. if (!$boolen3) {
  9909. Utils::throwError('20003:对话记录保存失败');
  9910. }
  9911. // 单剧集模式:生成并保存剧集信息
  9912. if ($is_single) {
  9913. $anime_name = getProp($anime, 'anime_name', '未命名');
  9914. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9915. if (empty($episode_arr['acts'])) {
  9916. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  9917. }
  9918. $saveResult = $this->saveEpisodeVersionData(
  9919. $anime_id,
  9920. 1,
  9921. $episode_arr,
  9922. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  9923. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  9924. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  9925. null,
  9926. null,
  9927. false,
  9928. $content,
  9929. $now,
  9930. $ref_products
  9931. );
  9932. $single_episode = $saveResult['episode'];
  9933. $episode_id = $saveResult['episode_id'];
  9934. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  9935. 'roles' => json_encode($saveResult['merged_roles'], 256),
  9936. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  9937. 'props' => json_encode($saveResult['merged_props'], 256),
  9938. 'updated_at' => $now
  9939. ]);
  9940. if ($boolen5 === false) {
  9941. Utils::throwError('20003:单剧集主表资源同步失败');
  9942. }
  9943. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  9944. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  9945. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  9946. $episode_record_content = '确认分镜大纲';
  9947. if ($content !== '') {
  9948. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  9949. }
  9950. $episode_records = [
  9951. [
  9952. 'uid' => $uid,
  9953. 'anime_id' => $anime_id,
  9954. 'role' => 'user',
  9955. 'content' => $episode_record_content,
  9956. 'sequence' => 1,
  9957. 'episode_id' => $episode_id,
  9958. 'created_at' => $now,
  9959. 'updated_at' => $now
  9960. ],
  9961. [
  9962. 'uid' => $uid,
  9963. 'anime_id' => $anime_id,
  9964. 'role' => 'assistant',
  9965. 'content' => $fullContent,
  9966. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  9967. 'sequence' => 1,
  9968. 'episode_id' => $episode_id,
  9969. 'created_at' => $now,
  9970. 'updated_at' => $now
  9971. ]
  9972. ];
  9973. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  9974. if (!$boolen4) {
  9975. Utils::throwError('20003:单剧集分镜记录保存失败');
  9976. }
  9977. }
  9978. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  9979. if ($is_single && !empty($single_episode)) {
  9980. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  9981. 'anime_id' => $anime_id,
  9982. 'episode_id' => $episode_id ?? 0,
  9983. 'model' => $model,
  9984. 'source' => 'reGenerateAnimeForAce',
  9985. ]);
  9986. }
  9987. }catch (\Exception $e) {
  9988. DB::rollBack();
  9989. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  9990. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  9991. yield [
  9992. 'type' => 'done',
  9993. 'answer' => $fullContent,
  9994. 'reasoning' => $fullReasoningContent,
  9995. 'usage' => $usage,
  9996. 'error' => $e->getMessage(),
  9997. ];
  9998. return;
  9999. }
  10000. DB::commit();
  10001. dLog('deepseek')->info('保存完毕');
  10002. if ($is_single && !empty($single_episode)) {
  10003. // $this->batchSetGlobalRoleImg([
  10004. // 'anime_id' => $anime_id,
  10005. // ]);
  10006. // $this->batchSetGlobalSceneImg([
  10007. // 'anime_id' => $anime_id,
  10008. // ]);
  10009. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  10010. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  10011. }
  10012. $table_data['anime_id'] = $anime_id;
  10013. $table_data['roles'] = json_decode($table_data['roles'], true);
  10014. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  10015. $table_data['props'] = json_decode($table_data['props'], true);
  10016. unset($table_data['updated_at']);
  10017. unset($table_data['status']);
  10018. yield [
  10019. 'type' => 'done',
  10020. 'script' => $table_data,
  10021. 'episode' => $single_episode,
  10022. 'answer' => $fullContent,
  10023. 'reasoning' => $fullReasoningContent,
  10024. 'usage' => $usage
  10025. ];
  10026. }
  10027. public function chatForAce($data) {
  10028. $uid = Site::getUid();
  10029. // 积分余额预检(不足直接报错)
  10030. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  10031. $anime_id = getProp($data, 'anime_id');
  10032. $file = getProp($data, 'file');
  10033. $content = getProp($data, 'content', '');
  10034. $bid = getProp($data, 'bid', 0);
  10035. $script_id = getProp($data, 'script_id', 0);
  10036. $episode_number = getProp($data, 'episode_number', 1);
  10037. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10038. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10039. if (!$anime) Utils::throwError('20003:该对话不存在!');
  10040. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  10041. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  10042. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  10043. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  10044. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  10045. $roles = is_array($roles) ? $roles : [];
  10046. $scenes = is_array($scenes) ? $scenes : [];
  10047. $extra_products = getProp($data, 'products', []);
  10048. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  10049. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  10050. $anime_script_id = getProp($anime, 'script_id');
  10051. if ($anime_script_id) {
  10052. $cpid = Site::getCpid();
  10053. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  10054. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  10055. ->where('mapping.script_id', $anime_script_id)
  10056. ->where('product.cpid', $cpid)
  10057. ->where('product.is_deleted', 0);
  10058. // 如果提供了 episode_number,则过滤指定集数
  10059. if ($episode_number !== null && $episode_number !== '') {
  10060. $script_products_mappings->where('mapping.episode_number', $episode_number);
  10061. }
  10062. $mappings = $script_products_mappings->select(
  10063. 'mapping.product_id',
  10064. 'mapping.episode_number',
  10065. 'product.product_name',
  10066. 'product.type',
  10067. 'product.product',
  10068. 'product.pic_prompt',
  10069. 'product.url',
  10070. 'product.pic_task_id',
  10071. 'product.pic_task_status',
  10072. 'product.three_view_image_url'
  10073. )
  10074. ->get();
  10075. // 按 product_id 分组,合并 episode_number
  10076. $productMap = [];
  10077. foreach ($mappings as $item) {
  10078. $product_id = $item->product_id;
  10079. $product_name = $item->product_name;
  10080. // 处理product_name两边的符号
  10081. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  10082. if (!isset($productMap[$product_id])) {
  10083. $productMap[$product_id] = [
  10084. 'product_id' => $product_id,
  10085. 'product_name' => $product_name,
  10086. 'type' => (int)$item->type,
  10087. 'product' => (int)$item->product,
  10088. 'pic_prompt' => $item->pic_prompt,
  10089. 'url' => $item->url,
  10090. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  10091. 'pic_task_id' => $item->pic_task_id,
  10092. 'pic_task_status' => $item->pic_task_status,
  10093. 'episode_numbers' => [],
  10094. ];
  10095. }
  10096. // 添加 episode_number(去重)
  10097. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  10098. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  10099. }
  10100. }
  10101. // 将查询到的剧本资产合并到extra_products中
  10102. // 先构建extra_products的索引(以product_id+episode_number为key)
  10103. $extraProductsMap = [];
  10104. foreach ($extra_products as $item) {
  10105. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  10106. $extraProductsMap[$key] = $item;
  10107. }
  10108. // 合并剧本资产(去重:product_id+episode_number)
  10109. foreach ($productMap as $product) {
  10110. foreach ($product['episode_numbers'] as $ep_num) {
  10111. $key = $product['product_id'] . '_' . $ep_num;
  10112. // 如果不存在则添加
  10113. if (!isset($extraProductsMap[$key])) {
  10114. $extraProductsMap[$key] = [
  10115. 'product_id' => $product['product_id'],
  10116. 'product_name' => $product['product_name'],
  10117. 'type' => $product['type'],
  10118. 'product' => $product['product'],
  10119. 'pic_prompt' => $product['pic_prompt'],
  10120. 'url' => $product['url'],
  10121. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  10122. 'pic_task_id' => $product['pic_task_id'],
  10123. 'pic_task_status' => $product['pic_task_status'],
  10124. 'episode_number' => $ep_num,
  10125. ];
  10126. }
  10127. }
  10128. }
  10129. // 重新赋值给extra_products
  10130. $extra_products = array_values($extraProductsMap);
  10131. }
  10132. // 处理提示词
  10133. if ($prompt && $extra_products) {
  10134. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  10135. foreach($extra_products as $item) {
  10136. $product_name = getProp($item, 'product_name');
  10137. if ($product_name) {
  10138. // 替换 {product_name} 为 product_name
  10139. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  10140. }
  10141. }
  10142. }
  10143. // 获取最后一集序号
  10144. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  10145. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  10146. // 转换主体列表和场景列表的格式
  10147. // 获取参考主体或场景
  10148. if ((int)$episode_number === 1) {
  10149. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  10150. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  10151. }else {
  10152. $prev_episode_number = $episode_number - 1;
  10153. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  10154. }
  10155. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  10156. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  10157. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  10158. // 合并anime_products和extra_products(extra_products优先,去重)
  10159. $anime_products = getProp($anime, 'extra_products');
  10160. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  10161. $ref_products = [];
  10162. foreach($anime_products as $item) {
  10163. $product_name = getProp($item, 'product_name');
  10164. $ref_products[$product_name] = $item;
  10165. }
  10166. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  10167. $extra_roles = []; // 从extra_products中提取的角色
  10168. $extra_scenes = []; // 从extra_products中提取的场景
  10169. $extra_props = []; // 从extra_products中提取的道具
  10170. if ($extra_products && is_array($extra_products)) {
  10171. foreach($extra_products as $item) {
  10172. $product = (int)getProp($item, 'product');
  10173. $product_name = getProp($item, 'product_name');
  10174. if ($product_name == '旁白') continue;
  10175. $pic_prompt = getProp($item, 'pic_prompt');
  10176. $ref_products[$product_name] = $item;
  10177. if ($product === 1) {
  10178. // 角色
  10179. $extra_roles[$product_name] = [
  10180. 'role' => $product_name,
  10181. 'pic_prompt' => $pic_prompt,
  10182. 'url' => getProp($item, 'url', ''),
  10183. ];
  10184. } elseif ($product === 2) {
  10185. // 场景
  10186. $extra_scenes[$product_name] = [
  10187. 'scene' => $product_name,
  10188. 'pic_prompt' => $pic_prompt,
  10189. 'url' => getProp($item, 'url', ''),
  10190. ];
  10191. } elseif ($product === 3) {
  10192. // 道具
  10193. $extra_props[$product_name] = [
  10194. 'prop' => $product_name,
  10195. 'pic_prompt' => $pic_prompt,
  10196. 'url' => getProp($item, 'url', ''),
  10197. ];
  10198. }
  10199. }
  10200. }
  10201. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  10202. $merged_roles = [];
  10203. foreach($ref_roles as $role) {
  10204. $role_name = getProp($role, 'role');
  10205. if (!isset($extra_roles[$role_name])) {
  10206. $merged_roles[$role_name] = $role;
  10207. }
  10208. }
  10209. // 添加extra_roles
  10210. foreach($extra_roles as $role_name => $role) {
  10211. $merged_roles[$role_name] = $role;
  10212. }
  10213. $ref_roles = array_values($merged_roles);
  10214. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  10215. $merged_scenes = [];
  10216. foreach($ref_scenes as $scene) {
  10217. $scene_name = getProp($scene, 'scene');
  10218. if (!isset($extra_scenes[$scene_name])) {
  10219. $merged_scenes[$scene_name] = $scene;
  10220. }
  10221. }
  10222. // 添加extra_scenes
  10223. foreach($extra_scenes as $scene_name => $scene) {
  10224. $merged_scenes[$scene_name] = $scene;
  10225. }
  10226. $ref_scenes = array_values($merged_scenes);
  10227. // 合并ref_props和extra_props(extra_props优先,去重)
  10228. $merged_props = [];
  10229. foreach($ref_props as $prop) {
  10230. $prop_name = getProp($prop, 'prop');
  10231. if (!isset($extra_props[$prop_name])) {
  10232. $merged_props[$prop_name] = $prop;
  10233. }
  10234. }
  10235. // 添加extra_props
  10236. foreach($extra_props as $prop_name => $prop) {
  10237. $merged_props[$prop_name] = $prop;
  10238. }
  10239. $ref_props = array_values($merged_props);
  10240. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  10241. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  10242. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  10243. // 构建强制主体、场景和道具提示词
  10244. $forced_roles_prompt = "";
  10245. $forced_scenes_prompt = "";
  10246. $forced_props_prompt = "";
  10247. if (!empty($extra_roles)) {
  10248. $forced_roles_list = "";
  10249. foreach($extra_roles as $role_name => $role) {
  10250. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  10251. }
  10252. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  10253. }
  10254. if (!empty($extra_scenes)) {
  10255. $forced_scenes_list = "";
  10256. foreach($extra_scenes as $scene_name => $scene) {
  10257. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  10258. }
  10259. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  10260. }
  10261. if (!empty($extra_props)) {
  10262. $forced_props_list = "";
  10263. foreach($extra_props as $prop_name => $prop) {
  10264. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  10265. }
  10266. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  10267. }
  10268. if ($anime_script_id) {
  10269. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  10270. }else if ($roles_content) {
  10271. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  10272. 主体范围:\n {$roles_content}\n
  10273. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  10274. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  10275. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  10276. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  10277. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  10278. }else {
  10279. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  10280. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  10281. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  10282. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  10283. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  10284. }
  10285. if ($anime_script_id) {
  10286. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  10287. }else if ($scenes_content) {
  10288. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  10289. 场景范围:\n {$scenes_content}\n
  10290. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  10291. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  10292. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  10293. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  10294. }else {
  10295. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  10296. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  10297. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  10298. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  10299. }
  10300. if ($anime_script_id) {
  10301. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  10302. }else if ($props_content) {
  10303. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  10304. 道具范围:\n {$props_content}\n
  10305. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  10306. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  10307. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  10308. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  10309. }else {
  10310. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  10311. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  10312. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  10313. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  10314. }
  10315. // 提取文件内容
  10316. if ($file) {
  10317. $uploaded_content = $this->extractFileContent($file);
  10318. if (!$uploaded_content) {
  10319. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  10320. }
  10321. } elseif ($script_id) {
  10322. $uploaded_content = $this->getContentByScriptId($script_id);
  10323. if (!$uploaded_content) {
  10324. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  10325. }
  10326. } elseif ($bid) {
  10327. $uploaded_content = $this->getContentByBid($bid);
  10328. if (!$uploaded_content) {
  10329. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  10330. }
  10331. } elseif ($content) {
  10332. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  10333. }
  10334. // elseif ($prompt) {
  10335. // $uploaded_content = filterContent($prompt);
  10336. // }
  10337. else {
  10338. $uploaded_content = '';
  10339. }
  10340. // 美术风格
  10341. $input_art_style = getProp($data, 'art_style');
  10342. if (!$input_art_style) {
  10343. $mappedArtStyle = getProp($anime, 'art_style');
  10344. }else {
  10345. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  10346. }
  10347. if (!$mappedArtStyle) {
  10348. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  10349. }else {
  10350. if (strstr($mappedArtStyle, '基础画风风格词')) {
  10351. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  10352. }else {
  10353. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  10354. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  10355. }
  10356. }
  10357. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10358. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  10359. // 强制要求:
  10360. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  10361. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  10362. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  10363. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  10364. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  10365. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  10366. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  10367. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  10368. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  10369. // 10.分镜要和场景列表、人物主体保持一致\n
  10370. // 普通要求:
  10371. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  10372. // {$role_demo}
  10373. // {$scene_demo}
  10374. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10375. // 4.1片段分割逻辑(优先级从高到低):
  10376. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10377. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10378. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10379. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10380. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10381. // - 片段数量格式为: 片段数量:8
  10382. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10383. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10384. // 4.3分镜结构:每个分镜包含以下字段:
  10385. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  10386. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  10387. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10388. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  10389. // - 运镜:场景+画面描述+运镜
  10390. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  10391. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10392. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10393. // 5.$mappedArtStyle_prompt\n\n
  10394. // 示例格式:\n
  10395. // 第1集:隐形的守护者
  10396. // ###故事梗概
  10397. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10398. // ###美术风格
  10399. // 基础画风风格词:胡金铨武侠
  10400. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10401. // ###主体列表
  10402. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10403. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10404. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10405. // ###场景列表
  10406. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10407. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10408. // ###分段剧本
  10409. // 片段数量:8
  10410. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10411. // ##片段1
  10412. // 时长:12s
  10413. // 分镜1
  10414. // 场景:边境小镇街道
  10415. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10416. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10417. // 配音台词:
  10418. // 背景音效:
  10419. // 分镜2
  10420. // 场景:悦来酒馆
  10421. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10422. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10423. // 配音台词:
  10424. // 背景音效:
  10425. // 分镜3
  10426. // 场景:悦来酒馆
  10427. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10428. // 运镜:从中景推向令牌特写。
  10429. // 配音台词:
  10430. // 背景音效:
  10431. // 分镜4
  10432. // 场景:悦来酒馆
  10433. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10434. // 运镜:极速推向酒水溅起的瞬间。
  10435. // 配音台词:
  10436. // 背景音效:
  10437. // 分镜5
  10438. // 镜头描述
  10439. // 场景:悦来酒馆
  10440. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10441. // 运镜:固定机位,利用倾斜构图制造压迫感。
  10442. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10443. // 背景音效:
  10444. // \n\n";
  10445. /*
  10446. // ====== 旧版 $demo(缓存优化前版本,动态数据内嵌在规则中间) ======
  10447. // 如需换回:删除下方新版 $demo,并把本块恢复为活动代码(去掉首尾注释标记)
  10448. // ===================================================================
  10449. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  10450. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  10451. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  10452. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  10453. 强制要求:
  10454. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  10455. 普通要求:
  10456. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  10457. {$role_demo}
  10458. {$scene_demo}
  10459. {$prop_demo}
  10460. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10461. 5.1片段分割逻辑(优先级从高到低):
  10462. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10463. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10464. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10465. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10466. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10467. - 片段数量格式为: 片段数量:8
  10468. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10469. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10470. 5.3分镜结构:每个分镜包含以下字段:
  10471. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  10472. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10473. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10474. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10475. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10476. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10477. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10478. - 运镜:场景+画面描述+运镜
  10479. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  10480. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  10481. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10482. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10483. 6.《情绪-视听语言映射表》:
  10484. 6.1 场景空间与时间心理学 (Scene & Temporality)
  10485. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10486. -----|---------|------------|----------------
  10487. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  10488. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  10489. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  10490. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  10491. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  10492. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10493. -----|---------|------------|----------------
  10494. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  10495. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  10496. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  10497. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  10498. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  10499. --------|---------|--------------|-------------
  10500. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  10501. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  10502. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  10503. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  10504. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  10505. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  10506. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  10507. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  10508. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  10509. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  10510. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  10511. -----|---------|------------|------------
  10512. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  10513. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  10514. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  10515. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  10516. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  10517. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  10518. --------|---------|--------------|----------
  10519. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  10520. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  10521. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  10522. 6.6 声音设计与潜意识影响 (Soundscape)
  10523. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  10524. -----|---------|------------|------------------
  10525. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  10526. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  10527. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  10528. 理论基石:
  10529. - The Five C's of Cinematography by Joseph V. Mascelli
  10530. - Film Art: An Introduction by David Bordwell
  10531. - Sight, Sound, Motion by Herbert Zettl
  10532. - Notes on the Cinematograph by Robert Bresson
  10533. \n\n
  10534. 7.{$mappedArtStyle_prompt}
  10535. 示例格式:\n
  10536. 第1集:隐形的守护者
  10537. ###故事梗概
  10538. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10539. ###美术风格
  10540. 基础画风风格词:胡金铨武侠
  10541. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10542. ###主体列表
  10543. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10544. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10545. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10546. ###场景列表
  10547. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10548. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10549. ###道具列表
  10550. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  10551. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  10552. ###分段剧本
  10553. 片段数量:8
  10554. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10555. ##片段1
  10556. 时长:12s
  10557. 分镜1
  10558. 出场角色:刀疤脸
  10559. 场景:边境小镇街道
  10560. 出场道具:酒杯-高脚杯
  10561. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10562. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10563. 配音台词:
  10564. 背景音效:
  10565. 分镜2
  10566. 出场角色:刀疤脸
  10567. 场景:悦来酒馆
  10568. 出场道具:酒杯-高脚杯
  10569. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10570. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10571. 配音台词:
  10572. 背景音效:
  10573. 分镜3
  10574. 出场角色:刀疤脸
  10575. 场景:悦来酒馆
  10576. 出场道具:酒杯-高脚杯
  10577. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10578. 运镜:从中景推向令牌特写。
  10579. 配音台词:
  10580. 背景音效:
  10581. 分镜4
  10582. 出场角色:刀疤脸
  10583. 场景:悦来酒馆
  10584. 出场道具:酒杯-高脚杯
  10585. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10586. 运镜:极速推向酒水溅起的瞬间。
  10587. 配音台词:
  10588. 背景音效:
  10589. 分镜5
  10590. 出场角色:刀疤脸
  10591. 场景:悦来酒馆
  10592. 出场道具:酒杯-高脚杯
  10593. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10594. 运镜:固定机位,利用倾斜构图制造压迫感。
  10595. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10596. 背景音效:
  10597. \n\n";
  10598. */
  10599. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  10600. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  10601. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  10602. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  10603. 强制要求:
  10604. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  10605. 普通要求:
  10606. 1.剧集标题必须与文档内容高度相关,剧集序号见文末【本次剧集信息】。
  10607. 2.<主体列表>的详细规则和可选范围见文末【本次生成数据-主体列表】。
  10608. 3.<场景列表>的详细规则和可选范围见文末【本次生成数据-场景列表】。
  10609. 4.<道具列表>的详细规则和可选范围见文末【本次生成数据-道具列表】。
  10610. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10611. 5.1片段分割逻辑(优先级从高到低):
  10612. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10613. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10614. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10615. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10616. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10617. - 片段数量格式为: 片段数量:8
  10618. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10619. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10620. 5.3分镜结构:每个分镜包含以下字段:
  10621. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  10622. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  10623. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10624. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10625. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10626. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10627. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10628. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10629. - 运镜:场景+画面描述+运镜
  10630. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  10631. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  10632. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10633. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10634. 6.《情绪-视听语言映射表》:
  10635. 6.1 场景空间与时间心理学 (Scene & Temporality)
  10636. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10637. -----|---------|------------|----------------
  10638. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  10639. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  10640. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  10641. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  10642. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  10643. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10644. -----|---------|------------|----------------
  10645. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  10646. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  10647. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  10648. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  10649. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  10650. --------|---------|--------------|-------------
  10651. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  10652. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  10653. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  10654. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  10655. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  10656. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  10657. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  10658. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  10659. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  10660. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  10661. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  10662. -----|---------|------------|------------
  10663. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  10664. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  10665. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  10666. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  10667. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  10668. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  10669. --------|---------|--------------|----------
  10670. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  10671. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  10672. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  10673. 6.6 声音设计与潜意识影响 (Soundscape)
  10674. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  10675. -----|---------|------------|------------------
  10676. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  10677. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  10678. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  10679. 理论基石:
  10680. - The Five C's of Cinematography by Joseph V. Mascelli
  10681. - Film Art: An Introduction by David Bordwell
  10682. - Sight, Sound, Motion by Herbert Zettl
  10683. - Notes on the Cinematograph by Robert Bresson
  10684. \n\n
  10685. 7.美术风格要求见文末【本次生成数据-美术风格】。
  10686. 示例格式:\n
  10687. 第1集:隐形的守护者
  10688. ###故事梗概
  10689. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10690. ###美术风格
  10691. 基础画风风格词:胡金铨武侠
  10692. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10693. ###主体列表
  10694. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10695. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10696. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10697. ###场景列表
  10698. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10699. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10700. ###道具列表
  10701. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  10702. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  10703. ###分段剧本
  10704. 片段数量:8
  10705. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10706. ##片段1
  10707. 时长:12s
  10708. 分镜1
  10709. 出场角色:刀疤脸
  10710. 场景:边境小镇街道
  10711. 出场道具:酒杯-高脚杯
  10712. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10713. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10714. 配音台词:
  10715. 背景音效:
  10716. 分镜2
  10717. 出场角色:刀疤脸
  10718. 场景:悦来酒馆
  10719. 出场道具:酒杯-高脚杯
  10720. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10721. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10722. 配音台词:
  10723. 背景音效:
  10724. 分镜3
  10725. 出场角色:刀疤脸
  10726. 场景:悦来酒馆
  10727. 出场道具:酒杯-高脚杯
  10728. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10729. 运镜:从中景推向令牌特写。
  10730. 配音台词:
  10731. 背景音效:
  10732. 分镜4
  10733. 出场角色:刀疤脸
  10734. 场景:悦来酒馆
  10735. 出场道具:酒杯-高脚杯
  10736. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10737. 运镜:极速推向酒水溅起的瞬间。
  10738. 配音台词:
  10739. 背景音效:
  10740. 分镜5
  10741. 出场角色:刀疤脸
  10742. 场景:悦来酒馆
  10743. 出场道具:酒杯-高脚杯
  10744. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10745. 运镜:固定机位,利用倾斜构图制造压迫感。
  10746. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10747. 背景音效:
  10748. \n\n本次生成数据(以上规则的动态数据均在此处,优先级等同对应编号规则):
  10749. 【本次剧集信息】剧集序号是{$episode_number}。
  10750. 【本次生成数据-主体列表】{$role_demo}
  10751. 【本次生成数据-场景列表】{$scene_demo}
  10752. 【本次生成数据-道具列表】{$prop_demo}
  10753. 【本次生成数据-美术风格】{$mappedArtStyle_prompt}
  10754. \n\n";
  10755. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10756. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  10757. // $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  10758. $is_regenerate_version = true;
  10759. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  10760. $prompt = $origin_prompt;
  10761. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  10762. // 获取章节内容
  10763. $full_content = getProp($anime, 'content');
  10764. if ($uploaded_content) {
  10765. $full_content = $uploaded_content;
  10766. }
  10767. // 根据章节内容拆分章节
  10768. $chapters = splitContent($full_content);
  10769. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  10770. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  10771. $messages = [];
  10772. if ($prompt == '确认分镜大纲') {
  10773. // 暂时保留
  10774. $content = $chapter_content;
  10775. if ($is_single) $content = $full_content; // 单剧集使用全文
  10776. if (!$content) {
  10777. Utils::throwError('20003:章节内容无法获取,请确认');
  10778. }
  10779. $question = $is_single
  10780. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  10781. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  10782. // 构建消息
  10783. $messages[] =
  10784. [
  10785. 'role' => 'user',
  10786. 'content' => $question
  10787. ];
  10788. }else if ($prompt == '继续策划下一集') {
  10789. if ($is_single) {
  10790. Utils::throwError('20003:单剧集不支持继续策划下一集');
  10791. }
  10792. $content = $chapter_content;
  10793. if (!$content) {
  10794. Utils::throwError('20003:章节内容无法获取,请确认');
  10795. }
  10796. // 获取上一集最后记录
  10797. $prev_sequence = $episode_number - 1;
  10798. $messages = array_merge(
  10799. [
  10800. [
  10801. 'role' => 'system',
  10802. 'content' => $demo
  10803. ]
  10804. ],
  10805. $this->getEpisodeChatContent($anime_id, $prev_sequence, $content)
  10806. );
  10807. // 构建消息
  10808. $messages[] =
  10809. [
  10810. 'role' => 'user',
  10811. 'content' => "请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)"
  10812. ];
  10813. /*
  10814. // 旧版逻辑
  10815. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  10816. // 构建消息
  10817. $messages[] =
  10818. [
  10819. 'role' => 'user',
  10820. 'content' => $question
  10821. ];
  10822. */
  10823. // dd($messages);
  10824. }else {
  10825. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  10826. if (!$content) {
  10827. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  10828. }
  10829. if (!$content) {
  10830. Utils::throwError('20003:章节内容无法获取,请确认');
  10831. }
  10832. $messages = array_merge(
  10833. [
  10834. [
  10835. 'role' => 'system',
  10836. 'content' => $demo
  10837. ]
  10838. ],
  10839. $this->getEpisodeChatMessages($anime_id, $episode_number)
  10840. );
  10841. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  10842. $question = "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  10843. if ($origin_prompt) {
  10844. $question .= "本次修改要求如下:\n{$origin_prompt}";
  10845. }
  10846. // 将本集原文加入消息,供模型逐字摘录原文台词(修复重新生成时配音台词全部为"无"的问题)
  10847. $messages[] = [
  10848. 'role' => 'user',
  10849. 'content' => "本集剧情内容:\n\n{$content}\n"
  10850. ];
  10851. $messages[] =
  10852. [
  10853. 'role' => 'user',
  10854. 'content' => $question
  10855. ];
  10856. }
  10857. // 处理文本模型
  10858. $model = getProp($data, 'model');
  10859. if (!$model) {
  10860. // 用户没有输入,从anime表获取
  10861. $model = getProp($anime, 'model');
  10862. if (!$model) {
  10863. // anime表也没有,使用默认值
  10864. $model = 'deepseek-v4-pro';
  10865. }
  10866. }
  10867. // 验证模型是否在可用模型表中
  10868. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10869. $model = 'deepseek-v4-pro';
  10870. }
  10871. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  10872. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  10873. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  10874. if ($model === 'deepseek-chat') {
  10875. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  10876. $model = 'deepseek-v4-flash';
  10877. $thinkingMode = 'disabled';
  10878. } elseif ($model === 'deepseek-reasoner') {
  10879. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  10880. $model = 'deepseek-v4-flash';
  10881. $thinkingMode = 'enabled';
  10882. }
  10883. $post_data = [
  10884. 'model' => $model,
  10885. 'messages' => $messages,
  10886. // 'max_tokens' => 8192,
  10887. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  10888. 'frequency_penalty' => 0,
  10889. 'presence_penalty' => 0,
  10890. 'response_format' => ['type' => 'text'],
  10891. 'thinking' => ['type' => $thinkingMode],
  10892. 'stream' => true // 启用流式输出
  10893. ];
  10894. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  10895. // 根据模型类型选择调用方法
  10896. $fullContent = '';
  10897. $fullReasoningContent = '';
  10898. $usage = [];
  10899. try {
  10900. $streamGenerator = $this->dispatchStreamByModel($post_data);
  10901. // 验证返回值类型
  10902. if (!is_iterable($streamGenerator)) {
  10903. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  10904. dLog('deepseek')->error('chat流式生成器无效', [
  10905. 'generator_type' => $errorType,
  10906. 'model' => $model,
  10907. 'anime_id' => $anime_id,
  10908. 'episode_number' => $episode_number
  10909. ]);
  10910. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  10911. 'type' => $errorType,
  10912. 'model' => $model
  10913. ]);
  10914. yield [
  10915. 'type' => 'error',
  10916. 'episode' => [],
  10917. 'answer' => '',
  10918. 'reasoning' => '',
  10919. 'usage' => [],
  10920. 'error' => '接口返回数据异常,请重新请求'
  10921. ];
  10922. return;
  10923. }
  10924. // 处理流式输出
  10925. foreach ($streamGenerator as $chunk) {
  10926. if (isset($chunk['type'])) {
  10927. if ($chunk['type'] === 'done') {
  10928. // 最终结果
  10929. $fullContent = $chunk['full_content'];
  10930. $fullReasoningContent = $chunk['full_reasoning'];
  10931. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  10932. } else {
  10933. // 逐块yield数据
  10934. yield $chunk;
  10935. }
  10936. }
  10937. }
  10938. } catch (\Exception $e) {
  10939. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  10940. 'model' => $model,
  10941. 'anime_id' => $anime_id,
  10942. 'episode_number' => $episode_number,
  10943. 'trace' => $e->getTraceAsString()
  10944. ]);
  10945. logDB('deepseek', 'error', 'chat流式处理失败', [
  10946. 'error' => $e->getMessage(),
  10947. 'model' => $model
  10948. ]);
  10949. yield [
  10950. 'type' => 'error',
  10951. 'episode' => [],
  10952. 'answer' => '',
  10953. 'reasoning' => '',
  10954. 'usage' => [],
  10955. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  10956. ];
  10957. return;
  10958. }
  10959. // 兼容模型偶发将整段正文包裹成 JSON 字符串返回
  10960. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  10961. dLog('deepseek')->info('完整内容: '.$fullContent);
  10962. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  10963. // 处理完整内容并返回最终结果
  10964. $episode_arr = handleEpisodeContentForAce($fullContent);
  10965. dLog('deepseek')->info('解析内容: ', $episode_arr);
  10966. logDB('deepseek', 'info', '解析内容', $episode_arr);
  10967. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  10968. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  10969. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  10970. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  10971. // }
  10972. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  10973. $max_retries = 3;
  10974. $retry_count = 0;
  10975. $validation_failed = false;
  10976. $validation_error_msg = '';
  10977. // 验证生成的内容
  10978. if ($anime_script_id) {
  10979. // 检查是否有acts数据
  10980. if (empty($episode_arr['acts'])) {
  10981. $validation_failed = true;
  10982. $validation_error_msg = '未生成分镜剧本相关的内容';
  10983. } else {
  10984. // 校验主体列表:不能为空主体(旁白不算)
  10985. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  10986. // 过滤掉"旁白"角色
  10987. $generated_roles = array_filter($generated_roles, function($role) {
  10988. return $role !== '旁白';
  10989. });
  10990. if (empty($generated_roles)) {
  10991. $validation_failed = true;
  10992. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  10993. }
  10994. // 仅当存在强制主体设定时校验主体列表
  10995. if (!$validation_failed && !empty($extra_roles)) {
  10996. $expected_roles = array_keys($extra_roles);
  10997. // 找出生成的主体中不在预期列表中的主体
  10998. $invalid_roles = array_diff($generated_roles, $expected_roles);
  10999. if (!empty($invalid_roles)) {
  11000. $validation_failed = true;
  11001. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  11002. }
  11003. }
  11004. // 仅当存在强制场景设定时校验场景列表
  11005. if (!$validation_failed && !empty($extra_scenes)) {
  11006. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  11007. $expected_scenes = array_keys($extra_scenes);
  11008. // 找出生成的场景中不在预期列表中的场景
  11009. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  11010. if (!empty($invalid_scenes)) {
  11011. $validation_failed = true;
  11012. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  11013. }
  11014. }
  11015. // 仅当存在强制道具设定时校验道具列表
  11016. if (!$validation_failed && !empty($extra_props)) {
  11017. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  11018. $expected_props = array_keys($extra_props);
  11019. // 找出生成的道具中不在预期列表中的道具
  11020. $invalid_props = array_diff($generated_props, $expected_props);
  11021. if (!empty($invalid_props)) {
  11022. $validation_failed = true;
  11023. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  11024. }
  11025. }
  11026. }
  11027. } else {
  11028. // 如果没有anime_script_id,只检查是否有acts数据
  11029. if (empty($episode_arr['acts'])) {
  11030. $validation_failed = true;
  11031. $validation_error_msg = '未生成分镜剧本相关的内容';
  11032. } else {
  11033. // 校验主体列表:不能为空主体(旁白不算)
  11034. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11035. // 过滤掉"旁白"角色
  11036. $generated_roles = array_filter($generated_roles, function($role) {
  11037. return $role !== '旁白';
  11038. });
  11039. if (empty($generated_roles)) {
  11040. $validation_failed = true;
  11041. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11042. }
  11043. }
  11044. }
  11045. // 重试逻辑
  11046. while ($validation_failed && $retry_count < $max_retries) {
  11047. $retry_count++;
  11048. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  11049. 'reason' => $validation_error_msg,
  11050. 'anime_id' => $anime_id,
  11051. 'episode_number' => $episode_number
  11052. ]);
  11053. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  11054. 'reason' => $validation_error_msg,
  11055. 'anime_id' => $anime_id
  11056. ]);
  11057. // 发送流式重试提示
  11058. yield [
  11059. 'type' => 'retry',
  11060. 'retry_count' => $retry_count,
  11061. 'reason' => $validation_error_msg
  11062. ];
  11063. // 构建重试提示词
  11064. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  11065. if ($anime_script_id) {
  11066. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  11067. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  11068. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  11069. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  11070. } else {
  11071. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  11072. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  11073. }
  11074. // 添加重试消息到messages
  11075. $messages[] = [
  11076. 'role' => 'assistant',
  11077. 'content' => $fullContent
  11078. ];
  11079. $messages[] = [
  11080. 'role' => 'user',
  11081. 'content' => $retry_prompt
  11082. ];
  11083. // 更新post_data的messages
  11084. $post_data['messages'] = $messages;
  11085. // 重新调用API
  11086. try {
  11087. $streamGenerator = $this->dispatchStreamByModel($post_data);
  11088. // 处理流式输出
  11089. $fullContent = '';
  11090. $fullReasoningContent = '';
  11091. foreach ($streamGenerator as $chunk) {
  11092. if (isset($chunk['type'])) {
  11093. if ($chunk['type'] === 'done') {
  11094. $fullContent = $chunk['full_content'];
  11095. $fullReasoningContent = $chunk['full_reasoning'];
  11096. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  11097. } else {
  11098. yield $chunk;
  11099. }
  11100. }
  11101. }
  11102. // 重新解析内容
  11103. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  11104. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  11105. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  11106. $episode_arr = handleEpisodeContentForAce($fullContent);
  11107. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  11108. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  11109. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  11110. // }
  11111. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  11112. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  11113. // 重新验证
  11114. $validation_failed = false;
  11115. $validation_error_msg = '';
  11116. if ($anime_script_id) {
  11117. if (empty($episode_arr['acts'])) {
  11118. $validation_failed = true;
  11119. $validation_error_msg = '未生成分镜剧本相关的内容';
  11120. } else {
  11121. // 校验主体列表:不能为空主体(旁白不算)
  11122. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11123. // 过滤掉"旁白"角色
  11124. $generated_roles = array_filter($generated_roles, function($role) {
  11125. return $role !== '旁白';
  11126. });
  11127. if (empty($generated_roles)) {
  11128. $validation_failed = true;
  11129. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11130. }
  11131. // 仅当存在强制主体设定时校验主体列表
  11132. if (!$validation_failed && !empty($extra_roles)) {
  11133. $expected_roles = array_keys($extra_roles);
  11134. $invalid_roles = array_diff($generated_roles, $expected_roles);
  11135. if (!empty($invalid_roles)) {
  11136. $validation_failed = true;
  11137. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  11138. }
  11139. }
  11140. // 仅当存在强制场景设定时校验场景列表
  11141. if (!$validation_failed && !empty($extra_scenes)) {
  11142. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  11143. $expected_scenes = array_keys($extra_scenes);
  11144. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  11145. if (!empty($invalid_scenes)) {
  11146. $validation_failed = true;
  11147. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  11148. }
  11149. }
  11150. // 仅当存在强制道具设定时校验道具列表
  11151. if (!$validation_failed && !empty($extra_props)) {
  11152. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  11153. $expected_props = array_keys($extra_props);
  11154. $invalid_props = array_diff($generated_props, $expected_props);
  11155. if (!empty($invalid_props)) {
  11156. $validation_failed = true;
  11157. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  11158. }
  11159. }
  11160. }
  11161. } else {
  11162. if (empty($episode_arr['acts'])) {
  11163. $validation_failed = true;
  11164. $validation_error_msg = '未生成分镜剧本相关的内容';
  11165. } else {
  11166. // 校验主体列表:不能为空主体(旁白不算)
  11167. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11168. // 过滤掉"旁白"角色
  11169. $generated_roles = array_filter($generated_roles, function($role) {
  11170. return $role !== '旁白';
  11171. });
  11172. if (empty($generated_roles)) {
  11173. $validation_failed = true;
  11174. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11175. }
  11176. }
  11177. }
  11178. } catch (\Exception $e) {
  11179. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  11180. 'trace' => $e->getTraceAsString()
  11181. ]);
  11182. break;
  11183. }
  11184. }
  11185. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  11186. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  11187. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  11188. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  11189. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  11190. if ($validation_failed && $retry_count >= $max_retries) {
  11191. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  11192. 'retry_count' => $retry_count,
  11193. 'last_error' => $validation_error_msg
  11194. ]);
  11195. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  11196. 'error' => $validation_error_msg,
  11197. 'anime_id' => $anime_id
  11198. ]);
  11199. $validation_failed = false;
  11200. $validation_error_msg = '';
  11201. }
  11202. // 如果重试后仍然失败
  11203. if ($validation_failed) {
  11204. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  11205. 'retry_count' => $retry_count,
  11206. 'last_error' => $validation_error_msg
  11207. ]);
  11208. try {
  11209. $now = date('Y-m-d H:i:s');
  11210. $records = [
  11211. [
  11212. 'uid' => $uid,
  11213. 'anime_id' => $anime_id,
  11214. 'sequence' => $episode_number,
  11215. 'role' => 'user',
  11216. 'content' => $prompt,
  11217. 'created_at' => $now,
  11218. 'updated_at' => $now
  11219. ],
  11220. [
  11221. 'uid' => $uid,
  11222. 'anime_id' => $anime_id,
  11223. 'sequence' => $episode_number,
  11224. 'role' => 'assistant',
  11225. 'content' => $fullContent,
  11226. 'created_at' => $now,
  11227. 'updated_at' => $now
  11228. ]
  11229. ];
  11230. DB::table('mp_anime_records')->insert($records);
  11231. } catch (\Exception $e) {
  11232. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  11233. }
  11234. yield [
  11235. 'type' => 'done',
  11236. 'episode' => [],
  11237. 'answer' => $fullContent,
  11238. 'reasoning' => $fullReasoningContent,
  11239. 'usage' => $usage,
  11240. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  11241. ];
  11242. return;
  11243. }
  11244. // 验证成功,记录日志
  11245. if ($retry_count > 0) {
  11246. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  11247. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  11248. }
  11249. // 老逻辑
  11250. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  11251. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  11252. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  11253. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  11254. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  11255. $existing_props = is_array($existing_props) ? $existing_props : [];
  11256. $now = date('Y-m-d H:i:s');
  11257. try {
  11258. DB::beginTransaction();
  11259. $saveResult = $this->saveEpisodeVersionData(
  11260. $anime_id,
  11261. $episode_number,
  11262. $episode_arr,
  11263. $existing_roles,
  11264. $existing_scenes,
  11265. $existing_props,
  11266. $current_episode,
  11267. $base_episode,
  11268. $is_regenerate_version,
  11269. $content,
  11270. $now,
  11271. $ref_products
  11272. );
  11273. $episode = $saveResult['episode'];
  11274. $episode_id = $saveResult['episode_id'];
  11275. $merged_roles = $saveResult['merged_roles'];
  11276. $merged_scenes = $saveResult['merged_scenes'];
  11277. $merged_props = $saveResult['merged_props'];
  11278. $record_content = $origin_prompt;
  11279. if ($uploaded_content !== '') {
  11280. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  11281. }
  11282. $records = [
  11283. [
  11284. 'uid' => $uid,
  11285. 'anime_id' => $anime_id,
  11286. 'role' => 'user',
  11287. 'content' => $record_content,
  11288. 'sequence' => $episode_number,
  11289. 'episode_id' => $episode_id,
  11290. 'created_at' => $now,
  11291. 'updated_at' => $now
  11292. ],
  11293. [
  11294. 'uid' => $uid,
  11295. 'anime_id' => $anime_id,
  11296. 'role' => 'assistant',
  11297. 'content' => $fullContent,
  11298. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  11299. 'sequence' => $episode_number,
  11300. 'episode_id' => $episode_id,
  11301. 'created_at' => $now,
  11302. 'updated_at' => $now
  11303. ]
  11304. ];
  11305. $boolen4 = DB::table('mp_anime_records')->insert($records);
  11306. if (!$boolen4) {
  11307. Utils::throwError('20003:对话记录保存失败');
  11308. }
  11309. // 保存模型到anime表
  11310. $update_anime_data = [
  11311. 'model' => $model,
  11312. 'updated_at' => $now
  11313. ];
  11314. if ($uploaded_content) {
  11315. $update_anime_data['content'] = $uploaded_content;
  11316. }
  11317. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  11318. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  11319. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  11320. 'anime_id' => $anime_id,
  11321. 'episode_number' => $episode_number,
  11322. 'model' => $model,
  11323. 'source' => 'chatForAce',
  11324. ]);
  11325. }catch (\Exception $e) {
  11326. DB::rollBack();
  11327. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  11328. yield [
  11329. 'type' => 'done',
  11330. 'answer' => $fullContent,
  11331. 'reasoning' => $fullReasoningContent,
  11332. 'usage' => $usage,
  11333. 'error' => $e->getMessage(),
  11334. ];
  11335. return;
  11336. }
  11337. DB::commit();
  11338. if ($is_global_generate_pics) {
  11339. // // 批量生成全局角色图片
  11340. // $this->batchSetGlobalRoleImg([
  11341. // 'anime_id' => $anime_id,
  11342. // ], true);
  11343. // // 批量生成全局场景图片
  11344. // $this->batchSetGlobalSceneImg([
  11345. // 'anime_id' => $anime_id,
  11346. // ], true);
  11347. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  11348. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  11349. }
  11350. $episode['episode_id'] = $episode_id;
  11351. $episode['roles'] = $merged_roles;
  11352. $episode['scenes'] = $merged_scenes;
  11353. $episode['props'] = $merged_props;
  11354. $episode['end_episode_sequence'] = $end_episode_sequence;
  11355. // 获取mp_animes表中的视频参数
  11356. $episode['video_params'] = [
  11357. 'video_model' => getProp($anime, 'video_model'),
  11358. 'video_resolution' => getProp($anime, 'video_resolution'),
  11359. 'ratio' => getProp($anime, 'video_ratio'),
  11360. ];
  11361. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  11362. yield [
  11363. 'type' => 'done',
  11364. 'episode' => $episode,
  11365. 'answer' => $fullContent,
  11366. 'reasoning' => $fullReasoningContent,
  11367. 'usage' => $usage
  11368. ];
  11369. }
  11370. /**
  11371. * chatForAce的非流式版本 - 用于定时任务
  11372. * 只获取最终 type=done 的数据,并验证必要字段
  11373. *
  11374. * @param array $data 请求数据
  11375. * @return array 生成结果
  11376. */
  11377. public function chatForAceNonStream($data) {
  11378. $finalResult = null;
  11379. // 调用流式方法,只保存 type=done 的数据
  11380. foreach ($this->chatForAce($data) as $chunk) {
  11381. // 只关注最终结果
  11382. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  11383. $finalResult = $chunk;
  11384. break; // 找到 done 就退出循环
  11385. }
  11386. }
  11387. // 验证最终结果
  11388. if (!$finalResult) {
  11389. return ['error' => '生成失败:未获取到最终结果'];
  11390. }
  11391. // 检查是否有错误
  11392. if (isset($finalResult['error']) && $finalResult['error']) {
  11393. return $finalResult;
  11394. }
  11395. // 验证必要字段
  11396. $episode = $finalResult['episode'] ?? [];
  11397. // 验证 roles(旁白不算主体,过滤后不能为空)
  11398. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  11399. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  11400. }
  11401. $nonNarratorRoles = array_filter(array_column($episode['roles'], 'role'), function($role) {
  11402. return $role !== '旁白';
  11403. });
  11404. if (empty($nonNarratorRoles)) {
  11405. return ['error' => '生成失败:主体列表(roles)为空或格式错误(旁白不算)'];
  11406. }
  11407. // 验证 scenes
  11408. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  11409. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  11410. }
  11411. // 验证 props(道具可以为空,但必须存在且为数组)
  11412. if (!isset($episode['props']) || !is_array($episode['props'])) {
  11413. $episode['props'] = [];
  11414. }
  11415. // 验证 acts(分镜剧本)
  11416. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  11417. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  11418. }
  11419. // 更新验证后的 episode 数据
  11420. $finalResult['episode'] = $episode;
  11421. // 记录验证成功日志
  11422. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  11423. 'roles_count' => count($episode['roles']),
  11424. 'scenes_count' => count($episode['scenes']),
  11425. 'props_count' => count($episode['props']),
  11426. 'acts_count' => count($episode['acts'])
  11427. ]);
  11428. return $finalResult;
  11429. }
  11430. /**
  11431. * 批量生成多个分集
  11432. *
  11433. * @param array $data 请求数据
  11434. * @return array 任务信息
  11435. */
  11436. public function batchGenerateEpisodes($data) {
  11437. $uid = Site::getUid();
  11438. $cpid = Site::getCpid();
  11439. $anime_id = getProp($data, 'anime_id');
  11440. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  11441. $start_episode_number = getProp($data, 'start_episode_number');
  11442. $end_episode_number = getProp($data, 'end_episode_number');
  11443. if (!$anime_id) {
  11444. Utils::throwError('20003:anime_id参数缺失');
  11445. }
  11446. if ($generate_episode_number < 1) {
  11447. Utils::throwError('20003:生成集数必须大于0');
  11448. }
  11449. // 获取动漫信息
  11450. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  11451. if (!$anime) {
  11452. Utils::throwError('20003:该剧集不存在');
  11453. }
  11454. // 检查是否是全能模式
  11455. if ((int)getProp($anime, 'ace_mode') !== 1) {
  11456. Utils::throwError('20003:只有全能模式才支持批量生成');
  11457. }
  11458. // 检查是否是多剧集模式
  11459. if ((int)getProp($anime, 'is_multi') !== 1) {
  11460. Utils::throwError('20003:单剧集不支持批量生成');
  11461. }
  11462. // 指定起始/结束剧集序号时的校验
  11463. $hasSpecifiedRange = ($start_episode_number !== null && $start_episode_number !== '')
  11464. || ($end_episode_number !== null && $end_episode_number !== '');
  11465. if ($hasSpecifiedRange) {
  11466. if ($start_episode_number === null || $start_episode_number === ''
  11467. || $end_episode_number === null || $end_episode_number === '') {
  11468. Utils::throwError('20003:起始剧集序号和结束剧集序号必须同时提供');
  11469. }
  11470. $start_episode_number = (int)$start_episode_number;
  11471. $end_episode_number = (int)$end_episode_number;
  11472. if ($start_episode_number < 1 || $end_episode_number < $start_episode_number) {
  11473. Utils::throwError('20003:剧集序号范围错误,结束剧集序号不能小于起始剧集序号');
  11474. }
  11475. // 起始序号必须是已有剧集(is_default=1)的下一个序号,不允许跨序号创建
  11476. $currentMaxEpisode = DB::table('mp_anime_episodes')
  11477. ->where('anime_id', $anime_id)
  11478. ->where('is_default', 1)
  11479. ->max('episode_number');
  11480. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  11481. $nextEpisodeNumber = $currentMaxEpisode + 1;
  11482. if ($start_episode_number !== $nextEpisodeNumber) {
  11483. Utils::throwError('20003:起始剧集序号必须是已有剧集的下一个序号(第' . $nextEpisodeNumber . '集),不允许跨序号创建');
  11484. }
  11485. $startEpisodeNumber = $start_episode_number;
  11486. $endEpisodeNumber = $end_episode_number;
  11487. } else {
  11488. // 未指定范围时,以 generate_episode_number 判断要生成的集数,从当前已生成的最大集数的下一集开始
  11489. $currentMaxEpisode = DB::table('mp_anime_episodes')
  11490. ->where('anime_id', $anime_id)
  11491. ->where('is_default', 1)
  11492. ->max('episode_number');
  11493. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  11494. // 确定起始集数
  11495. $startEpisodeNumber = $currentMaxEpisode + 1;
  11496. // 计算结束集数
  11497. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  11498. }
  11499. // 本次实际生成的集数
  11500. $totalEpisodeCount = $endEpisodeNumber - $startEpisodeNumber + 1;
  11501. // 检查是否超过总集数限制
  11502. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  11503. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  11504. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  11505. }
  11506. // 创建任务前验重:批量任务表与剧集表中是否已存在范围内的剧集序号
  11507. $duplicatedBatchEpisodes = DB::table('mp_batch_episode_generation_details')
  11508. ->where('anime_id', $anime_id)
  11509. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11510. ->pluck('episode_number')
  11511. ->unique()
  11512. ->sort()
  11513. ->values()
  11514. ->toArray();
  11515. $duplicatedAnimeEpisodes = DB::table('mp_anime_episodes')
  11516. ->where('anime_id', $anime_id)
  11517. ->where('is_default', 1)
  11518. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11519. ->pluck('episode_number')
  11520. ->unique()
  11521. ->sort()
  11522. ->values()
  11523. ->toArray();
  11524. if (!empty($duplicatedBatchEpisodes) || !empty($duplicatedAnimeEpisodes)) {
  11525. $duplicateMessages = [];
  11526. if (!empty($duplicatedBatchEpisodes)) {
  11527. $duplicateMessages[] = '批量生成任务中已存在第' . implode('、', $duplicatedBatchEpisodes) . '集';
  11528. }
  11529. if (!empty($duplicatedAnimeEpisodes)) {
  11530. $duplicateMessages[] = '剧集中已存在第' . implode('、', $duplicatedAnimeEpisodes) . '集';
  11531. }
  11532. Utils::throwError('20003:' . implode(';', $duplicateMessages) . ',请勿重复创建');
  11533. }
  11534. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  11535. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  11536. ->where('anime_id', $anime_id)
  11537. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11538. ->whereIn('status', ['pending', 'processing', 'completed'])
  11539. ->count();
  11540. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  11541. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  11542. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  11543. if ($needEpisodeCount > 0) {
  11544. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints() * $needEpisodeCount, $uid);
  11545. }
  11546. $now = date('Y-m-d H:i:s');
  11547. $createdTasks = [];
  11548. $skippedTasks = [];
  11549. // 为每一集创建详情记录
  11550. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  11551. // 检查是否已有该集的任务记录
  11552. $existingTask = DB::table('mp_batch_episode_generation_details')
  11553. ->where('anime_id', $anime_id)
  11554. ->where('episode_number', $episodeNumber)
  11555. ->first();
  11556. if ($existingTask) {
  11557. // 如果已存在且未完成,跳过
  11558. if (in_array($existingTask->status, ['pending', 'processing'])) {
  11559. $skippedTasks[] = $episodeNumber;
  11560. continue;
  11561. }
  11562. // 如果是失败状态,可以重新创建(删除旧记录)
  11563. if ($existingTask->status === 'failed') {
  11564. DB::table('mp_batch_episode_generation_details')
  11565. ->where('id', $existingTask->id)
  11566. ->delete();
  11567. }
  11568. // 如果是已完成状态,也跳过
  11569. if ($existingTask->status === 'completed') {
  11570. $skippedTasks[] = $episodeNumber;
  11571. continue;
  11572. }
  11573. }
  11574. // 准备任务数据
  11575. $taskData = [
  11576. 'anime_id' => $anime_id,
  11577. 'uid' => $uid,
  11578. 'cpid' => $cpid,
  11579. 'episode_number' => $episodeNumber,
  11580. 'status' => 'pending',
  11581. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  11582. 'retry_count' => 0,
  11583. 'created_at' => $now,
  11584. 'updated_at' => $now
  11585. ];
  11586. // 创建任务记录
  11587. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  11588. if ($taskId) {
  11589. $createdTasks[] = $episodeNumber;
  11590. }
  11591. }
  11592. if (empty($createdTasks)) {
  11593. if (!empty($skippedTasks)) {
  11594. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  11595. } else {
  11596. Utils::throwError('20003:创建批量生成任务失败');
  11597. }
  11598. }
  11599. // 创建/复用任务中心记录(按入参+type验重,避免重复任务)
  11600. $taskCenterId = $this->createBatchGenerateEpisodesTaskCenter(
  11601. $uid,
  11602. $cpid,
  11603. $anime_id,
  11604. $generate_episode_number,
  11605. $startEpisodeNumber,
  11606. $endEpisodeNumber
  11607. );
  11608. return [
  11609. 'anime_id' => $anime_id,
  11610. 'start_episode' => $startEpisodeNumber,
  11611. 'end_episode' => $endEpisodeNumber,
  11612. 'total_episodes' => $totalEpisodeCount,
  11613. 'created_episodes' => $createdTasks,
  11614. 'skipped_episodes' => $skippedTasks,
  11615. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$totalEpisodeCount}集。" .
  11616. "已创建: " . implode(',', $createdTasks) .
  11617. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : ""),
  11618. 'task_center_id' => $taskCenterId
  11619. ];
  11620. }
  11621. /**
  11622. * 根据入参创建或复用批量生成分集的任务中心记录
  11623. *
  11624. * 以入参(anime_id、generate_episode_number)计算 md5 存入 params_md5 字段用于验重:
  11625. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  11626. * 避免生成重复任务;唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复。
  11627. *
  11628. * @param int|string $uid
  11629. * @param int|string $cpid
  11630. * @param int|string $anime_id
  11631. * @param int $generate_episode_number
  11632. * @param int $startEpisodeNumber
  11633. * @param int $endEpisodeNumber
  11634. * @return int 任务中心ID
  11635. */
  11636. private function createBatchGenerateEpisodesTaskCenter($uid, $cpid, $anime_id, $generate_episode_number, $startEpisodeNumber, $endEpisodeNumber) {
  11637. $params = [
  11638. 'anime_id' => (int)$anime_id,
  11639. 'generate_episode_number' => (int)$generate_episode_number,
  11640. 'start_episode' => (int)$startEpisodeNumber,
  11641. 'end_episode' => (int)$endEpisodeNumber,
  11642. ];
  11643. // 验重键:入参 + 生成范围(anime_id + generate_episode_number + start/end)+ task_type
  11644. $paramsMd5 = md5(json_encode([
  11645. 'anime_id' => (int)$anime_id,
  11646. 'generate_episode_number' => (int)$generate_episode_number,
  11647. 'start_episode' => (int)$startEpisodeNumber,
  11648. 'end_episode' => (int)$endEpisodeNumber,
  11649. ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  11650. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  11651. $existing = DB::table('mp_task_center')
  11652. ->where('uid', (int)$uid)
  11653. ->where('cpid', (int)$cpid)
  11654. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11655. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  11656. ->where('params_md5', $paramsMd5)
  11657. ->orderBy('id', 'desc')
  11658. ->first();
  11659. if ($existing) {
  11660. dLog('deepseek')->info('复用批量生成分集任务中心记录,避免重复任务', [
  11661. 'anime_id' => $anime_id,
  11662. 'task_center_id' => $existing->id,
  11663. 'params_md5' => $paramsMd5,
  11664. ]);
  11665. return (int)$existing->id;
  11666. }
  11667. $now = date('Y-m-d H:i:s');
  11668. DB::table('mp_task_center')->insertOrIgnore([
  11669. 'uid' => (int)$uid,
  11670. 'cpid' => (int)$cpid,
  11671. 'task_type' => MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES,
  11672. 'title' => '批量生成分集',
  11673. 'ref_task_id' => 0,
  11674. 'status' => MpTaskCenter::STATUS_PROCESSING,
  11675. 'result' => null,
  11676. 'error_message' => null,
  11677. 'prompt' => null,
  11678. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  11679. 'params_md5' => $paramsMd5,
  11680. 'created_at' => $now,
  11681. 'updated_at' => $now,
  11682. ]);
  11683. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  11684. $taskId = (int)DB::table('mp_task_center')
  11685. ->where('uid', (int)$uid)
  11686. ->where('cpid', (int)$cpid)
  11687. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11688. ->where('params_md5', $paramsMd5)
  11689. ->orderBy('id', 'desc')
  11690. ->value('id');
  11691. dLog('deepseek')->info('创建批量生成分集任务中心记录', [
  11692. 'anime_id' => $anime_id,
  11693. 'task_center_id' => $taskId,
  11694. 'params_md5' => $paramsMd5,
  11695. ]);
  11696. return $taskId;
  11697. }
  11698. /**
  11699. * 批量生成分集全部结束后,更新任务中心记录的状态和结果
  11700. *
  11701. * 由批量生成 worker 子进程在退出前调用。分集详情任务的状态会在多处更新
  11702. * (completed/failed/pending/processing),这里只在所有详情任务均已结束时
  11703. * 统一汇总更新,避免在每个更新点重复处理。
  11704. *
  11705. * @param int|string $animeId
  11706. * @return int 更新的任务中心记录数
  11707. */
  11708. public function finishBatchGenerateEpisodesTaskCenters($animeId) {
  11709. $animeId = (int)$animeId;
  11710. $updated = 0;
  11711. // 该 anime 是否还有未结束的详情任务
  11712. $hasUnfinished = DB::table('mp_batch_episode_generation_details')
  11713. ->where('anime_id', $animeId)
  11714. ->whereIn('status', ['pending', 'processing'])
  11715. ->exists();
  11716. // 扫描该 anime 相关的未完成任务中心记录
  11717. $tasks = DB::table('mp_task_center')
  11718. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11719. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  11720. ->orderBy('id', 'desc')
  11721. ->limit(500)
  11722. ->get();
  11723. if ($hasUnfinished && !$tasks) {
  11724. return 0;
  11725. }
  11726. foreach ($tasks as $task) {
  11727. try {
  11728. $taskParams = json_decode((string)$task->params, true);
  11729. if (!is_array($taskParams) || (int)($taskParams['anime_id'] ?? 0) !== $animeId) {
  11730. continue;
  11731. }
  11732. $startEpisode = (int)($taskParams['start_episode'] ?? 0);
  11733. $endEpisode = (int)($taskParams['end_episode'] ?? 0);
  11734. if ($startEpisode < 1 || $endEpisode < $startEpisode) {
  11735. continue;
  11736. }
  11737. $details = DB::table('mp_batch_episode_generation_details')
  11738. ->where('anime_id', $animeId)
  11739. ->whereBetween('episode_number', [$startEpisode, $endEpisode])
  11740. ->get();
  11741. // 该批次范围内存在缺失记录,等待下一次检查
  11742. if ($details->isEmpty() || $details->count() < ($endEpisode - $startEpisode + 1)) {
  11743. continue;
  11744. }
  11745. $completedEpisodes = [];
  11746. $failedEpisodes = [];
  11747. $allFinished = true;
  11748. foreach ($details as $detail) {
  11749. if ($detail->status === 'completed') {
  11750. $completedEpisodes[] = $detail->episode_number;
  11751. } elseif ($detail->status === 'failed') {
  11752. $failedEpisodes[] = [
  11753. 'episode_number' => $detail->episode_number,
  11754. 'error_message' => $detail->error_message ?? '',
  11755. ];
  11756. } else {
  11757. // pending/processing(防御处理,正常不会走到)
  11758. $allFinished = false;
  11759. break;
  11760. }
  11761. }
  11762. if (!$allFinished) {
  11763. continue;
  11764. }
  11765. $result = json_encode([
  11766. 'anime_id' => $animeId,
  11767. 'start_episode' => $startEpisode,
  11768. 'end_episode' => $endEpisode,
  11769. 'total_episodes' => count($details),
  11770. 'completed_count' => count($completedEpisodes),
  11771. 'failed_count' => count($failedEpisodes),
  11772. 'completed_episodes' => $completedEpisodes,
  11773. 'failed_episodes' => $failedEpisodes,
  11774. ], JSON_UNESCAPED_UNICODE);
  11775. DB::table('mp_task_center')
  11776. ->where('id', $task->id)
  11777. ->update([
  11778. 'status' => !empty($failedEpisodes) ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  11779. 'result' => $result,
  11780. 'error_message' => !empty($failedEpisodes) ? ('有 ' . count($failedEpisodes) . ' 集生成失败') : null,
  11781. 'updated_at' => date('Y-m-d H:i:s'),
  11782. ]);
  11783. $updated++;
  11784. dLog('command')->info('批量生成分集任务已完成,更新任务中心', [
  11785. 'task_center_id' => $task->id,
  11786. 'anime_id' => $animeId,
  11787. 'start_episode' => $startEpisode,
  11788. 'end_episode' => $endEpisode,
  11789. ]);
  11790. } catch (\Exception $e) {
  11791. dLog('command')->error('更新批量生成分集任务中心异常', [
  11792. 'task_center_id' => $task->id,
  11793. 'anime_id' => $animeId,
  11794. 'error' => $e->getMessage(),
  11795. ]);
  11796. }
  11797. }
  11798. return $updated;
  11799. }
  11800. /**
  11801. * 获取批量生成任务状态
  11802. *
  11803. * @param array $data 请求数据
  11804. * @return array 任务状态信息
  11805. */
  11806. public function getBatchGenerationTaskStatus($data) {
  11807. $anime_id = getProp($data, 'anime_id');
  11808. if (!$anime_id) {
  11809. Utils::throwError('20003:anime_id参数缺失');
  11810. }
  11811. // 获取该anime的所有任务
  11812. $tasks = DB::table('mp_batch_episode_generation_details')
  11813. ->where('anime_id', $anime_id)
  11814. ->orderBy('episode_number')
  11815. ->get()
  11816. ->map(function($item) {
  11817. return [
  11818. 'id' => $item->id,
  11819. 'episode_number' => $item->episode_number,
  11820. 'status' => $item->status,
  11821. 'error_message' => $item->error_message,
  11822. 'retry_count' => $item->retry_count,
  11823. 'created_at' => $item->created_at,
  11824. 'updated_at' => $item->updated_at,
  11825. 'completed_at' => $item->completed_at
  11826. ];
  11827. })
  11828. ->toArray();
  11829. if (empty($tasks)) {
  11830. Utils::throwError('20003:该剧集没有批量生成任务');
  11831. }
  11832. // 统计各状态数量
  11833. $totalCount = count($tasks);
  11834. $pendingCount = 0;
  11835. $processingCount = 0;
  11836. $completedCount = 0;
  11837. $failedCount = 0;
  11838. $failed_episodes = [];
  11839. foreach ($tasks as $task) {
  11840. switch ($task['status']) {
  11841. case 'pending':
  11842. $pendingCount++;
  11843. break;
  11844. case 'processing':
  11845. $processingCount++;
  11846. break;
  11847. case 'completed':
  11848. $completedCount++;
  11849. break;
  11850. case 'failed':
  11851. $failedCount++;
  11852. // 组装失败分集对象(新对象):分集序号、错误原因
  11853. $failed_episodes[] = [
  11854. 'episode_number' => $task['episode_number'],
  11855. 'error_message' => $task['error_message'] ?? ''
  11856. ];
  11857. break;
  11858. }
  11859. }
  11860. // 计算进度百分比
  11861. $progress = 0;
  11862. if ($totalCount > 0) {
  11863. $progress = round(($completedCount / $totalCount) * 100, 2);
  11864. }
  11865. // 判断整体状态
  11866. $overallStatus = 'processing';
  11867. if ($completedCount === $totalCount) {
  11868. $overallStatus = 'completed';
  11869. } elseif ($pendingCount === $totalCount) {
  11870. $overallStatus = 'pending';
  11871. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  11872. $overallStatus = 'failed';
  11873. }
  11874. return [
  11875. 'anime_id' => $anime_id,
  11876. 'total_episodes' => $totalCount,
  11877. 'pending_count' => $pendingCount,
  11878. 'processing_count' => $processingCount,
  11879. 'completed_count' => $completedCount,
  11880. 'failed_count' => $failedCount,
  11881. 'progress' => $progress,
  11882. 'overall_status' => $overallStatus,
  11883. 'failed_episodes' => $failed_episodes,
  11884. 'tasks' => $tasks
  11885. ];
  11886. }
  11887. /**
  11888. * 将生成内容中不在强制列表中的资源合并进强制列表
  11889. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  11890. *
  11891. * @param array $generated 生成内容中的资源列表
  11892. * @param array $forced 强制资源列表(key为资源名称)
  11893. * @param string $type 资源类型:role、scene、prop
  11894. * @return array
  11895. */
  11896. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  11897. {
  11898. foreach ($generated as $item) {
  11899. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  11900. if ($name === null || $name === '') {
  11901. continue;
  11902. }
  11903. if ($name === '旁白') {
  11904. continue;
  11905. }
  11906. if (!isset($forced[$name])) {
  11907. $forced[$name] = $item;
  11908. }
  11909. }
  11910. return $forced;
  11911. }
  11912. /**
  11913. * 智能匹配并替换主体和场景名称
  11914. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  11915. *
  11916. * @param array $episode_arr 解析后的剧集数据
  11917. * @param array $extra_roles 强制主体设定(key为主体名称)
  11918. * @param array $extra_scenes 强制场景设定(key为场景名称)
  11919. * @return array 替换后的剧集数据
  11920. */
  11921. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  11922. $replaced_count = 0;
  11923. // 1. 处理主体列表
  11924. if (!empty($episode_arr['roles'])) {
  11925. foreach ($episode_arr['roles'] as &$role) {
  11926. $generated_role_name = $role['role'] ?? '';
  11927. // 跳过旁白
  11928. if ($generated_role_name === '旁白') {
  11929. continue;
  11930. }
  11931. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  11932. if (!isset($extra_roles[$generated_role_name])) {
  11933. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  11934. if ($matched_role) {
  11935. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  11936. $role['role'] = $matched_role;
  11937. $replaced_count++;
  11938. }
  11939. }
  11940. }
  11941. }
  11942. // 2. 处理场景列表
  11943. if (!empty($episode_arr['scenes'])) {
  11944. foreach ($episode_arr['scenes'] as &$scene) {
  11945. $generated_scene_name = $scene['scene'] ?? '';
  11946. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  11947. if (!isset($extra_scenes[$generated_scene_name])) {
  11948. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  11949. if ($matched_scene) {
  11950. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  11951. $scene['scene'] = $matched_scene;
  11952. $replaced_count++;
  11953. }
  11954. }
  11955. }
  11956. }
  11957. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  11958. if (!empty($episode_arr['acts'])) {
  11959. foreach ($episode_arr['acts'] as &$act) {
  11960. if (!empty($act['segments'])) {
  11961. foreach ($act['segments'] as &$segment) {
  11962. if (!empty($segment['segment_content'])) {
  11963. $original_content = $segment['segment_content'];
  11964. $replaced_content = $original_content;
  11965. // 替换场景名 - 在文本中查找并替换
  11966. foreach (array_keys($extra_scenes) as $full_scene_name) {
  11967. // 尝试找到可能的短名称
  11968. $potential_short_names = [];
  11969. // 提取场景名的主要部分(冒号之前)
  11970. if (mb_strpos($full_scene_name, ':') !== false) {
  11971. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  11972. $potential_short_names[] = $short_name;
  11973. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  11974. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  11975. $potential_short_names[] = $short_name;
  11976. }
  11977. // 替换场景字段中的短名称
  11978. foreach ($potential_short_names as $short_name) {
  11979. if ($short_name !== $full_scene_name) {
  11980. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  11981. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  11982. if ($new_content !== $replaced_content) {
  11983. $replaced_content = $new_content;
  11984. $replaced_count++;
  11985. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  11986. }
  11987. }
  11988. }
  11989. }
  11990. // 替换配音角色名(跳过旁白)
  11991. foreach (array_keys($extra_roles) as $full_role_name) {
  11992. if ($full_role_name === '旁白') {
  11993. continue;
  11994. }
  11995. // 尝试找到可能的短名称
  11996. $potential_short_names = [];
  11997. // 提取角色名的主要部分(短横线之前)
  11998. if (mb_strpos($full_role_name, '-') !== false) {
  11999. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  12000. $potential_short_names[] = $short_name;
  12001. }
  12002. // 替换配音台词中的短名称
  12003. foreach ($potential_short_names as $short_name) {
  12004. if ($short_name !== $full_role_name) {
  12005. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  12006. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  12007. if ($new_content !== $replaced_content) {
  12008. $replaced_content = $new_content;
  12009. $replaced_count++;
  12010. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  12011. }
  12012. }
  12013. }
  12014. }
  12015. // 如果有替换,更新segment_content
  12016. if ($replaced_content !== $original_content) {
  12017. $segment['segment_content'] = $replaced_content;
  12018. }
  12019. }
  12020. }
  12021. }
  12022. }
  12023. }
  12024. if ($replaced_count > 0) {
  12025. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  12026. 'replaced_count' => $replaced_count
  12027. ]);
  12028. }
  12029. return $episode_arr;
  12030. }
  12031. /**
  12032. * 查找匹配的名称
  12033. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  12034. *
  12035. * @param string $generated_name 生成的名称
  12036. * @param array $expected_names 预期的名称列表
  12037. * @return string|null 匹配到的名称,如果没有匹配则返回null
  12038. */
  12039. private function findMatchingName($generated_name, $expected_names) {
  12040. if (empty($generated_name)) {
  12041. return null;
  12042. }
  12043. // 尝试精确匹配
  12044. if (in_array($generated_name, $expected_names)) {
  12045. return $generated_name;
  12046. }
  12047. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  12048. foreach ($expected_names as $expected_name) {
  12049. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  12050. if (mb_strpos($expected_name, $generated_name) === 0) {
  12051. return $expected_name;
  12052. }
  12053. }
  12054. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  12055. // 这样可以处理一些变体,但优先级较低
  12056. foreach ($expected_names as $expected_name) {
  12057. if (mb_strpos($expected_name, $generated_name) !== false) {
  12058. return $expected_name;
  12059. }
  12060. }
  12061. return null;
  12062. }
  12063. /**
  12064. * 重新生成分段剧本
  12065. * @param array $data 包含以下字段:
  12066. * - prompt: string|null 用户修改要求(可选)
  12067. * - template_id: int|null 提示词模板ID(可选)
  12068. * - act_id: int|null 单个片段ID(与episode_id二选一)
  12069. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  12070. * @return array 返回生成结果
  12071. */
  12072. public function regenerateSegmentScript($data) {
  12073. $uid = Site::getUid();
  12074. $prompt = trim((string)getProp($data, 'prompt', ''));
  12075. $template_id = getProp($data, 'template_id', 0);
  12076. $act_id = getProp($data, 'act_id', 0);
  12077. $episode_id = getProp($data, 'episode_id', 0);
  12078. $check_mode = (int)getProp($data, 'check_mode', 0); // 1=预览确认模式(仅 act_id 模式生效,不落库,返回 editAct 入参)
  12079. // 单片段模式:act_id 可以是数据库真实ID(数字)或预览生成的虚拟ID(字符串),非空即单片段模式
  12080. $isActIdMode = !empty($act_id);
  12081. // 验证:prompt和template_id至少提供一个
  12082. if (empty($prompt) && empty($template_id)) {
  12083. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  12084. }
  12085. // 验证:act_id和episode_id二选一
  12086. if (empty($act_id) && empty($episode_id)) {
  12087. Utils::throwError('20003:请提供片段ID或剧集ID');
  12088. }
  12089. if (!empty($act_id) && !empty($episode_id)) {
  12090. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  12091. }
  12092. // 积分余额预检:act_id 单片段模式按 normal 档,episode_id 剧集模式按 special 档
  12093. $chargeType = $isActIdMode ? 'normal' : 'special';
  12094. if ($isActIdMode) {
  12095. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', $chargeType), $uid);
  12096. } else {
  12097. $is_generated = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('is_generated');
  12098. if ($is_generated) Utils::throwError('20003:该分集已不支持重新生成片段,请创建副本后重试!');
  12099. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', $chargeType), $uid);
  12100. }
  12101. // 如果提供了template_id,获取模板提示词
  12102. $template_prompt = '';
  12103. if ($template_id > 0) {
  12104. $template = DB::table('mp_prompt_templates')
  12105. ->where('id', $template_id)
  12106. ->where('is_deleted', 0)
  12107. ->first();
  12108. if (!$template) {
  12109. Utils::throwError('20003:提示词模板不存在或已删除');
  12110. }
  12111. $template_prompt = $template->template_prompt ?? '';
  12112. }
  12113. // 合并用户提示词和模板提示词(模板提示词与用户输入基本一致时只保留一个,避免重复提示词)
  12114. $final_prompt = '';
  12115. if (!empty($template_prompt)) {
  12116. $trimmedPrompt = trim((string)$prompt);
  12117. if ($trimmedPrompt !== '' && mb_strtolower($trimmedPrompt) === mb_strtolower(trim($template_prompt))) {
  12118. $final_prompt = $template_prompt;
  12119. } elseif (!empty($prompt)) {
  12120. $final_prompt = $template_prompt . "\n\n补充要求:" . $prompt;
  12121. } else {
  12122. $final_prompt = $template_prompt;
  12123. }
  12124. } else {
  12125. $final_prompt = $prompt;
  12126. }
  12127. // 获取需要重新生成的内容参考
  12128. $reference_content = '';
  12129. $target_episode_id = 0;
  12130. $target_anime_id = 0;
  12131. $target_episode_number = 0;
  12132. if ($isActIdMode) {
  12133. // 单个片段模式:获取该片段的内容
  12134. $segment = DB::table('mp_episode_segments')
  12135. ->where('id', $act_id)
  12136. ->first();
  12137. // 数据库不存在时,尝试从预览虚拟 act_id 保存的 redis 数据中恢复
  12138. if (!$segment) {
  12139. $previewData = Redis::get($this->buildActPreviewKey($act_id));
  12140. if ($previewData) {
  12141. $previewData = json_decode($previewData, true);
  12142. $segment = (object)[
  12143. 'anime_id' => getProp($previewData, 'anime_id'),
  12144. 'episode_id' => getProp($previewData, 'episode_id'),
  12145. 'episode_number' => getProp($previewData, 'episode_number'),
  12146. 'act_number' => getProp($previewData, 'act_number'),
  12147. 'act_duration' => getProp($previewData, 'act_duration'),
  12148. 'act_content' => getProp($previewData, 'act_content'),
  12149. ];
  12150. }
  12151. }
  12152. if (!$segment) {
  12153. Utils::throwError('20003:片段不存在');
  12154. }
  12155. $target_episode_id = $segment->episode_id;
  12156. $target_anime_id = $segment->anime_id;
  12157. $target_episode_number = $segment->episode_number;
  12158. $reference_content = $segment->act_content ?? '';
  12159. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  12160. } else {
  12161. // 整个剧集模式:获取所有片段的内容
  12162. $segments = DB::table('mp_episode_segments')
  12163. ->where('episode_id', $episode_id)
  12164. ->orderBy('act_number')
  12165. ->get();
  12166. if ($segments->isEmpty()) {
  12167. Utils::throwError('20003:该剧集没有片段数据');
  12168. }
  12169. $target_episode_id = $episode_id;
  12170. $target_anime_id = $segments[0]->anime_id;
  12171. $target_episode_number = $segments[0]->episode_number;
  12172. // 拼接所有片段内容,保留格式用于AI理解
  12173. $act_contents = [];
  12174. foreach ($segments as $seg) {
  12175. $act_number = $seg->act_number;
  12176. $act_content = $seg->act_content ?? '';
  12177. if (!empty($act_content)) {
  12178. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  12179. }
  12180. }
  12181. $reference_content = implode("\n\n", $act_contents);
  12182. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  12183. if ($episode_content) {
  12184. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【原分段剧本内容】\n{$reference_content}";
  12185. //$reference_content = "\n\n【本集原始内容】\n{$episode_content}";
  12186. }else {
  12187. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  12188. }
  12189. }
  12190. if (empty($reference_content)) {
  12191. Utils::throwError('20003:没有可参考的片段内容');
  12192. }
  12193. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  12194. $episode = DB::table('mp_anime_episodes')
  12195. ->where('id', $target_episode_id)
  12196. ->first();
  12197. if (!$episode) {
  12198. Utils::throwError('20003:剧集不存在');
  12199. }
  12200. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  12201. $anime_script_id = getProp($anime, 'script_id');
  12202. $intro = $episode->intro ?? '';
  12203. $art_style = $episode->art_style ?? '';
  12204. $roles = json_decode($episode->roles ?? '[]', true);
  12205. $scenes = json_decode($episode->scenes ?? '[]', true);
  12206. $props = json_decode($episode->props ?? '[]', true);
  12207. // 构建提示词中的主体列表和场景列表参考
  12208. $roles_ref = '';
  12209. if (!empty($roles) && is_array($roles)) {
  12210. $roles_list = [];
  12211. foreach ($roles as $role) {
  12212. $role_name = getProp($role, 'role', '');
  12213. $role_desc = getProp($role, 'description', '');
  12214. $pic_prompt = getProp($role, 'pic_prompt', '');
  12215. $voice_prompt = getProp($role, 'voice_prompt', '');
  12216. if (!empty($role_name)) {
  12217. $role_line = $role_name;
  12218. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  12219. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  12220. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  12221. $roles_list[] = $role_line;
  12222. }
  12223. }
  12224. if (!empty($roles_list)) {
  12225. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  12226. }
  12227. }
  12228. $scenes_ref = '';
  12229. if (!empty($scenes) && is_array($scenes)) {
  12230. $scenes_list = [];
  12231. foreach ($scenes as $scene) {
  12232. $scene_name = getProp($scene, 'scene', '');
  12233. $scene_desc = getProp($scene, 'description', '');
  12234. $pic_prompt = getProp($scene, 'pic_prompt', '');
  12235. if (!empty($scene_name)) {
  12236. $scene_line = $scene_name;
  12237. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  12238. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  12239. $scenes_list[] = $scene_line;
  12240. }
  12241. }
  12242. if (!empty($scenes_list)) {
  12243. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  12244. }
  12245. }
  12246. $props_ref = '';
  12247. if (!empty($props) && is_array($props)) {
  12248. $props_list = [];
  12249. foreach ($props as $prop) {
  12250. $prop_name = getProp($prop, 'prop', '');
  12251. $prop_desc = getProp($prop, 'description', '');
  12252. $pic_prompt = getProp($prop, 'pic_prompt', '');
  12253. if (!empty($prop_name)) {
  12254. $prop_line = $prop_name;
  12255. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  12256. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  12257. $props_list[] = $prop_line;
  12258. }
  12259. }
  12260. if (!empty($props_list)) {
  12261. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  12262. }
  12263. }
  12264. // 构建美术风格参考
  12265. $art_style_ref = '';
  12266. if (!empty($art_style)) {
  12267. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  12268. }
  12269. // 构建内容简介参考
  12270. $intro_ref = '';
  12271. if (!empty($intro)) {
  12272. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  12273. }
  12274. // 构建完整的AI提示词
  12275. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  12276. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  12277. $user_prompt .= $intro_ref;
  12278. $user_prompt .= $art_style_ref;
  12279. $user_prompt .= $reference_content;
  12280. $user_prompt .= "\n\n【生成要求】\n- 请以【原分段剧本内容】为蓝本,保留剧情脉络、角色、场景与分段结构,但必须围绕【用户要求】对相关片段进行实质性修改;若【用户要求】未指定具体修改点,也需对画面、运镜、台词等描述进行改写,禁止整段原样复制。\n";
  12281. // $user_prompt .= $roles_ref;
  12282. // $user_prompt .= $scenes_ref;
  12283. // 输出格式铁律(用户消息侧再次强制,避免模型自由发挥)
  12284. $user_prompt .= "\n\n【输出格式铁律-必须严格遵守】\n";
  12285. if ($isActIdMode) {
  12286. $user_prompt .= "- 请直接以“##片段1”开头,紧跟“时长:X s”行,然后输出本片段的完整分镜内容(分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效),分镜从1开始连续编号。\n";
  12287. $user_prompt .= "- 只允许根据【原分段剧本内容】生成一个片段(即“##片段1”),禁止生成多个片段。\n";
  12288. } else {
  12289. $user_prompt .= "- 请以“###分段剧本”开头,依次输出“片段数量:N”、“旁白音色:...”,然后按“##片段N”逐段输出,每段必须紧跟“时长:X s”行,再输出该片段的完整分镜内容(分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效),分镜从1开始连续编号。\n";
  12290. }
  12291. $user_prompt .= "- 缺少“##片段N”标题或“时长:”行即为格式错误;输出前必须检查格式,不得输出其他任何内容。\n";
  12292. $user_prompt .= "- 片段时长必须在4秒到15秒之间(4s≤时长≤15s),超过15秒必须拆分为多个片段,不得输出低于4秒或超过15秒的片段。\n";
  12293. // 整集模式:强制生成与原来一致的片段数量
  12294. if ($episode_id > 0 && isset($segments)) {
  12295. $originSegmentCount = count($segments);
  12296. $user_prompt .= "- 本集原有{$originSegmentCount}个片段,必须严格生成{$originSegmentCount}个片段(##片段1 到 ##片段{$originSegmentCount}),不得多不得少。\n";
  12297. }
  12298. $system_prompt = "\n\n【输出格式铁律-最高优先级】\n";
  12299. if ($isActIdMode) {
  12300. $system_prompt .= "- 直接以“##片段1”开头,紧跟“时长:X s”行,然后输出本片段分镜内容\n";
  12301. $system_prompt .= "- 只允许根据【原分段剧本内容】生成一个片段(即“##片段1”),禁止生成多个片段。\n";
  12302. } else {
  12303. $system_prompt .= "- 以“###分段剧本”开头,输出“片段数量:N”、“旁白音色:...”\n";
  12304. $system_prompt .= "- 然后按“##片段N”逐段输出,每段紧跟“时长:X s”行\n";
  12305. }
  12306. $system_prompt .= "- 每个片段必须严格以“##片段N”开头(N从1开始连续),并且必须包含“时长:X s”行,缺少即为格式错误\n";
  12307. $system_prompt .= "- 片段时长必须在4~15秒之间(4s≤时长≤15s),超过15秒必须拆分为多个片段,禁止输出低于4秒或超过15秒的片段\n";
  12308. $system_prompt .= "- 输出前检查:若缺少##片段N标题或时长行,视为输出无效,必须修正后输出\n\n";
  12309. $system_prompt .= "【强制要求】\n";
  12310. // $system_prompt .= "- 请严格参考【本集原始内容】或【原分段剧本内容】进行本次生成,注意新生成的分段剧本内容一定不要跟【原分段剧本内容】一致,要进行一定程度调整\n";
  12311. $system_prompt .= "- 【重要】必须参考【本集原始内容】与【原分段剧本内容】中的剧情脉络、角色、场景、道具和分段结构,但严禁原样复制或几乎照抄原文;必须围绕【用户要求】对相关内容进行实质性修改,若生成结果与【原分段剧本内容】完全一致或未体现用户要求,视为生成失败\n";
  12312. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:\n";
  12313. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)\n";
  12314. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  12315. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  12316. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  12317. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  12318. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  12319. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  12320. $system_prompt .= "- 【重要】每个片段必须以“##片段N”开头(N为序号),并且必须包含“时长:X s”行,缺少片段标题或时长视为格式错误\n";
  12321. // 按模式构造强制输出格式:只传 act_id(单片段)时不需要 ###分段剧本/片段数量/旁白音色;传 episode_id(整集)时需要完整格式
  12322. $segmentHeader = '';
  12323. if ($episode_id > 0) {
  12324. $segmentHeader = "###分段剧本\n片段数量:8\n旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。\n\n";
  12325. }
  12326. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:\n" . $segmentHeader . "##片段1\n时长:12s\n分镜1\n出场角色:刀疤脸\n场景:边境小镇街道\n出场道具:酒杯-高脚杯\n画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。\n运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。\n配音台词:\n背景音效:\n\n分镜2\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。\n运镜:缓慢横移,掠过阴影中瑟缩的食客。\n配音台词:\n背景音效:\n\n分镜3\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。\n运镜:从中景推向令牌特写。\n配音台词:\n背景音效:\n\n分镜4\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。\n运镜:极速推向酒水溅起的瞬间。\n配音台词:\n背景音效:\n\n分镜5\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。\n运镜:固定机位,利用倾斜构图制造压迫感。\n配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?\n背景音效:";
  12327. // 获取模型配置
  12328. $model = getProp($data, 'model');
  12329. if (!$model) {
  12330. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  12331. }
  12332. // 验证模型是否在可用模型表中
  12333. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  12334. $model = 'deepseek-v4-pro';
  12335. }
  12336. // 模型兼容性处理
  12337. $thinkingMode = 'disabled';
  12338. $reasoningEffort = 'high';
  12339. if ($model === 'deepseek-chat') {
  12340. $model = 'deepseek-v4-flash';
  12341. $thinkingMode = 'disabled';
  12342. } elseif ($model === 'deepseek-reasoner') {
  12343. $model = 'deepseek-v4-flash';
  12344. $thinkingMode = 'enabled';
  12345. }
  12346. // 构建消息
  12347. $messages = [
  12348. [
  12349. 'role' => 'system',
  12350. 'content' => $system_prompt
  12351. ],
  12352. [
  12353. 'role' => 'user',
  12354. 'content' => $user_prompt
  12355. ]
  12356. ];
  12357. // dd($messages);
  12358. // 构建请求参数
  12359. $post_data = [
  12360. 'model' => $model,
  12361. 'messages' => $messages,
  12362. 'temperature' => 1.35,
  12363. 'frequency_penalty' => 0.3,
  12364. 'presence_penalty' => 0,
  12365. 'response_format' => ['type' => 'text'],
  12366. 'thinking' => ['type' => $thinkingMode],
  12367. 'stream' => false // 非流式输出
  12368. ];
  12369. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  12370. // 调用AI生成新的分段剧本
  12371. try {
  12372. $fullContent = '';
  12373. $usage = [];
  12374. // 根据模型类型选择调用方法
  12375. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  12376. if (is_array($chatResult)) {
  12377. $fullContent = $chatResult['fullContent'] ?? '';
  12378. $usage = $chatResult['usage'] ?? [];
  12379. }
  12380. $generated_content = $fullContent;
  12381. // 归一化"场景:"标签换行格式:场景:\n场景名\n => 场景:场景名\n,保证场景字段为一行
  12382. $generated_content = preg_replace('/场景[::]\s*\n\s*([^\n]+)/u', '场景:$1', $generated_content);
  12383. if (empty($generated_content)) {
  12384. Utils::throwError('20003:AI生成内容为空,请重试');
  12385. }
  12386. dLog('deepseek')->info('regenerateSegmentScript AI生成内容', [
  12387. 'act_id' => $act_id,
  12388. 'episode_id' => $episode_id,
  12389. 'content_length' => mb_strlen($generated_content),
  12390. 'content_head' => mb_substr($generated_content, 0, 500),
  12391. 'content_tail' => mb_substr($generated_content, -200),
  12392. ]);
  12393. // 解析生成的内容 - 按片段分割
  12394. $parsed_segments = [];
  12395. // 先在开头添加换行符,确保第1片段也能被正确分割
  12396. $normalizedText = "\n" . $generated_content;
  12397. $parts = preg_split('/\n\s*##/', $normalizedText);
  12398. foreach ($parts as $part) {
  12399. $part = trim($part);
  12400. if (empty($part)) continue;
  12401. // 匹配"片段X"格式
  12402. if (!preg_match('/^片段\d+/', $part)) {
  12403. continue;
  12404. }
  12405. // 分离标题和内容
  12406. $lines = explode("\n", $part, 2);
  12407. $actTitle = trim($lines[0]);
  12408. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  12409. // 解析标题,提取序号
  12410. $actNumber = 0;
  12411. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  12412. $actNumber = intval($segmentTitleMatch[1]);
  12413. } else {
  12414. $actNumber = count($parsed_segments) + 1;
  12415. }
  12416. // 提取时长(仅保留数字)
  12417. $actDuration = 0;
  12418. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  12419. $actDurationStr = trim($actDurationMatch[1]);
  12420. // 提取数字部分(支持整数和小数)
  12421. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  12422. $actDuration = (float)$numMatch[1];
  12423. }
  12424. }
  12425. // 时长范围约束:4~15秒,超限兜底修正(0=未知按最低4秒)
  12426. if ($actDuration > 15) {
  12427. $actDuration = 15;
  12428. }
  12429. if ($actDuration < 4) {
  12430. $actDuration = 4;
  12431. }
  12432. // 清理act_content:去除时长、旁白音色等非分镜内容行,只保留分镜内容
  12433. $cleaned_content = $this->cleanSegmentContent($actContent);
  12434. $parsed_segments[] = [
  12435. 'act_number' => $actNumber,
  12436. 'act_title' => $actTitle,
  12437. 'act_duration' => $actDuration,
  12438. 'act_content' => $cleaned_content,
  12439. ];
  12440. }
  12441. // 兜底:模型未输出 ##片段N 标题时(如直接输出分镜正文),将整个生成内容作为单个片段解析(act_id 单片段场景)
  12442. if (empty($parsed_segments)) {
  12443. $fallbackContent = $this->cleanSegmentContent($generated_content);
  12444. if ($fallbackContent !== '') {
  12445. $fallbackDuration = 0;
  12446. if (preg_match('/时长[::]\s*([^\n]+)/u', $generated_content, $durationMatch)) {
  12447. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $durationMatch[1], $numMatch)) {
  12448. $fallbackDuration = (float)$numMatch[1];
  12449. }
  12450. }
  12451. // 内容未带时长时,单片段模式沿用原片段的时长
  12452. if ($fallbackDuration <= 0 && $isActIdMode && !empty($segment->act_duration)) {
  12453. $fallbackDuration = (float)$segment->act_duration;
  12454. }
  12455. // 时长范围约束:4~15秒,超限兜底修正(0=未知按最低4秒)
  12456. if ($fallbackDuration > 15) {
  12457. $fallbackDuration = 15;
  12458. }
  12459. if ($fallbackDuration < 4) {
  12460. $fallbackDuration = 4;
  12461. }
  12462. $parsed_segments[] = [
  12463. 'act_number' => 1,
  12464. 'act_title' => '片段1',
  12465. 'act_duration' => $fallbackDuration,
  12466. 'act_content' => $fallbackContent,
  12467. ];
  12468. }
  12469. }
  12470. // act_id 单片段模式:只允许一个片段,多余片段丢弃,仅保留第一个
  12471. if ($isActIdMode && count($parsed_segments) > 1) {
  12472. dLog('deepseek')->info('regenerateSegmentScript act_id 模式仅保留第一个片段', [
  12473. 'act_id' => $act_id,
  12474. 'original_count' => count($parsed_segments),
  12475. ]);
  12476. $parsed_segments = array_slice($parsed_segments, 0, 1);
  12477. }
  12478. dLog('deepseek')->info('regenerateSegmentScript 解析结果', [
  12479. 'act_id' => $act_id,
  12480. 'episode_id' => $episode_id,
  12481. 'segment_count' => count($parsed_segments),
  12482. 'segments' => array_map(function ($seg) {
  12483. return [
  12484. 'act_number' => $seg['act_number'],
  12485. 'act_duration' => $seg['act_duration'],
  12486. 'content_length' => mb_strlen($seg['act_content']),
  12487. ];
  12488. }, $parsed_segments),
  12489. ]);
  12490. if (empty($parsed_segments)) {
  12491. dLog('deepseek')->error('regenerateSegmentScript 无法解析生成的分段剧本', [
  12492. 'act_id' => $act_id,
  12493. 'episode_id' => $episode_id,
  12494. 'content_length' => mb_strlen($generated_content),
  12495. 'content_head' => mb_substr($generated_content, 0, 1000),
  12496. 'content_tail' => mb_substr($generated_content, -300),
  12497. ]);
  12498. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  12499. }
  12500. // 收集所有资产名称(角色、场景、道具)
  12501. $product_names = [];
  12502. // 收集角色名称
  12503. if (!empty($roles) && is_array($roles)) {
  12504. foreach ($roles as $role) {
  12505. $role_name = getProp($role, 'role', '');
  12506. if (!empty($role_name)) {
  12507. $product_names[] = $role_name;
  12508. }
  12509. }
  12510. }
  12511. // 收集场景名称
  12512. if (!empty($scenes) && is_array($scenes)) {
  12513. foreach ($scenes as $scene) {
  12514. $scene_name = getProp($scene, 'scene', '');
  12515. if (!empty($scene_name)) {
  12516. $product_names[] = $scene_name;
  12517. }
  12518. }
  12519. }
  12520. // 收集道具名称
  12521. if (!empty($props) && is_array($props)) {
  12522. foreach ($props as $prop) {
  12523. $prop_name = getProp($prop, 'prop', '');
  12524. if (!empty($prop_name)) {
  12525. $product_names[] = $prop_name;
  12526. }
  12527. }
  12528. }
  12529. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  12530. $product_names = array_unique($product_names);
  12531. usort($product_names, function($a, $b) {
  12532. return mb_strlen($b) - mb_strlen($a);
  12533. });
  12534. // 处理每个片段的 act_show_content
  12535. foreach ($parsed_segments as &$segment) {
  12536. $act_content = getProp($segment, 'act_content', '');
  12537. if (empty($act_content)) {
  12538. $segment['act_show_content'] = '';
  12539. continue;
  12540. }
  12541. $processed_content = $act_content;
  12542. // 统一替换所有资产名称为 {资产名} 格式
  12543. // 使用占位符避免嵌套替换问题
  12544. $placeholder_map = [];
  12545. $placeholder_index = 0;
  12546. foreach ($product_names as $product_name) {
  12547. // 转义特殊字符
  12548. $escaped_product = preg_quote($product_name, '/');
  12549. // 检查是否匹配且未被 {} 包裹
  12550. $processed_content = preg_replace_callback(
  12551. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  12552. function($matches) use (&$placeholder_map, &$placeholder_index) {
  12553. // 使用唯一占位符
  12554. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  12555. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  12556. $placeholder_index++;
  12557. return $placeholder;
  12558. },
  12559. $processed_content
  12560. );
  12561. }
  12562. // 将所有占位符替换回实际内容
  12563. foreach ($placeholder_map as $placeholder => $replacement) {
  12564. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  12565. }
  12566. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  12567. $shot_counter = 0;
  12568. $processed_content = preg_replace_callback(
  12569. // 兼容“【镜头 1】”“【分镜 1】”等分镜/镜头与数字间带空格的情况
  12570. '/【(?:镜头|分镜)\s*(\d+)】/u',
  12571. function($matches) use (&$shot_counter) {
  12572. $shot_counter++;
  12573. return '【镜头' . $shot_counter . '】';
  12574. },
  12575. $processed_content
  12576. );
  12577. $segment['act_show_content'] = $processed_content;
  12578. }
  12579. unset($segment); // 解除引用
  12580. // 保存到数据库
  12581. $now = date('Y-m-d H:i:s');
  12582. $saved_acts = []; // 用于记录保存后的片段信息
  12583. if ($isActIdMode) {
  12584. // 单个片段模式:更新单条记录
  12585. if (count($parsed_segments) > 0) {
  12586. $new_segment = $parsed_segments[0];
  12587. // 预览确认模式(check_mode=1):不落库,组装 editAct 入参返回,由前端确认后调用 editAct 更新
  12588. if ($check_mode === 1) {
  12589. // 单片段预览生成即按 normal 档扣费
  12590. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12591. 'anime_id' => $target_anime_id,
  12592. 'episode_id' => $target_episode_id,
  12593. 'model' => $model,
  12594. 'source' => 'regenerateSegmentScript',
  12595. ], 'normal');
  12596. return [
  12597. 'check_mode' => 1,
  12598. 'act_id' => $act_id,
  12599. 'act_title' => getProp($new_segment, 'act_title', ''),
  12600. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  12601. 'act_content' => getProp($new_segment, 'act_show_content', ''),
  12602. ];
  12603. }
  12604. // 虚拟 act_id 仅用于预览/参考,不允许直接保存到数据库
  12605. if (!is_numeric($act_id)) {
  12606. Utils::throwError('20003:该片段不可直接保存');
  12607. }
  12608. $update_data = [
  12609. 'act_content' => getProp($new_segment, 'act_content', ''),
  12610. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  12611. 'act_title' => getProp($new_segment, 'act_title', ''),
  12612. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  12613. 'updated_at' => $now,
  12614. ];
  12615. DB::table('mp_episode_segments')
  12616. ->where('id', $act_id)
  12617. ->update($update_data);
  12618. // 获取更新后的记录
  12619. $updated_act = DB::table('mp_episode_segments')
  12620. ->where('id', $act_id)
  12621. ->first();
  12622. if ($updated_act) {
  12623. $saved_acts[] = [
  12624. 'act_id' => $updated_act->id,
  12625. 'act_number' => $updated_act->act_number,
  12626. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  12627. 'act_content' => $updated_act->act_content,
  12628. 'act_show_content' => $updated_act->act_show_content,
  12629. 'video_url' => $updated_act->video_url ?? '',
  12630. 'video_duration' => $updated_act->video_duration ?? 0,
  12631. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  12632. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  12633. ];
  12634. }
  12635. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  12636. // 单片段模式成功扣费(normal 档)
  12637. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12638. 'anime_id' => $target_anime_id,
  12639. 'episode_id' => $target_episode_id,
  12640. 'model' => $model,
  12641. 'source' => 'regenerateSegmentScript',
  12642. ], 'normal');
  12643. }
  12644. } else {
  12645. // 预览确认模式(check_mode=1):不落库,返回展示参数供前端确认后调用 saveEpisodeActs 保存
  12646. if ($check_mode === 1) {
  12647. // 剧集模式预览生成即扣除积分并记录 token 明细(special 档)
  12648. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12649. 'anime_id' => $target_anime_id,
  12650. 'episode_id' => $target_episode_id,
  12651. 'model' => $model,
  12652. 'source' => 'regenerateSegmentScript',
  12653. ], 'special');
  12654. // 为每个片段生成虚拟 act_id 并写入 redis(1天有效),供后续按虚拟 act_id 恢复片段数据
  12655. $previewActs = [];
  12656. foreach ($parsed_segments as $seg) {
  12657. $virtualActId = 'preview_' . time() . '_' . uniqid();
  12658. Redis::setex($this->buildActPreviewKey($virtualActId), 86400, json_encode([
  12659. 'anime_id' => $target_anime_id,
  12660. 'episode_id' => $target_episode_id,
  12661. 'episode_number' => $target_episode_number,
  12662. 'act_number' => $seg['act_number'],
  12663. 'act_title' => $seg['act_title'],
  12664. 'act_duration' => $seg['act_duration'],
  12665. 'act_content' => $seg['act_content'],
  12666. 'act_show_content'=> $seg['act_show_content'],
  12667. ], JSON_UNESCAPED_UNICODE));
  12668. $previewActs[] = [
  12669. 'act_id' => $virtualActId,
  12670. 'act_number' => $seg['act_number'],
  12671. 'act_title' => $seg['act_title'],
  12672. 'act_duration' => $seg['act_duration'],
  12673. 'act_content' => $seg['act_content'],
  12674. 'act_show_content' => $seg['act_show_content'],
  12675. 'video_url' => '',
  12676. 'video_duration' => 0,
  12677. 'video_time_point_start' => 0,
  12678. 'video_time_point_end' => 0,
  12679. 'last_frame_url' => '',
  12680. 'current_type' => 0,
  12681. ];
  12682. }
  12683. return [
  12684. 'check_mode' => 1,
  12685. 'anime_id' => $target_anime_id,
  12686. 'episode_id' => $target_episode_id,
  12687. 'title' => getProp($episode, 'title', ''),
  12688. 'episode_number' => $target_episode_number,
  12689. 'is_generated' => getProp($episode, 'is_generated', 0),
  12690. 'acts' => $previewActs,
  12691. ];
  12692. }
  12693. // 整个剧集模式:删除原有记录并批量保存新记录
  12694. DB::beginTransaction();
  12695. try {
  12696. // 删除原有的所有片段记录
  12697. DB::table('mp_episode_segments')
  12698. ->where('episode_id', $target_episode_id)
  12699. ->delete();
  12700. // 批量插入新的片段记录
  12701. $segments_to_insert = [];
  12702. foreach ($parsed_segments as $index => $segment) {
  12703. $act_number = $index + 1;
  12704. $segments_to_insert[] = [
  12705. 'anime_id' => $target_anime_id,
  12706. 'episode_id' => $target_episode_id,
  12707. 'episode_number' => $target_episode_number,
  12708. 'act_number' => $act_number,
  12709. 'act_title' => getProp($segment, 'act_title', ''),
  12710. 'act_duration' => getProp($segment, 'act_duration', 0),
  12711. 'act_content' => getProp($segment, 'act_content', ''),
  12712. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  12713. 'created_at' => $now,
  12714. 'updated_at' => $now,
  12715. ];
  12716. }
  12717. if (!empty($segments_to_insert)) {
  12718. DB::table('mp_episode_segments')->insert($segments_to_insert);
  12719. }
  12720. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(special 档,与保存同事务)
  12721. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12722. 'anime_id' => $target_anime_id,
  12723. 'episode_id' => $target_episode_id,
  12724. 'model' => $model,
  12725. 'source' => 'regenerateSegmentScript',
  12726. ], 'special');
  12727. DB::commit();
  12728. // 查询保存后的所有片段记录
  12729. $saved_segments = DB::table('mp_episode_segments')
  12730. ->where('episode_id', $target_episode_id)
  12731. ->orderBy('act_number')
  12732. ->get();
  12733. foreach ($saved_segments as $saved_segment) {
  12734. $saved_acts[] = [
  12735. 'act_id' => $saved_segment->id,
  12736. 'act_number' => $saved_segment->act_number,
  12737. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  12738. 'act_content' => $saved_segment->act_content,
  12739. 'act_show_content' => $saved_segment->act_show_content,
  12740. 'video_url' => $saved_segment->video_url ?? '',
  12741. 'video_duration' => $saved_segment->video_duration ?? 0,
  12742. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  12743. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  12744. ];
  12745. }
  12746. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  12747. 'episode_id' => $target_episode_id,
  12748. 'segments_count' => count($segments_to_insert)
  12749. ]);
  12750. } catch (\Exception $e) {
  12751. DB::rollBack();
  12752. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  12753. Utils::throwError('20003:保存失败,请重试');
  12754. }
  12755. }
  12756. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  12757. return [
  12758. 'anime_id' => $target_anime_id,
  12759. 'episode_id' => $target_episode_id,
  12760. 'title' => getProp($episode, 'title', ''),
  12761. 'episode_number' => $target_episode_number,
  12762. 'is_generated' => getProp($episode, 'is_generated', 0),
  12763. 'acts' => $saved_acts,
  12764. ];
  12765. } catch (\Exception $e) {
  12766. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  12767. throw $e;
  12768. }
  12769. }
  12770. /**
  12771. * 保存剧集片段(预览确认模式使用):删除旧数据并批量保存新数据到 mp_episode_segments
  12772. *
  12773. * 逻辑与 regenerateSegmentScript 的 episode_id + check_mode=0 保存保持一致。
  12774. *
  12775. * @param array $data 请求参数:episode_id 必填,acts 必填(预览返回的片段数组)
  12776. * @return array
  12777. */
  12778. public function saveEpisodeActs($data) {
  12779. $uid = Site::getUid();
  12780. $episode_id = (int)getProp($data, 'episode_id', 0);
  12781. $acts = getProp($data, 'acts', []);
  12782. if (!$episode_id) {
  12783. Utils::throwError('20003:请提供剧集ID');
  12784. }
  12785. if (!is_array($acts) || empty($acts)) {
  12786. Utils::throwError('20003:请提供片段数据');
  12787. }
  12788. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  12789. if (!$episode) {
  12790. Utils::throwError('20003:剧集不存在');
  12791. }
  12792. // 用户校验:只能调整自己的剧集
  12793. $anime = DB::table('mp_animes')->where('id', $episode->anime_id)->first();
  12794. if (!$anime || (int)$anime->user_id !== (int)$uid) {
  12795. Utils::throwError('20003:没有权限操作该剧集');
  12796. }
  12797. $anime_id = (int)$episode->anime_id;
  12798. $episode_number = (int)$episode->episode_number;
  12799. $now = date('Y-m-d H:i:s');
  12800. try {
  12801. DB::beginTransaction();
  12802. // 删除原有的所有片段记录
  12803. DB::table('mp_episode_segments')
  12804. ->where('episode_id', $episode_id)
  12805. ->delete();
  12806. // 批量插入新的片段记录
  12807. $segments_to_insert = [];
  12808. $index = 0;
  12809. foreach ($acts as $act) {
  12810. if (!is_array($act)) {
  12811. continue;
  12812. }
  12813. $index++;
  12814. $segments_to_insert[] = [
  12815. 'anime_id' => $anime_id,
  12816. 'episode_id' => $episode_id,
  12817. 'episode_number' => $episode_number,
  12818. 'act_number' => (int)getProp($act, 'act_number', $index),
  12819. 'act_title' => (string)getProp($act, 'act_title', ''),
  12820. 'act_duration' => (float)getProp($act, 'act_duration', 0),
  12821. 'act_content' => (string)getProp($act, 'act_content', ''),
  12822. // 'act_show_content' => (string)getProp($act, 'act_show_content', ''),
  12823. 'created_at' => $now,
  12824. 'updated_at' => $now,
  12825. ];
  12826. }
  12827. if (empty($segments_to_insert)) {
  12828. DB::rollBack();
  12829. Utils::throwError('20003:没有有效的片段数据');
  12830. }
  12831. DB::table('mp_episode_segments')->insert($segments_to_insert);
  12832. DB::commit();
  12833. } catch (\Exception $e) {
  12834. DB::rollBack();
  12835. dLog('deepseek')->error('保存剧集片段失败: ' . $e->getMessage(), [
  12836. 'episode_id' => $episode_id,
  12837. ]);
  12838. Utils::throwError('20003:保存失败,请重试');
  12839. }
  12840. // 查询保存后的所有片段记录(数组化,与 episodeInfoForAce 处理一致)
  12841. $saved_segments = DB::table('mp_episode_segments')
  12842. ->where('episode_id', $episode_id)
  12843. ->orderBy('act_number')
  12844. ->get()
  12845. ->map(function ($value) {
  12846. return (array)$value;
  12847. })
  12848. ->toArray();
  12849. // 构造与 episodeInfoForAce 一致的 acts 与 total_duration
  12850. $acts = [];
  12851. $totalDuration = 0;
  12852. foreach ($saved_segments as $segment) {
  12853. $videoDuration = getProp($segment, 'video_duration');
  12854. $actDuration = getProp($segment, 'act_duration');
  12855. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  12856. $totalDuration += floatval($videoDuration);
  12857. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  12858. $totalDuration += floatval($actDuration);
  12859. } else {
  12860. $totalDuration += 5;
  12861. }
  12862. $acts[] = [
  12863. 'act_id' => getProp($segment, 'id'),
  12864. 'act_number' => getProp($segment, 'act_number'),
  12865. 'act_title' => getProp($segment, 'act_title'),
  12866. 'act_duration' => getProp($segment, 'act_duration'),
  12867. 'act_content' => getProp($segment, 'act_content'),
  12868. 'video_url' => getProp($segment, 'video_url'),
  12869. 'video_duration' => getProp($segment, 'video_duration', 0),
  12870. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  12871. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  12872. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  12873. 'current_type' => getProp($segment, 'current_type'),
  12874. ];
  12875. }
  12876. // 顶层与 episodeInfoForAce 一致
  12877. $result = [
  12878. 'episode_id' => $episode_id,
  12879. 'anime_id' => $anime_id,
  12880. 'episode_number' => $episode_number,
  12881. 'title' => getProp($episode, 'title'),
  12882. 'intro' => getProp($episode, 'intro'),
  12883. 'art_style' => getProp($episode, 'art_style'),
  12884. 'roles' => json_decode(getProp($episode, 'roles', '[]'), true),
  12885. 'scenes' => json_decode(getProp($episode, 'scenes', '[]'), true),
  12886. 'props' => getProp($episode, 'props') ? json_decode(getProp($episode, 'props'), true) : [],
  12887. 'is_generated' => getProp($episode, 'is_generated'),
  12888. 'acts' => array_values($acts),
  12889. 'total_duration' => intval(round($totalDuration)),
  12890. ];
  12891. // video_params(从 mp_animes 取,与 episodeInfoForAce 一致)
  12892. $animeRow = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  12893. $result['video_params'] = [
  12894. 'video_model' => getProp($animeRow, 'video_model'),
  12895. 'video_resolution' => getProp($animeRow, 'video_resolution'),
  12896. 'ratio' => getProp($animeRow, 'video_ratio'),
  12897. ];
  12898. return $result;
  12899. }
  12900. /**
  12901. * 预览虚拟 act_id 在 redis 中的键
  12902. *
  12903. * @param mixed $actId
  12904. * @return string
  12905. */
  12906. private function buildActPreviewKey($actId): string
  12907. {
  12908. return 'anime_act_preview:' . $actId;
  12909. }
  12910. /**
  12911. * 清理分镜内容:去除时长、旁白音色等非分镜行,只保留完整分镜内容(分镜标记统一为【分镜N】/【镜头N】)
  12912. *
  12913. * @param string $actContent
  12914. * @return string
  12915. */
  12916. private function cleanSegmentContent(string $actContent): string
  12917. {
  12918. $cleaned_content = '';
  12919. $content_lines = explode("\n", $actContent);
  12920. $is_capturing = false; // 标记是否开始捕获分镜内容
  12921. $count = 0;
  12922. foreach ($content_lines as $line) {
  12923. $trimmed_line = trim($line);
  12924. // 跳过时长、旁白音色等非分镜行
  12925. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  12926. continue;
  12927. }
  12928. // 检测分镜开始(支持【分镜X】【镜头X】、分镜X、镜头X,以及分镜/镜头与数字间带空格的情况)
  12929. if (preg_match('/^(?:【)?(分镜|镜头)\s*(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  12930. $count++;
  12931. $is_capturing = true;
  12932. // 统一归一化为【分镜N】/【镜头N】(兼容“镜头 1”“【镜头 1】”等写法)
  12933. $trimmed_line = preg_replace('/^(?:【)?(分镜|镜头)\s*(\d+)(?:】)?/u', '【$1$2】', $trimmed_line);
  12934. if ($count > 1) {
  12935. $trimmed_line = "\n" . $trimmed_line;
  12936. }
  12937. }
  12938. if ($is_capturing && !empty($trimmed_line)) {
  12939. $cleaned_content .= $trimmed_line . "\n";
  12940. }
  12941. }
  12942. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  12943. return $cleaned_content;
  12944. }
  12945. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  12946. {
  12947. $episode_arr = [
  12948. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  12949. 'intro' => getProp($script_arr, 'intro'),
  12950. 'art_style' => getProp($script_arr, 'art_style'),
  12951. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  12952. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  12953. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  12954. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  12955. ];
  12956. if (empty($episode_arr['acts'])) {
  12957. $fallback_episode_arr = handleEpisodeContent($fullContent);
  12958. if (!empty($fallback_episode_arr['acts'])) {
  12959. $episode_arr = array_merge($fallback_episode_arr, [
  12960. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  12961. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  12962. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  12963. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  12964. ]);
  12965. }
  12966. }
  12967. // if (!getProp($episode_arr, 'episode_title')) {
  12968. // $episode_title = '';
  12969. // $episodes = getProp($script_arr, 'episodes', []);
  12970. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  12971. // $episode_title = '第1集:' . $episodes[0]['title'];
  12972. // }
  12973. // if (!$episode_title) {
  12974. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  12975. // }
  12976. // $episode_arr['episode_title'] = $episode_title;
  12977. // }
  12978. return $episode_arr;
  12979. }
  12980. private function saveEpisodeVersionData(
  12981. int $anime_id,
  12982. int $episode_number,
  12983. array $episode_arr,
  12984. array $existing_roles,
  12985. array $existing_scenes,
  12986. array $existing_props,
  12987. $current_episode,
  12988. $base_episode,
  12989. bool $is_regenerate_version,
  12990. string $content,
  12991. string $now,
  12992. array $ref_products = []
  12993. ): array {
  12994. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  12995. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  12996. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  12997. // 过滤掉关键字段为空的条目
  12998. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  12999. return !empty($item['role'] ?? null);
  13000. }));
  13001. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  13002. return !empty($item['scene'] ?? null);
  13003. }));
  13004. $merged_props = array_values(array_filter($generated_props, function ($item) {
  13005. return !empty($item['prop'] ?? null);
  13006. }));
  13007. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  13008. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  13009. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  13010. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  13011. $ace_mode = getProp($anime, 'ace_mode');
  13012. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  13013. $global_roles = json_decode(getProp($anime, 'roles'), true);
  13014. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  13015. $global_roles = is_array($global_roles) ? $global_roles : [];
  13016. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  13017. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  13018. $art_style_type = getProp($anime, 'art_style_type');
  13019. // 检查并创建 roles 的图片生成任务
  13020. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  13021. // 检查并创建 scenes 的图片生成任务
  13022. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  13023. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  13024. if ($arr && is_array($arr)) {
  13025. $merged_roles = $arr['roles'];
  13026. $merged_scenes = $arr['scenes'];
  13027. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  13028. }
  13029. // 确保数据是数组类型
  13030. if (!is_array($merged_roles)) {
  13031. dLog('deepseek')->error('merged_roles不是数组类型', [
  13032. 'type' => gettype($merged_roles),
  13033. 'value' => $merged_roles
  13034. ]);
  13035. $merged_roles = [];
  13036. }
  13037. if (!is_array($merged_scenes)) {
  13038. dLog('deepseek')->error('merged_scenes不是数组类型', [
  13039. 'type' => gettype($merged_scenes),
  13040. 'value' => $merged_scenes
  13041. ]);
  13042. $merged_scenes = [];
  13043. }
  13044. if (!is_array($merged_props)) {
  13045. dLog('deepseek')->error('merged_props不是数组类型', [
  13046. 'type' => gettype($merged_props),
  13047. 'value' => $merged_props
  13048. ]);
  13049. $merged_props = [];
  13050. }
  13051. // 同步新出现的主体和场景到全局
  13052. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  13053. $role_arr = [];
  13054. foreach ($merged_roles as $item) {
  13055. $role_arr[$item['role']] = $item;
  13056. }
  13057. $version_count = DB::table('mp_anime_episodes')
  13058. ->where('anime_id', $anime_id)
  13059. ->where('episode_number', $episode_number)
  13060. ->count('id');
  13061. $episode = [
  13062. 'anime_id' => $anime_id,
  13063. 'episode_number' => $episode_number,
  13064. 'title' => getProp($episode_arr, 'episode_title'),
  13065. 'content' => $content,
  13066. 'intro' => getProp($episode_arr, 'intro'),
  13067. 'art_style' => getProp($episode_arr, 'art_style'),
  13068. 'roles' => json_encode($merged_roles, 256),
  13069. 'scenes' => json_encode($merged_scenes, 256),
  13070. 'props' => json_encode($merged_props, 256),
  13071. 'generate_status' => '待执行',
  13072. 'generate_at' => $now,
  13073. 'is_default' => 1,
  13074. 'updated_at' => $now,
  13075. ];
  13076. $del_flag = false;
  13077. if ($is_regenerate_version) {
  13078. DB::table('mp_anime_episodes')
  13079. ->where('anime_id', $anime_id)
  13080. ->where('episode_number', $episode_number)
  13081. ->update(['is_default' => 0, 'updated_at' => $now]);
  13082. $episode['sequence'] = $version_count + 1;
  13083. $episode['created_at'] = $now;
  13084. $episode['cpid'] = Site::getCpid();
  13085. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  13086. if (!$episode_id) {
  13087. Utils::throwError('20003:创建剧集版本失败');
  13088. }
  13089. } else {
  13090. $target_episode = $current_episode ?: $base_episode;
  13091. if ($target_episode) {
  13092. $episode_id = getProp($target_episode, 'id');
  13093. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  13094. DB::table('mp_anime_episodes')
  13095. ->where('anime_id', $anime_id)
  13096. ->where('episode_number', $episode_number)
  13097. ->where('id', '<>', $episode_id)
  13098. ->update(['is_default' => 0, 'updated_at' => $now]);
  13099. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  13100. if ($boolen === false) {
  13101. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  13102. Utils::throwError('20003:分集内容保存失败');
  13103. }
  13104. $del_flag = true;
  13105. } else {
  13106. DB::table('mp_anime_episodes')
  13107. ->where('anime_id', $anime_id)
  13108. ->where('episode_number', $episode_number)
  13109. ->update(['is_default' => 0, 'updated_at' => $now]);
  13110. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  13111. $episode['created_at'] = $now;
  13112. $episode['cpid'] = Site::getCpid();
  13113. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  13114. if (!$episode_id) {
  13115. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  13116. Utils::throwError('20003:分集内容保存失败');
  13117. }
  13118. }
  13119. }
  13120. $segments = [];
  13121. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  13122. // 如果是第2集及以后,获取上一集的主体音色数据
  13123. $previous_roles_voice = [];
  13124. if ($episode_number >= 2) {
  13125. $previous_episode = DB::table('mp_anime_episodes')
  13126. ->where('anime_id', $anime_id)
  13127. ->where('episode_number', $episode_number - 1)
  13128. ->where('is_default', 1)
  13129. ->first();
  13130. if ($previous_episode) {
  13131. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  13132. if (is_array($previous_roles)) {
  13133. foreach ($previous_roles as $prev_role) {
  13134. $role_name = getProp($prev_role, 'role');
  13135. if ($role_name) {
  13136. $previous_roles_voice[$role_name] = [
  13137. 'voice_name' => getProp($prev_role, 'voice_name'),
  13138. 'voice_type' => getProp($prev_role, 'voice_type'),
  13139. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  13140. ];
  13141. $voice_prompt = getProp($prev_role, 'voice_prompt');
  13142. if ($voice_prompt) {
  13143. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  13144. }
  13145. }
  13146. }
  13147. }
  13148. }
  13149. }
  13150. // 将继承的音色数据同步到当前集的主体列表
  13151. if (!empty($previous_roles_voice)) {
  13152. foreach ($merged_roles as &$role) {
  13153. $role_name = getProp($role, 'role');
  13154. if ($role_name && isset($previous_roles_voice[$role_name])) {
  13155. // 强制继承上一集的音色数据
  13156. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  13157. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  13158. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  13159. // 如果上一集有 voice_prompt 则继承,否则跳过
  13160. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  13161. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  13162. }
  13163. }
  13164. }
  13165. unset($role); // 解除引用
  13166. // 更新 role_arr 以便后续使用
  13167. $role_arr = [];
  13168. foreach ($merged_roles as $item) {
  13169. $role_arr[$item['role']] = $item;
  13170. }
  13171. }
  13172. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  13173. $emotion_list = array_flip($emotion_list);
  13174. foreach ($acts as $act) {
  13175. $act_segments = getProp($act, 'segments', []);
  13176. if (!is_array($act_segments)) {
  13177. continue;
  13178. }
  13179. if ((int)$ace_mode === 1) {
  13180. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  13181. $merged_parts = [];
  13182. foreach ($act_segments as $seg) {
  13183. $seg_num = getProp($seg, 'segment_number');
  13184. $seg_content = getProp($seg, 'segment_content');
  13185. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  13186. }
  13187. $act_content = implode("\n", $merged_parts);
  13188. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  13189. $segments[] = [
  13190. 'anime_id' => $anime_id,
  13191. 'episode_id' => $episode_id,
  13192. 'episode_number' => $episode_number,
  13193. 'act_number' => getProp($act, 'act_number'),
  13194. 'act_title' => getProp($act, 'act_title'),
  13195. 'act_duration' => getProp($act, 'act_duration'),
  13196. 'act_content' => $act_content,
  13197. 'created_at' => $now,
  13198. 'updated_at' => $now
  13199. ];
  13200. } else {
  13201. foreach ($act_segments as $segment) {
  13202. $voice_actor = getProp($segment, 'voice_actor');
  13203. // 优先从上一集继承音色数据
  13204. $timbre_info = [];
  13205. if (isset($previous_roles_voice[$voice_actor])) {
  13206. // 从上一集继承音色数据
  13207. $timbre_info = $previous_roles_voice[$voice_actor];
  13208. } elseif (isset($role_arr[$voice_actor])) {
  13209. // 使用当前集的主体音色数据
  13210. $timbre_info = $role_arr[$voice_actor];
  13211. }
  13212. $voice_type = getProp($timbre_info, 'voice_type');
  13213. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  13214. if ($timbre_emotion) {
  13215. $timbre_emotion = explode(',', $timbre_emotion);
  13216. } else {
  13217. $timbre_emotion = [];
  13218. }
  13219. $emotion = getProp($segment, 'emotion', '中性');
  13220. if (!in_array($emotion, $timbre_emotion)) {
  13221. $emotion = '中性';
  13222. }
  13223. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  13224. $segments[] = [
  13225. 'anime_id' => $anime_id,
  13226. 'episode_id' => $episode_id,
  13227. 'episode_number' => $episode_number,
  13228. 'act_number' => getProp($act, 'act_number'),
  13229. 'act_title' => getProp($act, 'act_title'),
  13230. 'act_duration' => getProp($act, 'act_duration'),
  13231. 'segment_id' => getProp($segment, 'segment_id'),
  13232. 'segment_number' => getProp($segment, 'segment_number'),
  13233. 'segment_content' => getProp($segment, 'segment_content'),
  13234. 'description' => getProp($segment, 'description'),
  13235. 'composition' => getProp($segment, 'composition'),
  13236. 'camera_movement' => getProp($segment, 'camera_movement'),
  13237. 'voice_actor' => $voice_actor,
  13238. 'dialogue' => getProp($segment, 'dialogue'),
  13239. 'frame_type' => getProp($segment, 'frame_type'),
  13240. 'scene' => getProp($segment, 'scene'),
  13241. 'characters' => getProp($segment, 'characters'),
  13242. 'tail_frame' => getProp($segment, 'tail_frame'),
  13243. 'voice_name' => getProp($timbre_info, 'voice_name'),
  13244. 'voice_type' => $voice_type,
  13245. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  13246. 'emotion' => $emotion,
  13247. 'emotion_type' => $emotion_type,
  13248. 'gender' => getProp($segment, 'gender', '0'),
  13249. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  13250. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  13251. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  13252. 'pitch' => getProp($segment, 'pitch', 0),
  13253. 'created_at' => $now,
  13254. 'updated_at' => $now
  13255. ];
  13256. }
  13257. }
  13258. }
  13259. if ($segments) {
  13260. if ($del_flag) {
  13261. DB::table('mp_episode_segments')
  13262. ->where('anime_id', $anime_id)
  13263. ->where('episode_id', $episode_id)
  13264. ->delete();
  13265. }
  13266. $boolen = DB::table('mp_episode_segments')->insert($segments);
  13267. if (!$boolen) {
  13268. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  13269. Utils::throwError('20003:分镜内容保存失败');
  13270. }
  13271. }
  13272. dLog('deepseek')->info('segments', $segments);
  13273. // ace_mode=1: acts 返回值按合并格式调整
  13274. if ((int)$ace_mode === 1) {
  13275. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  13276. $act_map = [];
  13277. foreach ($table_act_data as $item) {
  13278. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  13279. }
  13280. $restructured_acts = [];
  13281. foreach ($acts as $act) {
  13282. $act_segments = getProp($act, 'segments', []);
  13283. if (!is_array($act_segments)) {
  13284. continue;
  13285. }
  13286. $merged_parts = [];
  13287. foreach ($act_segments as $seg) {
  13288. $seg_num = getProp($seg, 'segment_number');
  13289. $seg_content = getProp($seg, 'segment_content');
  13290. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  13291. }
  13292. $act_content = implode("\n", $merged_parts);
  13293. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  13294. $restructured_acts[] = [
  13295. 'anime_id' => $anime_id,
  13296. 'episode_id' => $episode_id,
  13297. 'episode_number' => $episode_number,
  13298. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  13299. 'act_number' => getProp($act, 'act_number'),
  13300. 'act_title' => getProp($act, 'act_title'),
  13301. 'act_duration' => getProp($act, 'act_duration'),
  13302. 'act_content' => $act_content,
  13303. 'created_at' => $now,
  13304. 'updated_at' => $now,
  13305. ];
  13306. }
  13307. $acts = $restructured_acts;
  13308. }
  13309. $episode['episode_id'] = $episode_id;
  13310. $episode['roles'] = $merged_roles;
  13311. $episode['scenes'] = $merged_scenes;
  13312. $episode['props'] = $merged_props;
  13313. $episode['acts'] = $acts;
  13314. return [
  13315. 'episode' => $episode,
  13316. 'episode_id' => $episode_id,
  13317. 'merged_roles' => $merged_roles,
  13318. 'merged_scenes' => $merged_scenes,
  13319. 'merged_props' => $merged_props,
  13320. ];
  13321. }
  13322. private function buildEpisodeItemContent(array $items, string $nameKey): string
  13323. {
  13324. $content = '';
  13325. foreach ($items as $item) {
  13326. $name = trim((string)getProp($item, $nameKey));
  13327. if ($name === '' || $name === '旁白') {
  13328. continue;
  13329. }
  13330. $description = trim((string)getProp($item, 'description'));
  13331. $content .= $name . ': ' . $description;
  13332. if ($nameKey == 'role') {
  13333. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  13334. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13335. $voice_name = trim(getProp($item, 'voice_name'));
  13336. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  13337. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  13338. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  13339. }else {
  13340. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  13341. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13342. }
  13343. $content .= "\n";
  13344. }
  13345. return trim($content);
  13346. }
  13347. private function getEpisodeChatContent($animeId, $sequence, $content) {
  13348. if ((int)$sequence <= 0) {
  13349. return [];
  13350. }
  13351. $origin_content = '';
  13352. if ($content) {
  13353. $origin_content = '本集剧情内容:'.$content;
  13354. }else {
  13355. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  13356. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  13357. }
  13358. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  13359. // 获取分集信息
  13360. $episode = DB::table('mp_anime_episodes')
  13361. ->where('anime_id', $animeId)
  13362. ->where('episode_number', $sequence)
  13363. ->where('is_default', 1)
  13364. ->first();
  13365. if (!$episode) {
  13366. return [];
  13367. }
  13368. $episode_id = getProp($episode, 'id');
  13369. $episode_number = getProp($episode, 'episode_number');
  13370. $title = getProp($episode, 'title');
  13371. $intro = getProp($episode, 'intro');
  13372. $art_style = getProp($episode, 'art_style');
  13373. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  13374. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  13375. // 组装纯文本内容
  13376. $content = '';
  13377. // 添加分集标题和梗概
  13378. $content .= "###第{$episode_number}集:{$title}\n\n";
  13379. $content .= "###故事梗概\n";
  13380. $content .= trim($intro) . "\n\n";
  13381. // 添加美术风格
  13382. $content .= "###美术风格\n";
  13383. $content .= trim($art_style) . "\n\n";
  13384. // 添加主体列表
  13385. $content .= "###主体列表\n";
  13386. $pangbai_voice_prompt = "";
  13387. foreach ($roles as $role) {
  13388. $name = getProp($role, 'role');
  13389. $description = getProp($role, 'description');
  13390. $pic_prompt = getProp($role, 'pic_prompt');
  13391. $voice_prompt = getProp($role, 'voice_prompt');
  13392. $voice_name = getProp($role, 'voice_name');
  13393. $content .= "{$name}: {$description}";
  13394. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13395. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  13396. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  13397. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  13398. $content .= "\n";
  13399. }
  13400. $content .= "\n";
  13401. // 添加场景列表
  13402. $content .= "###场景列表\n";
  13403. foreach ($scenes as $scene) {
  13404. $name = getProp($scene, 'scene');
  13405. $description = getProp($scene, 'description');
  13406. $pic_prompt = getProp($scene, 'pic_prompt');
  13407. $content .= "{$name}: {$description}";
  13408. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13409. $content .= "\n";
  13410. }
  13411. $content .= "\n";
  13412. // 获取分镜信息
  13413. $segments = DB::table('mp_episode_segments')
  13414. ->where('anime_id', $animeId)
  13415. ->where('episode_id', $episode_id)
  13416. ->orderBy('segment_number')
  13417. ->get();
  13418. if ($segments && count($segments) > 0) {
  13419. if ((int)$ace_mode === 1) {
  13420. $content .= "###分段剧本\n";
  13421. // 获取片段数量
  13422. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  13423. $content .= "片段数量:{$act_count}\n";
  13424. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  13425. $content .= "\n";
  13426. }else {
  13427. $content .= "###分镜剧本\n";
  13428. }
  13429. // 按幕分组
  13430. $currentAct = null;
  13431. foreach ($segments as $segment) {
  13432. $act_number = getProp($segment, 'act_number');
  13433. $act_title = getProp($segment, 'act_title');
  13434. $act_duration = getProp($segment, 'act_duration');
  13435. $segment_number = getProp($segment, 'segment_number');
  13436. $segment_content = getProp($segment, 'segment_content');
  13437. $scene_description = getProp($segment, 'scene_description');
  13438. $scene_name = getProp($segment, 'scene_name');
  13439. $composition = getProp($segment, 'composition');
  13440. $camera_movement = getProp($segment, 'camera_movement');
  13441. $voice_type = getProp($segment, 'voice_type');
  13442. $characters = getProp($segment, 'characters');
  13443. $dialogue = getProp($segment, 'dialogue');
  13444. $frame_type = getProp($segment, 'frame_type');
  13445. $tail_frame_description = getProp($segment, 'tail_frame_description');
  13446. // 判断是否是全能模式
  13447. if ((int)$ace_mode === 1) { // 全能模式
  13448. // 如果是新的分段,添加分段标题
  13449. if ($act_number !== $currentAct) {
  13450. $currentAct = $act_number;
  13451. $content .= "##{$act_title}\n";
  13452. $content .= "时长:{$act_duration}s\n";
  13453. }
  13454. }else {
  13455. // 如果是新的幕,添加幕标题
  13456. if ($act_number !== $currentAct) {
  13457. $currentAct = $act_number;
  13458. $content .= "##第{$act_number}幕:{$scene_name}\n";
  13459. }
  13460. }
  13461. // 添加分镜信息
  13462. $content .= "分镜{$segment_number}\n";
  13463. $content .= "分镜内容:\n{$segment_content}\n";
  13464. // $content .= "画面描述:{$scene_description}\n";
  13465. // $content .= "场景:{$scene_name}\n";
  13466. // $content .= "构图设计:{$composition}\n";
  13467. // $content .= "运镜调度:{$camera_movement}\n";
  13468. // if (!empty($voice_type)) {
  13469. // $content .= "配音角色:{$voice_type}\n";
  13470. // }
  13471. // if (!empty($characters)) {
  13472. // $content .= "出镜角色:{$characters}\n";
  13473. // }
  13474. // if (!empty($dialogue)) {
  13475. // $content .= "台词内容:\"{$dialogue}\"\n";
  13476. // }
  13477. // $content .= "画面类型:{$frame_type}\n";
  13478. // $content .= "尾帧描述:{$tail_frame_description}\n";
  13479. $content .= "\n";
  13480. }
  13481. }
  13482. $content = trim($content);
  13483. if($content) $content = "上集剧本内容:\n{$content}";
  13484. return [
  13485. [
  13486. 'role' => 'user',
  13487. 'content' => $origin_content
  13488. ],
  13489. [
  13490. 'role' => 'assistant',
  13491. 'content' => $content
  13492. ]
  13493. ];
  13494. }
  13495. private function getEpisodeChatMessages($animeId, $sequence): array
  13496. {
  13497. if ((int)$sequence <= 0) {
  13498. return [];
  13499. }
  13500. return DB::table('mp_anime_records')
  13501. ->where('anime_id', $animeId)
  13502. ->where('sequence', $sequence)
  13503. ->where('episode_id', '>', 0)
  13504. ->select('role', 'content')
  13505. ->orderBy('created_at')
  13506. ->orderBy('id')
  13507. ->get()
  13508. ->map(function ($value) {
  13509. return (array)$value;
  13510. })
  13511. ->toArray();
  13512. }
  13513. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  13514. {
  13515. $existingMap = [];
  13516. foreach ($existingItems as $item) {
  13517. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13518. if ($itemKey === '') {
  13519. continue;
  13520. }
  13521. $existingMap[$itemKey] = $item;
  13522. }
  13523. if (!$generatedItems) {
  13524. return array_values($existingItems);
  13525. }
  13526. $merged = [];
  13527. foreach ($generatedItems as $item) {
  13528. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13529. if ($itemKey === '') {
  13530. continue;
  13531. }
  13532. if (isset($existingMap[$itemKey])) {
  13533. if (trim((string)getProp($item, 'description')) === '') {
  13534. $merged[] = $existingMap[$itemKey];
  13535. continue;
  13536. }
  13537. // 检查内容是否发生变化
  13538. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  13539. if (!$isChanged) {
  13540. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  13541. $mergedItem = [
  13542. $nameKey => trim((string)getProp($item, $nameKey)),
  13543. 'description' => trim((string)getProp($item, 'description')),
  13544. ];
  13545. // 如果有 pic_prompt,添加到合并项中
  13546. $picPrompt = getProp($item, 'pic_prompt');
  13547. if (!empty($picPrompt)) {
  13548. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  13549. }
  13550. // 继承现有项的 URL
  13551. $existingUrl = getProp($existingMap[$itemKey], 'url');
  13552. if (!empty($existingUrl)) {
  13553. $mergedItem['url'] = $existingUrl;
  13554. }
  13555. // 继承现有项的 task_id
  13556. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  13557. if (!empty($existingTaskId)) {
  13558. $mergedItem['task_id'] = $existingTaskId;
  13559. }
  13560. // 继承现有项的 task_status
  13561. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  13562. if (!empty($existingTaskStatus)) {
  13563. $mergedItem['task_status'] = $existingTaskStatus;
  13564. }
  13565. // 保留生成项的音色字段
  13566. $voiceName = getProp($item, 'voice_name');
  13567. if (!empty($voiceName)) {
  13568. $mergedItem['voice_name'] = $voiceName;
  13569. }
  13570. $voiceType = getProp($item, 'voice_type');
  13571. if (!empty($voiceType)) {
  13572. $mergedItem['voice_type'] = $voiceType;
  13573. }
  13574. $audioUrl = getProp($item, 'voice_audio_url');
  13575. if (!empty($audioUrl)) {
  13576. $mergedItem['voice_audio_url'] = $audioUrl;
  13577. }
  13578. $merged[] = $mergedItem;
  13579. } else {
  13580. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  13581. $mergedItem = [
  13582. $nameKey => trim((string)getProp($item, $nameKey)),
  13583. 'description' => trim((string)getProp($item, 'description')),
  13584. ];
  13585. // 如果有 pic_prompt,添加到合并项中
  13586. $picPrompt = getProp($item, 'pic_prompt');
  13587. if (!empty($picPrompt)) {
  13588. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  13589. }
  13590. // 保留生成项的音色字段
  13591. $voiceName = getProp($item, 'voice_name');
  13592. if (!empty($voiceName)) {
  13593. $mergedItem['voice_name'] = $voiceName;
  13594. }
  13595. $voiceType = getProp($item, 'voice_type');
  13596. if (!empty($voiceType)) {
  13597. $mergedItem['voice_type'] = $voiceType;
  13598. }
  13599. $audioUrl = getProp($item, 'voice_audio_url');
  13600. if (!empty($audioUrl)) {
  13601. $mergedItem['voice_audio_url'] = $audioUrl;
  13602. }
  13603. // 不继承 URL、task_id 和 task_status(重置状态)
  13604. $merged[] = $mergedItem;
  13605. }
  13606. } else {
  13607. // 新增项,保留生成项的所有字段
  13608. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  13609. }
  13610. }
  13611. return $merged ?: array_values($existingItems);
  13612. }
  13613. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  13614. {
  13615. $resetItem = [
  13616. $nameKey => trim((string)getProp($item, $nameKey)),
  13617. 'description' => trim((string)getProp($item, 'description')),
  13618. ];
  13619. // 保留指定的字段
  13620. foreach ($preserveFields as $field) {
  13621. $value = getProp($item, $field);
  13622. if (!empty($value)) {
  13623. $resetItem[$field] = $value;
  13624. }
  13625. }
  13626. return $resetItem;
  13627. }
  13628. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  13629. {
  13630. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  13631. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  13632. if ($existingKey !== $generatedKey) {
  13633. return true;
  13634. }
  13635. // 比较 description 是否变化
  13636. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  13637. return true;
  13638. }
  13639. // 比较 pic_prompt 是否变化
  13640. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  13641. }
  13642. private function normalizeEpisodeResourceKey($value): string
  13643. {
  13644. $value = trim((string)$value);
  13645. if ($value === '') {
  13646. return '';
  13647. }
  13648. return strtolower((string)preg_replace('/\s+/u', '', $value));
  13649. }
  13650. // 生成全局角色图片
  13651. private function batchSetGlobalRoleImg($data, $is_force=false) {
  13652. $anime_id = getProp($data, 'anime_id');
  13653. if (!$anime_id) Utils::throwError('1002:请选择对话');
  13654. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  13655. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  13656. $art_style = getProp($anime, 'art_style');
  13657. $update_flag = false;
  13658. foreach ($roles as &$role) {
  13659. $role_name = getProp($role, 'role');
  13660. if ($role_name == '旁白') continue;
  13661. // 优先使用 pic_prompt,如果没有则使用 description
  13662. $pic_prompt = getProp($role, 'pic_prompt');
  13663. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  13664. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  13665. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  13666. // 参考图地址
  13667. $ref_img_url = getProp($role, 'url');
  13668. if (!$is_force && $ref_img_url) continue;
  13669. $update_flag = true;
  13670. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  13671. try {
  13672. $params = [
  13673. 'prompt' => $description,
  13674. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  13675. 'ref_img_urls' => []
  13676. ];
  13677. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13678. $task_id = $task->id;
  13679. if (!$task_id) {
  13680. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  13681. }
  13682. $role['task_id'] = $task_id;
  13683. $role['task_status'] = 'processing';
  13684. } catch (\Exception $e) {
  13685. Utils::throwError("20003:" . $e->getMessage());
  13686. }
  13687. }
  13688. if (!$update_flag) return true;
  13689. // 保存角色信息
  13690. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  13691. 'roles' => json_encode($roles, 256),
  13692. 'generate_status' => '执行中',
  13693. 'generate_at' => date('Y-m-d H:i:s'),
  13694. 'updated_at' => date('Y-m-d H:i:s')
  13695. ]);
  13696. if (!$boolen) {
  13697. Utils::throwError('20003:保存角色信息失败');
  13698. }
  13699. return $boolen;
  13700. }
  13701. // 生成全局场景图片
  13702. private function batchSetGlobalSceneImg($data, $is_force=false) {
  13703. $anime_id = getProp($data, 'anime_id');
  13704. if (!$anime_id) Utils::throwError('1002:请选择对话');
  13705. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  13706. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  13707. $art_style = getProp($anime, 'art_style');
  13708. $update_flag = false;
  13709. foreach ($scenes as &$scene) {
  13710. $scene_name = getProp($scene, 'scene');
  13711. // 优先使用 pic_prompt,如果没有则使用 description
  13712. $pic_prompt = getProp($scene, 'pic_prompt');
  13713. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  13714. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  13715. // 参考图地址
  13716. $ref_img_url = getProp($scene, 'url');
  13717. if (!$is_force && $ref_img_url) continue;
  13718. $update_flag = true;
  13719. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  13720. try {
  13721. $params = [
  13722. 'prompt' => $description,
  13723. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  13724. 'ref_img_urls' => []
  13725. ];
  13726. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13727. $task_id = $task->id;
  13728. if (!$task_id) {
  13729. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  13730. }
  13731. $scene['task_id'] = $task_id;
  13732. $scene['task_status'] = 'processing';
  13733. } catch (\Exception $e) {
  13734. Utils::throwError("20003:" . $e->getMessage());
  13735. }
  13736. }
  13737. if (!$update_flag) return true;
  13738. // 保存角色信息
  13739. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  13740. 'scenes' => json_encode($scenes, 256),
  13741. 'generate_status' => '执行中',
  13742. 'generate_at' => date('Y-m-d H:i:s'),
  13743. 'updated_at' => date('Y-m-d H:i:s')
  13744. ]);
  13745. if (!$boolen) {
  13746. Utils::throwError('20003:保存角色信息失败');
  13747. }
  13748. return $boolen;
  13749. }
  13750. // 生成分镜主体、场景和道具图片
  13751. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  13752. $character_prefix = '';
  13753. $scene_prefix = '';
  13754. $prop_prefix = '';
  13755. if ($art_style_type) {
  13756. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  13757. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  13758. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  13759. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  13760. }
  13761. $update_flag = false;
  13762. // 获取上一集的roles、scenes和props数据
  13763. $prev_roles = [];
  13764. $prev_scenes = [];
  13765. $prev_props = [];
  13766. if ($episode_number > 1) {
  13767. $prev_episode = DB::table('mp_anime_episodes')
  13768. ->where('anime_id', $anime_id)
  13769. ->where('episode_number', $episode_number - 1)
  13770. ->where('is_default', 1)
  13771. ->first();
  13772. if ($prev_episode) {
  13773. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  13774. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  13775. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  13776. dLog('deepseek')->info("获取上一集数据成功", [
  13777. 'anime_id' => $anime_id,
  13778. 'prev_episode_number' => $episode_number - 1,
  13779. 'prev_roles_count' => count($prev_roles),
  13780. 'prev_scenes_count' => count($prev_scenes),
  13781. 'prev_props_count' => count($prev_props)
  13782. ]);
  13783. }
  13784. }
  13785. // 处理角色图片生成
  13786. foreach ($roles as &$role) {
  13787. $role_name = getProp($role, 'role');
  13788. if ($role_name == '旁白') continue;
  13789. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  13790. if (isset($ref_products[$role_name])) {
  13791. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  13792. $role['three_view_image_url'] = isset($ref_products[$role_name]['three_view_image_url']) ? $ref_products[$role_name]['three_view_image_url'] : '';
  13793. if ($role['url']) continue;
  13794. }
  13795. $role_description = getProp($role, 'description');
  13796. $role_pic_prompt = getProp($role, 'pic_prompt');
  13797. $role_url = getProp($role, 'url');
  13798. // 检查是否可以从上一集继承
  13799. $inherited = false;
  13800. if (!$is_force && !empty($prev_roles)) {
  13801. foreach ($prev_roles as $prev_role) {
  13802. $prev_role_name = getProp($prev_role, 'role');
  13803. $prev_description = getProp($prev_role, 'description');
  13804. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  13805. $prev_url = getProp($prev_role, 'url');
  13806. $prev_task_id = getProp($prev_role, 'task_id');
  13807. $prev_task_status = getProp($prev_role, 'task_status');
  13808. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  13809. if ($role_name == $prev_role_name
  13810. && $role_description == $prev_description
  13811. && $role_pic_prompt == $prev_pic_prompt
  13812. && !empty($prev_url)) {
  13813. $role['task_id'] = $prev_task_id;
  13814. $role['task_status'] = $prev_task_status;
  13815. $role['url'] = $prev_url;
  13816. $inherited = true;
  13817. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  13818. 'anime_id' => $anime_id,
  13819. 'episode_number' => $episode_number,
  13820. 'task_id' => $prev_task_id,
  13821. 'url' => $prev_url
  13822. ]);
  13823. break;
  13824. }
  13825. }
  13826. }
  13827. // 如果已继承或已有url,跳过生成
  13828. if ($inherited || (!$is_force && $role_url)) {
  13829. continue;
  13830. }
  13831. // 优先使用 pic_prompt,如果没有则使用 description
  13832. $pic_prompt = getProp($role, 'pic_prompt');
  13833. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  13834. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  13835. $update_flag = true;
  13836. // 调用AIImageGenerationService的生成图片任务接口
  13837. try {
  13838. $params = [
  13839. 'prompt' => $description,
  13840. 'ref_img_urls' => []
  13841. ];
  13842. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13843. $task_id = $task->id;
  13844. if (!$task_id) {
  13845. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  13846. continue; // 不中断,继续处理其他角色
  13847. }
  13848. $role['task_id'] = $task_id;
  13849. $role['task_status'] = 'processing';
  13850. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  13851. 'anime_id' => $anime_id,
  13852. 'episode_number' => $episode_number,
  13853. 'task_id' => $task_id
  13854. ]);
  13855. } catch (\Exception $e) {
  13856. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  13857. // 不抛出异常,继续处理其他角色
  13858. }
  13859. }
  13860. // 处理场景图片生成
  13861. foreach ($scenes as &$scene) {
  13862. $scene_name = getProp($scene, 'scene');
  13863. $scene_description = getProp($scene, 'description');
  13864. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  13865. $scene_url = getProp($scene, 'url');
  13866. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  13867. if (isset($ref_products[$scene_name])) {
  13868. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  13869. $scene['three_view_image_url'] = isset($ref_products[$scene_name]['three_view_image_url']) ? $ref_products[$scene_name]['three_view_image_url'] : '';
  13870. if ($scene['url']) continue;
  13871. }
  13872. // 检查是否可以从上一集继承
  13873. $inherited = false;
  13874. if (!$is_force && !empty($prev_scenes)) {
  13875. foreach ($prev_scenes as $prev_scene) {
  13876. $prev_scene_name = getProp($prev_scene, 'scene');
  13877. $prev_description = getProp($prev_scene, 'description');
  13878. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  13879. $prev_url = getProp($prev_scene, 'url');
  13880. $prev_task_id = getProp($prev_scene, 'task_id');
  13881. $prev_task_status = getProp($prev_scene, 'task_status');
  13882. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  13883. if ($scene_name == $prev_scene_name
  13884. && $scene_description == $prev_description
  13885. && $scene_pic_prompt == $prev_pic_prompt
  13886. && !empty($prev_url)) {
  13887. $scene['task_id'] = $prev_task_id;
  13888. $scene['task_status'] = $prev_task_status;
  13889. $scene['url'] = $prev_url;
  13890. $inherited = true;
  13891. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  13892. 'anime_id' => $anime_id,
  13893. 'episode_number' => $episode_number,
  13894. 'task_id' => $prev_task_id,
  13895. 'url' => $prev_url
  13896. ]);
  13897. break;
  13898. }
  13899. }
  13900. }
  13901. // 如果已继承或已有url,跳过生成
  13902. if ($inherited || (!$is_force && $scene_url)) {
  13903. continue;
  13904. }
  13905. // 优先使用 pic_prompt,如果没有则使用 description
  13906. $pic_prompt = getProp($scene, 'pic_prompt');
  13907. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  13908. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  13909. $update_flag = true;
  13910. // 调用AIImageGenerationService的生成图片任务接口
  13911. try {
  13912. $params = [
  13913. 'prompt' => $description,
  13914. 'ref_img_urls' => []
  13915. ];
  13916. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13917. $task_id = $task->id;
  13918. if (!$task_id) {
  13919. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  13920. continue; // 不中断,继续处理其他场景
  13921. }
  13922. $scene['task_id'] = $task_id;
  13923. $scene['task_status'] = 'processing';
  13924. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  13925. 'anime_id' => $anime_id,
  13926. 'episode_number' => $episode_number,
  13927. 'task_id' => $task_id
  13928. ]);
  13929. } catch (\Exception $e) {
  13930. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  13931. // 不抛出异常,继续处理其他场景
  13932. }
  13933. }
  13934. // 处理道具图片生成(逻辑与场景一致)
  13935. foreach ($props as &$prop) {
  13936. $prop_name = getProp($prop, 'prop');
  13937. $prop_description = getProp($prop, 'description');
  13938. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  13939. $prop_url = getProp($prop, 'url');
  13940. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  13941. if (isset($ref_products[$prop_name])) {
  13942. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  13943. $prop['three_view_image_url'] = isset($ref_products[$prop_name]['three_view_image_url']) ? $ref_products[$prop_name]['three_view_image_url'] : '';
  13944. if ($prop['url']) continue;
  13945. }
  13946. // 检查是否可以从上一集继承
  13947. $inherited = false;
  13948. if (!$is_force && !empty($prev_props)) {
  13949. foreach ($prev_props as $prev_prop) {
  13950. $prev_prop_name = getProp($prev_prop, 'prop');
  13951. $prev_description = getProp($prev_prop, 'description');
  13952. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  13953. $prev_url = getProp($prev_prop, 'url');
  13954. $prev_task_id = getProp($prev_prop, 'task_id');
  13955. $prev_task_status = getProp($prev_prop, 'task_status');
  13956. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  13957. if ($prop_name == $prev_prop_name
  13958. && $prop_description == $prev_description
  13959. && $prop_pic_prompt == $prev_pic_prompt
  13960. && !empty($prev_url)) {
  13961. $prop['task_id'] = $prev_task_id;
  13962. $prop['task_status'] = $prev_task_status;
  13963. $prop['url'] = $prev_url;
  13964. $inherited = true;
  13965. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  13966. 'anime_id' => $anime_id,
  13967. 'episode_number' => $episode_number,
  13968. 'task_id' => $prev_task_id,
  13969. 'url' => $prev_url
  13970. ]);
  13971. break;
  13972. }
  13973. }
  13974. }
  13975. // 如果已继承或已有url,跳过生成
  13976. if ($inherited || (!$is_force && $prop_url)) {
  13977. continue;
  13978. }
  13979. // 优先使用 pic_prompt,如果没有则使用 description
  13980. $pic_prompt = getProp($prop, 'pic_prompt');
  13981. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  13982. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  13983. $update_flag = true;
  13984. // 调用AIImageGenerationService的生成图片任务接口
  13985. try {
  13986. $params = [
  13987. 'prompt' => $description,
  13988. 'ref_img_urls' => []
  13989. ];
  13990. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13991. $task_id = $task->id;
  13992. if (!$task_id) {
  13993. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  13994. continue; // 不中断,继续处理其他道具
  13995. }
  13996. $prop['task_id'] = $task_id;
  13997. $prop['task_status'] = 'processing';
  13998. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  13999. 'anime_id' => $anime_id,
  14000. 'episode_number' => $episode_number,
  14001. 'task_id' => $task_id
  14002. ]);
  14003. } catch (\Exception $e) {
  14004. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  14005. // 不抛出异常,继续处理其他道具
  14006. }
  14007. }
  14008. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  14009. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  14010. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  14011. // // 保存剧集的角色和场景信息
  14012. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  14013. // 'roles' => json_encode($roles, 256),
  14014. // 'scenes' => json_encode($scenes, 256),
  14015. // 'generate_status' => '执行中',
  14016. // 'generate_at' => date('Y-m-d H:i:s'),
  14017. // 'updated_at' => date('Y-m-d H:i:s')
  14018. // ]);
  14019. // if (!$boolen) {
  14020. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  14021. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  14022. // }
  14023. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  14024. // 'episode_id' => $episode_id,
  14025. 'roles_count' => count($roles),
  14026. 'scenes_count' => count($scenes),
  14027. 'props_count' => count($props)
  14028. ]);
  14029. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  14030. }
  14031. /**
  14032. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  14033. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  14034. *
  14035. * @param int $anime_id 动漫对话ID
  14036. * @param array $episode_roles 剧集角色数据
  14037. * @param array $episode_scenes 剧集场景数据
  14038. * @param array $episode_props 剧集道具数据
  14039. * @return bool
  14040. */
  14041. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  14042. // 获取全局数据
  14043. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  14044. if (!$anime) {
  14045. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  14046. return false;
  14047. }
  14048. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  14049. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  14050. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  14051. $roles_added = false;
  14052. $roles_updated = false;
  14053. $scenes_added = false;
  14054. $props_added = false;
  14055. // 处理角色同步
  14056. foreach ($episode_roles as $episode_role) {
  14057. $episode_role_name = getProp($episode_role, 'role');
  14058. $episode_description = getProp($episode_role, 'description');
  14059. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  14060. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  14061. // 跳过旁白
  14062. if ($episode_role_name == '旁白') {
  14063. continue;
  14064. }
  14065. // 检查全局中是否已存在相同的角色
  14066. $exists = false;
  14067. $global_role_index = -1;
  14068. foreach ($global_roles as $index => $global_role) {
  14069. $global_role_name = getProp($global_role, 'role');
  14070. $global_description = getProp($global_role, 'description');
  14071. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  14072. // 如果role、description、pic_prompt三项都一致,则认为已存在
  14073. if ($episode_role_name == $global_role_name
  14074. && $episode_description == $global_description
  14075. && $episode_pic_prompt == $global_pic_prompt) {
  14076. $exists = true;
  14077. $global_role_index = $index;
  14078. break;
  14079. }
  14080. }
  14081. // 如果不存在,则添加到全局
  14082. if (!$exists) {
  14083. $global_roles[] = $episode_role;
  14084. $roles_added = true;
  14085. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  14086. 'anime_id' => $anime_id,
  14087. 'role' => $episode_role_name
  14088. ]);
  14089. } else {
  14090. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  14091. if (!empty($episode_voice_prompt)) {
  14092. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  14093. // 如果全局没有voice_prompt或与剧集不一致,则更新
  14094. if ($global_voice_prompt !== $episode_voice_prompt) {
  14095. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  14096. $roles_updated = true;
  14097. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  14098. 'anime_id' => $anime_id,
  14099. 'role' => $episode_role_name,
  14100. 'voice_prompt' => $episode_voice_prompt
  14101. ]);
  14102. }
  14103. }
  14104. }
  14105. }
  14106. // 处理场景同步
  14107. foreach ($episode_scenes as $episode_scene) {
  14108. $episode_scene_name = getProp($episode_scene, 'scene');
  14109. $episode_description = getProp($episode_scene, 'description');
  14110. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  14111. // 检查全局中是否已存在相同的场景
  14112. $exists = false;
  14113. foreach ($global_scenes as $global_scene) {
  14114. $global_scene_name = getProp($global_scene, 'scene');
  14115. $global_description = getProp($global_scene, 'description');
  14116. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  14117. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  14118. if ($episode_scene_name == $global_scene_name
  14119. && $episode_description == $global_description
  14120. && $episode_pic_prompt == $global_pic_prompt) {
  14121. $exists = true;
  14122. break;
  14123. }
  14124. }
  14125. // 如果不存在,则添加到全局
  14126. if (!$exists) {
  14127. $global_scenes[] = $episode_scene;
  14128. $scenes_added = true;
  14129. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  14130. 'anime_id' => $anime_id,
  14131. 'scene' => $episode_scene_name
  14132. ]);
  14133. }
  14134. }
  14135. // 处理道具同步(逻辑与场景一致)
  14136. foreach ($episode_props as $episode_prop) {
  14137. $episode_prop_name = getProp($episode_prop, 'prop');
  14138. $episode_description = getProp($episode_prop, 'description');
  14139. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  14140. // 检查全局中是否已存在相同的道具
  14141. $exists = false;
  14142. foreach ($global_props as $global_prop) {
  14143. $global_prop_name = getProp($global_prop, 'prop');
  14144. $global_description = getProp($global_prop, 'description');
  14145. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  14146. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  14147. if ($episode_prop_name == $global_prop_name
  14148. && $episode_description == $global_description
  14149. && $episode_pic_prompt == $global_pic_prompt) {
  14150. $exists = true;
  14151. break;
  14152. }
  14153. }
  14154. // 如果不存在,则添加到全局
  14155. if (!$exists) {
  14156. $global_props[] = $episode_prop;
  14157. $props_added = true;
  14158. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  14159. 'anime_id' => $anime_id,
  14160. 'prop' => $episode_prop_name
  14161. ]);
  14162. }
  14163. }
  14164. // 如果有新增或更新,则更新全局数据
  14165. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  14166. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  14167. if ($roles_added || $roles_updated) {
  14168. $update_data['roles'] = json_encode($global_roles, 256);
  14169. }
  14170. if ($scenes_added) {
  14171. $update_data['scenes'] = json_encode($global_scenes, 256);
  14172. }
  14173. if ($props_added) {
  14174. $update_data['props'] = json_encode($global_props, 256);
  14175. }
  14176. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  14177. dLog('deepseek')->info('剧集数据同步到全局完成', [
  14178. 'anime_id' => $anime_id,
  14179. 'roles_added' => $roles_added,
  14180. 'roles_updated' => $roles_updated,
  14181. 'scenes_added' => $scenes_added,
  14182. 'props_added' => $props_added,
  14183. 'global_roles_count' => count($global_roles),
  14184. 'global_scenes_count' => count($global_scenes),
  14185. 'global_props_count' => count($global_props)
  14186. ]);
  14187. }
  14188. return true;
  14189. }
  14190. /**
  14191. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  14192. *
  14193. * @param int $anime_id 动漫对话ID
  14194. * @param int $episode_id 分集ID
  14195. * @return bool
  14196. */
  14197. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  14198. // 获取全局角色和场景数据
  14199. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  14200. if (!$anime) {
  14201. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  14202. return false;
  14203. }
  14204. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  14205. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  14206. // 获取指定的分集
  14207. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  14208. if (!$episode) {
  14209. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  14210. return false;
  14211. }
  14212. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  14213. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  14214. $roles_updated = false;
  14215. $scenes_updated = false;
  14216. // 继承角色的task_id、task_status和url
  14217. foreach ($episode_roles as &$episode_role) {
  14218. $episode_role_name = getProp($episode_role, 'role');
  14219. $episode_description = getProp($episode_role, 'description');
  14220. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  14221. $episode_url = getProp($episode_role, 'url');
  14222. // 跳过旁白角色
  14223. if ($episode_role_name == '旁白') {
  14224. continue;
  14225. }
  14226. // 如果剧集中已有URL,跳过
  14227. if (!empty($episode_url)) {
  14228. continue;
  14229. }
  14230. // 遍历全局角色数据,查找匹配的角色
  14231. foreach ($global_roles as $global_role) {
  14232. $global_role_name = getProp($global_role, 'role');
  14233. $global_description = getProp($global_role, 'description');
  14234. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  14235. $global_url = getProp($global_role, 'url');
  14236. $global_task_id = getProp($global_role, 'task_id');
  14237. $global_task_status = getProp($global_role, 'task_status');
  14238. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  14239. if ($episode_role_name == $global_role_name
  14240. && $episode_description == $global_description
  14241. && $episode_pic_prompt == $global_pic_prompt) {
  14242. // 继承 task_id、task_status 和 url
  14243. if (!empty($global_task_id)) {
  14244. $episode_role['task_id'] = $global_task_id;
  14245. $episode_role['task_status'] = $global_task_status;
  14246. $roles_updated = true;
  14247. dLog('deepseek')->info('剧集角色继承全局task_id', [
  14248. 'episode_id' => $episode_id,
  14249. 'role' => $episode_role_name,
  14250. 'task_id' => $global_task_id,
  14251. 'task_status' => $global_task_status
  14252. ]);
  14253. }
  14254. if (!empty($global_url)) {
  14255. $episode_role['url'] = $global_url;
  14256. $roles_updated = true;
  14257. dLog('deepseek')->info('剧集角色继承全局url', [
  14258. 'episode_id' => $episode_id,
  14259. 'role' => $episode_role_name,
  14260. 'url' => $global_url
  14261. ]);
  14262. }
  14263. break;
  14264. }
  14265. }
  14266. }
  14267. // 继承场景的task_id、task_status和url
  14268. foreach ($episode_scenes as &$episode_scene) {
  14269. $episode_scene_name = getProp($episode_scene, 'scene');
  14270. $episode_description = getProp($episode_scene, 'description');
  14271. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  14272. $episode_url = getProp($episode_scene, 'url');
  14273. // 如果剧集中已有URL,跳过
  14274. if (!empty($episode_url)) {
  14275. continue;
  14276. }
  14277. // 遍历全局场景数据,查找匹配的场景
  14278. foreach ($global_scenes as $global_scene) {
  14279. $global_scene_name = getProp($global_scene, 'scene');
  14280. $global_description = getProp($global_scene, 'description');
  14281. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  14282. $global_url = getProp($global_scene, 'url');
  14283. $global_task_id = getProp($global_scene, 'task_id');
  14284. $global_task_status = getProp($global_scene, 'task_status');
  14285. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  14286. if ($episode_scene_name == $global_scene_name
  14287. && $episode_description == $global_description
  14288. && $episode_pic_prompt == $global_pic_prompt) {
  14289. // 继承 task_id、task_status 和 url
  14290. if (!empty($global_task_id)) {
  14291. $episode_scene['task_id'] = $global_task_id;
  14292. $episode_scene['task_status'] = $global_task_status;
  14293. $scenes_updated = true;
  14294. dLog('deepseek')->info('剧集场景继承全局task_id', [
  14295. 'episode_id' => $episode_id,
  14296. 'scene' => $episode_scene_name,
  14297. 'task_id' => $global_task_id,
  14298. 'task_status' => $global_task_status
  14299. ]);
  14300. }
  14301. if (!empty($global_url)) {
  14302. $episode_scene['url'] = $global_url;
  14303. $scenes_updated = true;
  14304. dLog('deepseek')->info('剧集场景继承全局url', [
  14305. 'episode_id' => $episode_id,
  14306. 'scene' => $episode_scene_name,
  14307. 'url' => $global_url
  14308. ]);
  14309. }
  14310. break;
  14311. }
  14312. }
  14313. }
  14314. // 如果有更新,则保存到数据库
  14315. if ($roles_updated || $scenes_updated) {
  14316. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  14317. if ($roles_updated) {
  14318. $update_data['roles'] = json_encode($episode_roles, 256);
  14319. }
  14320. if ($scenes_updated) {
  14321. $update_data['scenes'] = json_encode($episode_scenes, 256);
  14322. }
  14323. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  14324. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  14325. 'episode_id' => $episode_id,
  14326. 'roles_updated' => $roles_updated,
  14327. 'scenes_updated' => $scenes_updated
  14328. ]);
  14329. }
  14330. return true;
  14331. }
  14332. public function chatChangeImg($data) {
  14333. // 文生文计费预检(normal 档)
  14334. $uid = Site::getUid();
  14335. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'normal'), $uid);
  14336. $segment = getProp($data, 'segment');
  14337. $segment_content = getProp($segment, 'segment_content');
  14338. $prompt = getProp($data, 'prompt');
  14339. $ref_img = getProp($data, 'ref_img');
  14340. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  14341. // 处理文本模型
  14342. $model = getProp($data, 'model');
  14343. if (!$model) {
  14344. // 用户没有输入,从anime表获取
  14345. $segment_id = getProp($segment, 'segment_id');
  14346. if ($segment_id) {
  14347. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  14348. if ($episode_id) {
  14349. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  14350. if ($anime_id) {
  14351. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  14352. }
  14353. }
  14354. }
  14355. if (!$model) {
  14356. // anime表也没有,使用默认值
  14357. $model = 'doubao-seed-2-0-mini-260215';
  14358. }
  14359. }
  14360. // 验证模型是否在可用模型表中
  14361. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  14362. $model = 'doubao-seed-2-0-mini-260215';
  14363. }
  14364. $messages[] =
  14365. [
  14366. 'role' => 'user',
  14367. 'content' => $question
  14368. ];
  14369. $post_data = [
  14370. 'model' => $model,
  14371. 'messages' => $messages,
  14372. // 'max_tokens' => 8192,
  14373. 'temperature' => 0.7,
  14374. 'frequency_penalty' => 0,
  14375. 'presence_penalty' => 0,
  14376. 'response_format' => ['type' => 'text'],
  14377. 'stream' => false // 是否启用流式输出
  14378. ];
  14379. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  14380. if (is_array($chatResult)) {
  14381. extract($chatResult);
  14382. }else {
  14383. Utils::throwError('20003: 接口调用失败!');
  14384. }
  14385. // 文生文成功计费(normal 档):同时记录积分与 token 明细
  14386. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  14387. 'model' => $model,
  14388. 'source' => 'chatChangeImg',
  14389. ], 'normal');
  14390. return [
  14391. 'type' => 'done',
  14392. // 'episode' => $episode,
  14393. 'answer' => $fullContent,
  14394. 'reasoning' => $fullReasoningContent,
  14395. 'usage' => $usage
  14396. ];
  14397. }
  14398. /**
  14399. * 仅调用 deepseek 对话接口(非流式)
  14400. *
  14401. * @param array $post_data
  14402. * @param int $timeout
  14403. * @return array
  14404. */
  14405. private function chatOnly($post_data, $timeout = 1800) {
  14406. $post_data['max_tokens'] = 300000;
  14407. $client = new Client(['timeout' => $timeout, 'verify' => false]);
  14408. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  14409. $response = $result->getBody()->getContents();
  14410. $response_arr = json_decode($response, true);
  14411. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  14412. $fullContent = '';
  14413. $fullReasoningContent = [];
  14414. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  14415. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  14416. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  14417. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  14418. }
  14419. return [
  14420. 'fullContent' => $fullContent,
  14421. 'fullReasoningContent' => $fullReasoningContent,
  14422. 'usage' => $usage
  14423. ];
  14424. }
  14425. /**
  14426. * 用 deepseek-v4-flash 非流式分析报错,返回不超过50字的用户友好提示
  14427. *
  14428. * @param string $errorMessage
  14429. * @return string|null
  14430. */
  14431. public function analyzeErrorMessage($errorMessage)
  14432. {
  14433. try {
  14434. $post_data = [
  14435. 'model' => 'deepseek-v4-flash',
  14436. 'messages' => [
  14437. [
  14438. 'role' => 'system',
  14439. 'content' => '你是视频生成任务的报错分析助手。请根据用户给出的原始报错,用一句中文提示告诉用户问题原因和下一步怎么做,不超过50个字,直接输出提示内容,不要解释、不要输出代码。',
  14440. ],
  14441. [
  14442. 'role' => 'user',
  14443. 'content' => (string)$errorMessage,
  14444. ],
  14445. ],
  14446. 'temperature' => 0.3,
  14447. 'frequency_penalty' => 0,
  14448. 'presence_penalty' => 0,
  14449. 'response_format' => ['type' => 'text'],
  14450. 'stream' => false,
  14451. ];
  14452. $result = $this->chatOnly($post_data, 8);
  14453. // 调用成功即记录 token 使用明细(不扣积分),保证错误分析这类隐性 AI 调用进入统计口径
  14454. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  14455. 'model' => 'deepseek-v4-flash',
  14456. 'source' => 'analyzeErrorMessage',
  14457. ], 'deepseek-v4-flash');
  14458. $content = trim((string)($result['fullContent'] ?? ''));
  14459. if ($content === '') {
  14460. return null;
  14461. }
  14462. return mb_substr($content, 0, 50);
  14463. } catch (\Exception $e) {
  14464. dLog('deepseek')->error('视频任务报错分析失败: ' . $e->getMessage(), [
  14465. 'error_message' => $errorMessage
  14466. ]);
  14467. return null;
  14468. }
  14469. }
  14470. // 仅调用 GPT-5.4 对话接口(非流式)
  14471. private function gpt54ChatOnly($post_data) {
  14472. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  14473. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  14474. // gpt-5.4 中转已下线,强制映射到 gpt-5.6-sol
  14475. if ($modelName === 'gpt-5.4') {
  14476. $modelName = 'gpt-5.6-terra';
  14477. $post_data['model'] = $modelName;
  14478. }
  14479. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  14480. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  14481. $usedLunaFallback = false;
  14482. if (empty($apiKey)) {
  14483. Utils::throwError('20003:GPT-5.4 API Key未配置');
  14484. }
  14485. // 先探活,服务不可用时自动重试
  14486. $this->ensureGptServiceAvailable($apiKey);
  14487. $client = new Client(['timeout' => 1800, 'verify' => false]);
  14488. // 移除 thinking 参数,GPT-5.4 不支持
  14489. if (isset($post_data['thinking'])) {
  14490. unset($post_data['thinking']);
  14491. }
  14492. if (isset($post_data['reasoning_effort'])) {
  14493. unset($post_data['reasoning_effort']);
  14494. }
  14495. $post_data['max_completion_tokens'] = 100000;
  14496. // GPT-5.x 上游不支持 max_tokens,与 gpt54StreamResponse 保持一致,显式移除避免 400。
  14497. unset($post_data['max_tokens']);
  14498. // GPT-5.x 上游不接受 frequency_penalty / presence_penalty,移除默认值 0 不影响行为。
  14499. unset($post_data['frequency_penalty'], $post_data['presence_penalty']);
  14500. // 确保 stream 为 false
  14501. $post_data['stream'] = false;
  14502. $maxRetries = $this->gptRetryTimes();
  14503. $interval = $this->gptRetryInterval();
  14504. $attempt = 0;
  14505. while (true) {
  14506. try {
  14507. $headers = [
  14508. 'Authorization' => 'Bearer ' . $apiKey,
  14509. 'Content-Type' => 'application/json'
  14510. ];
  14511. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  14512. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  14513. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  14514. 'json' => $post_data,
  14515. 'headers' => $headers
  14516. ]);
  14517. $response = $result->getBody()->getContents();
  14518. $response_arr = json_decode($response, true);
  14519. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  14520. $fullContent = '';
  14521. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  14522. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  14523. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  14524. }
  14525. return [
  14526. 'fullContent' => $fullContent,
  14527. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  14528. 'usage' => $usage
  14529. ];
  14530. } catch (\Exception $e) {
  14531. // 报错或超时时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  14532. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  14533. $usedLunaFallback = true;
  14534. $apiKey = $lunaApiKey;
  14535. dLog('deepseek')->warning('GPT-5.4 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  14536. continue;
  14537. }
  14538. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  14539. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  14540. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  14541. throw $e;
  14542. }
  14543. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  14544. 'retry' => $attempt + 1,
  14545. 'max_retries' => $maxRetries,
  14546. 'error' => $e->getMessage()
  14547. ]);
  14548. sleep($interval);
  14549. $attempt++;
  14550. }
  14551. }
  14552. }
  14553. public function getContentByBid($bid) {
  14554. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  14555. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  14556. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  14557. $content = '';
  14558. foreach ($chapters as $chapter) {
  14559. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  14560. }
  14561. return $content;
  14562. }
  14563. public function getContentByScriptId($script_id) {
  14564. $content = '';
  14565. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  14566. if ($contents) {
  14567. $content = implode(PHP_EOL, $contents);
  14568. }else {
  14569. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  14570. }
  14571. return $content;
  14572. }
  14573. /**
  14574. * 根据文件类型提取文本内容
  14575. *
  14576. * @param mixed $file 文件对象或文件路径
  14577. * @return string
  14578. */
  14579. public function extractFileContent($file) {
  14580. // 获取文件路径和扩展名
  14581. if (is_string($file)) {
  14582. $filePath = $file;
  14583. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  14584. } else {
  14585. // Laravel UploadedFile 对象
  14586. $filePath = $file->getRealPath();
  14587. $extension = strtolower($file->getClientOriginalExtension());
  14588. }
  14589. $content = '';
  14590. switch ($extension) {
  14591. case 'txt':
  14592. $content = $this->extractTxtContent($filePath);
  14593. break;
  14594. case 'pdf':
  14595. $content = $this->extractPdfContent($filePath);
  14596. break;
  14597. case 'doc':
  14598. case 'docx':
  14599. $content = $this->extractWordContent($filePath);
  14600. break;
  14601. // case 'jpg':
  14602. // case 'jpeg':
  14603. // case 'png':
  14604. // case 'gif':
  14605. // case 'bmp':
  14606. // case 'webp':
  14607. // $content = $this->extractImageContent($filePath);
  14608. // break;
  14609. default:
  14610. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  14611. }
  14612. // 移除非法 UTF-8 字节,避免后续 JSON 编码或正则解析异常
  14613. if (!mb_check_encoding($content, 'UTF-8')) {
  14614. $cleaned = @iconv('UTF-8', 'UTF-8//IGNORE', $content);
  14615. $content = $cleaned === false ? $content : $cleaned;
  14616. }
  14617. return $content;
  14618. }
  14619. /**
  14620. * 提取 TXT 文件内容
  14621. */
  14622. private function extractTxtContent($filePath) {
  14623. if (!file_exists($filePath)) {
  14624. Utils::throwError('20003:文件不存在');
  14625. }
  14626. $content = file_get_contents($filePath);
  14627. // 尝试检测并转换编码
  14628. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  14629. if ($encoding && $encoding !== 'UTF-8') {
  14630. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  14631. }
  14632. return trim($content);
  14633. }
  14634. /**
  14635. * 提取 PDF 文件内容
  14636. */
  14637. private function extractPdfContent($filePath) {
  14638. if (!file_exists($filePath)) {
  14639. Utils::throwError('20003:文件不存在');
  14640. }
  14641. try {
  14642. $parser = new PdfParser();
  14643. $pdf = $parser->parseFile($filePath);
  14644. $content = $pdf->getText();
  14645. return trim($content);
  14646. } catch (\Exception $e) {
  14647. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  14648. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  14649. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  14650. }
  14651. }
  14652. /**
  14653. * 提取 Word 文件内容(支持 doc 和 docx)
  14654. */
  14655. private function extractWordContent($filePath) {
  14656. if (!file_exists($filePath)) {
  14657. Utils::throwError('20003:文件不存在');
  14658. }
  14659. try {
  14660. $phpWord = WordIOFactory::load($filePath);
  14661. $content = '';
  14662. foreach ($phpWord->getSections() as $section) {
  14663. foreach ($section->getElements() as $element) {
  14664. $content .= $this->extractWordElementText($element);
  14665. // 段落边界补换行(段落内的软换行已在元素递归中处理)
  14666. $content .= "\n";
  14667. }
  14668. }
  14669. return trim($content);
  14670. } catch (\Exception $e) {
  14671. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  14672. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  14673. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  14674. }
  14675. }
  14676. /**
  14677. * 递归提取 Word 元素中的文本
  14678. */
  14679. private function extractWordElementText($element) {
  14680. $text = '';
  14681. if ($element instanceof \PhpOffice\PhpWord\Element\TextBreak
  14682. || $element instanceof \PhpOffice\PhpWord\Element\LineBreak) {
  14683. // 软换行:保留 Word 中的换行显示,避免"第X集"标题与正文粘连
  14684. $text .= "\n";
  14685. } elseif (method_exists($element, 'getElements')) {
  14686. foreach ($element->getElements() as $childElement) {
  14687. $text .= $this->extractWordElementText($childElement);
  14688. }
  14689. } elseif (method_exists($element, 'getText')) {
  14690. $text .= $element->getText();
  14691. }
  14692. return $text;
  14693. }
  14694. /**
  14695. * 提取图片内容(使用火山引擎 OCR)
  14696. */
  14697. private function extractImageContent($filePath) {
  14698. if (!file_exists($filePath)) {
  14699. Utils::throwError('20003:文件不存在');
  14700. }
  14701. try {
  14702. // 读取图片并转换为 base64
  14703. $imageData = file_get_contents($filePath);
  14704. $base64Image = base64_encode($imageData);
  14705. // 调用火山引擎 OCR 服务
  14706. $content = $this->callVolcEngineOCR($base64Image);
  14707. return trim($content);
  14708. } catch (\Exception $e) {
  14709. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  14710. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  14711. Utils::throwError('20003:图片识别失败');
  14712. }
  14713. }
  14714. /**
  14715. * 调用火山引擎 OCR 服务识别图片文字
  14716. *
  14717. * @param string $base64Image base64 编码的图片数据
  14718. * @return string 识别的文字内容
  14719. */
  14720. private function callVolcEngineOCR($base64Image) {
  14721. $method = 'POST';
  14722. $service = 'cv';
  14723. $host = 'visual.volcengineapi.com';
  14724. $region = env('VOLC_REGION', 'cn-north-1');
  14725. $access_key = env('VOLC_AK');
  14726. $secret_key = env('VOLC_SK');
  14727. $action = 'OCRNormal';
  14728. $version = '2020-08-26';
  14729. if (!$access_key || !$secret_key) {
  14730. Utils::throwError('20003:请配置火山引擎 AK/SK');
  14731. }
  14732. // 请求体
  14733. $body = json_encode([
  14734. 'image_base64' => $base64Image
  14735. ]);
  14736. // 生成签名
  14737. $headers = $this->getVolcEngineSignHeaders(
  14738. $method, $service, $host, $region,
  14739. "Action={$action}&Version={$version}",
  14740. $access_key, $secret_key, $body
  14741. );
  14742. $client = new Client(['timeout' => 1800, 'verify' => false]);
  14743. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  14744. 'headers' => $headers,
  14745. 'body' => $body
  14746. ]);
  14747. $response_arr = json_decode($response->getBody()->getContents(), true);
  14748. // 提取识别的文字
  14749. $textLines = [];
  14750. if (isset($response_arr['data']['line_texts'])) {
  14751. $textLines = $response_arr['data']['line_texts'];
  14752. } elseif (isset($response_arr['data']['ocr_infos'])) {
  14753. foreach ($response_arr['data']['ocr_infos'] as $info) {
  14754. if (isset($info['text'])) {
  14755. $textLines[] = $info['text'];
  14756. }
  14757. }
  14758. }
  14759. if (empty($textLines)) {
  14760. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  14761. return '';
  14762. }
  14763. return implode("\n", $textLines);
  14764. }
  14765. /**
  14766. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  14767. */
  14768. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  14769. $contentType = 'application/json';
  14770. $accept = 'application/json';
  14771. // 获取当前UTC时间
  14772. $t = new DateTime('now', new DateTimeZone('UTC'));
  14773. $xDate = $t->format('Ymd\THis\Z');
  14774. $dateStamp = $t->format('Ymd');
  14775. // 计算 body 的 sha256 哈希
  14776. $payloadHash = hash('sha256', $body);
  14777. // 1. 拼接规范请求串
  14778. $canonicalUri = '/';
  14779. $canonicalQueryString = $queryString;
  14780. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  14781. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  14782. $canonicalRequest = implode("\n", [
  14783. $method,
  14784. $canonicalUri,
  14785. $canonicalQueryString,
  14786. $canonicalHeaders,
  14787. $signedHeaders,
  14788. $payloadHash
  14789. ]);
  14790. // 2. 拼接待签名字符串
  14791. $algorithm = 'HMAC-SHA256';
  14792. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  14793. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  14794. $stringToSign = implode("\n", [
  14795. $algorithm,
  14796. $xDate,
  14797. $credentialScope,
  14798. $hashedCanonicalRequest
  14799. ]);
  14800. // 3. 计算签名
  14801. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  14802. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  14803. // 4. 添加签名到请求头
  14804. $authorizationHeader = sprintf(
  14805. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  14806. $algorithm,
  14807. $access_key,
  14808. $credentialScope,
  14809. $signedHeaders,
  14810. $signature
  14811. );
  14812. return [
  14813. 'Accept' => $accept,
  14814. 'Content-Type' => $contentType,
  14815. 'Host' => $host,
  14816. 'X-Date' => $xDate,
  14817. 'X-Content-Sha256'=> $payloadHash,
  14818. 'Authorization' => $authorizationHeader
  14819. ];
  14820. }
  14821. public function generateScriptWords($cid, $model = 'r1') {
  14822. ini_set('max_execution_time', 0);
  14823. if (!$cid) Utils::throwError('20003: 请选择章节!');
  14824. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  14825. // 模型兼容性处理和思考模式设置
  14826. $thinkingMode = 'disabled';
  14827. $reasoningEffort = 'high';
  14828. if ($model == 'r1') {
  14829. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  14830. $thinkingMode = 'enabled';
  14831. } else {
  14832. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  14833. $thinkingMode = 'disabled';
  14834. }
  14835. $messages = [
  14836. [
  14837. 'role' => 'system',
  14838. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  14839. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  14840. 2.非对话部分请全部用旁白角色代替
  14841. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  14842. ],
  14843. [
  14844. 'role' => 'user',
  14845. 'content' => $content
  14846. ]
  14847. ];
  14848. $post_data = [
  14849. 'model' => $model,
  14850. 'messages' => $messages,
  14851. // 'max_tokens' => 8192,
  14852. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  14853. 'frequency_penalty' => 0,
  14854. 'presence_penalty' => 0,
  14855. 'thinking' => ['type' => $thinkingMode],
  14856. 'response_format' => [
  14857. 'type' => 'text'
  14858. ],
  14859. 'stream' => false
  14860. ];
  14861. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  14862. // 根据模型类型选择调用方法
  14863. $fullContent = '';
  14864. $usage = [];
  14865. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  14866. if (is_array($chatResult)) {
  14867. $fullContent = $chatResult['fullContent'];
  14868. $usage = $chatResult['usage'] ?? [];
  14869. }
  14870. // 仅记录 token 使用明细(不扣积分)
  14871. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  14872. 'model' => $model,
  14873. 'cid' => $cid,
  14874. 'source' => 'generateScriptWords',
  14875. ], $model);
  14876. return $fullContent;
  14877. }
  14878. /**
  14879. * 智能化解析集数信息
  14880. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  14881. *
  14882. * @param string $prompt 用户输入的提示词
  14883. * @return int|null 解析出的集数,如果没有找到则返回null
  14884. */
  14885. private function extractEpisodeNumber($prompt)
  14886. {
  14887. if (empty($prompt)) {
  14888. return null;
  14889. }
  14890. // 定义各种可能的表达模式
  14891. $patterns = [
  14892. // 基本模式:改成N集、调整成N集、修改成N集
  14893. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  14894. // 扩展模式:分成N集、拆分成N集、分割成N集
  14895. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  14896. // 数量模式:N集、共N集、总共N集
  14897. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  14898. // 制作模式:制作N集、生成N集、创建N集
  14899. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  14900. // 计划模式:计划N集、预计N集、打算N集
  14901. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  14902. // 需要模式:需要N集、要N集
  14903. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  14904. // 中文数字模式:改成三集、调整成五集等
  14905. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  14906. // 英文数字模式
  14907. '/(?: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',
  14908. ];
  14909. // 中文数字转阿拉伯数字的映射
  14910. $chineseNumbers = [
  14911. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  14912. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  14913. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  14914. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  14915. ];
  14916. // 逐个尝试匹配模式
  14917. foreach ($patterns as $pattern) {
  14918. if (preg_match($pattern, $prompt, $matches)) {
  14919. $number = trim($matches[1]);
  14920. // 如果是中文数字,转换为阿拉伯数字
  14921. if (isset($chineseNumbers[$number])) {
  14922. return $chineseNumbers[$number];
  14923. }
  14924. // 如果是阿拉伯数字,直接返回
  14925. if (is_numeric($number)) {
  14926. $episodeNum = intval($number);
  14927. // 合理性检查:集数应该在1-100之间
  14928. if ($episodeNum >= 1 && $episodeNum <= 100) {
  14929. return $episodeNum;
  14930. }
  14931. }
  14932. }
  14933. }
  14934. return null;
  14935. }
  14936. /**
  14937. * 调用火山引擎对话(Chat) API
  14938. *
  14939. * @param array $params 包含以下参数:
  14940. * - model: 模型ID(必填)
  14941. * - messages: 消息列表(必填)
  14942. * - stream: 是否流式输出(可选,默认false)
  14943. * - max_tokens: 最大输出token数(可选)
  14944. * - temperature: 采样温度(可选,默认1)
  14945. * - top_p: 核采样概率(可选,默认0.7)
  14946. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  14947. * - presence_penalty: 存在惩罚系数(可选,默认0)
  14948. * - stop: 停止词(可选)
  14949. * - tools: 工具列表(可选)
  14950. * @return array|Generator 非流式返回数组,流式返回生成器
  14951. */
  14952. public function volcEngineChatCompletion(array $params)
  14953. {
  14954. // 百度 GLM 已由 dispatchStreamByModel / dispatchChatOnlyByModel 统一分发,此处不再转发
  14955. $frontModel = getProp($params, 'model', '');
  14956. if (in_array($frontModel, $this->baidu_glm_text_models, true)) {
  14957. Utils::throwError('20003:百度GLM模型请使用统一分发方法dispatchStreamByModel/dispatchChatOnlyByModel调用');
  14958. }
  14959. $apiKey = env('VOLC_AI_API_KEY');
  14960. if (empty($apiKey)) {
  14961. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  14962. }
  14963. // 构建请求参数
  14964. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  14965. $requestData = [
  14966. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  14967. 'messages' => $params['messages'] ?? [],
  14968. ];
  14969. if (!in_array($originalModel, $this->valid_text_models)) {
  14970. Utils::throwError('20003:该模型不支持!');
  14971. }
  14972. // 添加可选参数
  14973. if (isset($params['stream'])) {
  14974. $requestData['stream'] = $params['stream'];
  14975. }
  14976. if (isset($params['stream_options'])) {
  14977. $requestData['stream_options'] = $params['stream_options'];
  14978. }
  14979. if (isset($params['max_tokens'])) {
  14980. $requestData['max_tokens'] = $params['max_tokens'];
  14981. }else if (isset($params['max_completion_tokens'])) {
  14982. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  14983. }else {
  14984. $requestData['max_completion_tokens'] = 100000;
  14985. }
  14986. if (isset($params['temperature'])) {
  14987. $requestData['temperature'] = $params['temperature'];
  14988. }
  14989. if (isset($params['top_p'])) {
  14990. $requestData['top_p'] = $params['top_p'];
  14991. }
  14992. if (isset($params['frequency_penalty'])) {
  14993. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  14994. }
  14995. if (isset($params['presence_penalty'])) {
  14996. $requestData['presence_penalty'] = $params['presence_penalty'];
  14997. }
  14998. if (isset($params['stop'])) {
  14999. $requestData['stop'] = $params['stop'];
  15000. }
  15001. if (isset($params['tools'])) {
  15002. $requestData['tools'] = $params['tools'];
  15003. }
  15004. if (isset($params['tool_choice'])) {
  15005. $requestData['tool_choice'] = $params['tool_choice'];
  15006. }
  15007. if (isset($params['response_format'])) {
  15008. $requestData['response_format'] = $params['response_format'];
  15009. }
  15010. if (isset($params['thinking'])) {
  15011. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  15012. if (is_array($params['thinking'])) {
  15013. $requestData['thinking'] = $params['thinking'];
  15014. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  15015. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  15016. }
  15017. } else {
  15018. $requestData['thinking'] = ['type' => $params['thinking']];
  15019. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  15020. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  15021. }
  15022. }
  15023. } else {
  15024. $requestData['thinking'] = ['type' => 'disabled'];
  15025. }
  15026. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  15027. $client = new Client(['verify' => false, 'timeout' => 1800]);
  15028. try {
  15029. // 判断是否为流式输出
  15030. $isStream = isset($params['stream']) && $params['stream'] === true;
  15031. if ($isStream) {
  15032. // 流式输出
  15033. // 流式请求默认声明返回 usage(未显式传参时)
  15034. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  15035. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  15036. } else {
  15037. // 非流式输出
  15038. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  15039. 'headers' => [
  15040. 'Authorization' => 'Bearer ' . $apiKey,
  15041. 'Content-Type' => 'application/json',
  15042. ],
  15043. 'json' => $requestData
  15044. ]);
  15045. $responseData = json_decode($response->getBody(), true);
  15046. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  15047. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  15048. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  15049. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  15050. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  15051. }
  15052. return [
  15053. 'fullContent' => $fullContent,
  15054. 'fullReasoningContent' => $fullReasoningContent,
  15055. 'usage' => $usage
  15056. ];
  15057. }
  15058. } catch (\Exception $e) {
  15059. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  15060. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  15061. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  15062. }
  15063. }
  15064. /**
  15065. * 火山引擎对话API流式输出
  15066. *
  15067. * @param Client $client HTTP客户端
  15068. * @param string $apiKey API密钥
  15069. * @param array $requestData 请求数据
  15070. * @return Generator
  15071. */
  15072. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  15073. {
  15074. try {
  15075. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  15076. 'headers' => [
  15077. 'Authorization' => 'Bearer ' . $apiKey,
  15078. 'Content-Type' => 'application/json',
  15079. ],
  15080. 'json' => $requestData,
  15081. 'stream' => true
  15082. ]);
  15083. $body = $response->getBody();
  15084. $buffer = '';
  15085. $fullContent = '';
  15086. $fullReasoningContent = '';
  15087. $usage = [];
  15088. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  15089. // 逐行读取流式响应
  15090. while (!$body->eof()) {
  15091. $chunk = $body->read(1024);
  15092. $buffer .= $chunk;
  15093. // 按行分割
  15094. $lines = explode("\n", $buffer);
  15095. $buffer = array_pop($lines);
  15096. foreach ($lines as $line) {
  15097. $line = trim($line);
  15098. if (empty($line)) {
  15099. continue;
  15100. }
  15101. // 检查是否是SSE数据行
  15102. if (strpos($line, 'data: ') !== 0) {
  15103. continue;
  15104. }
  15105. $data = substr($line, 6);
  15106. if ($data === '[DONE]') {
  15107. dLog('deepseek')->info('收到结束标记');
  15108. break 2;
  15109. }
  15110. try {
  15111. $json = json_decode($data, true);
  15112. if (json_last_error() !== JSON_ERROR_NONE) {
  15113. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  15114. continue;
  15115. }
  15116. if (isset($json['choices'][0]['delta'])) {
  15117. $delta = $json['choices'][0]['delta'];
  15118. // 处理思维链内容
  15119. if (isset($delta['reasoning_content'])) {
  15120. $fullReasoningContent .= $delta['reasoning_content'];
  15121. yield [
  15122. 'type' => 'reasoning',
  15123. 'content' => $delta['reasoning_content'],
  15124. 'full_reasoning' => $fullReasoningContent
  15125. ];
  15126. }
  15127. // 处理回答内容
  15128. if (isset($delta['content'])) {
  15129. $fullContent .= $delta['content'];
  15130. yield [
  15131. 'type' => 'content',
  15132. 'content' => $delta['content'],
  15133. ];
  15134. }
  15135. }
  15136. // 获取使用统计信息
  15137. if (isset($json['usage'])) {
  15138. $usage = $json['usage'];
  15139. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  15140. }
  15141. } catch (\Exception $e) {
  15142. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  15143. continue;
  15144. }
  15145. }
  15146. }
  15147. dLog('deepseek')->info('流式读取完成', [
  15148. 'content_length' => strlen($fullContent),
  15149. 'reasoning_length' => strlen($fullReasoningContent)
  15150. ]);
  15151. yield [
  15152. 'type' => 'done',
  15153. 'full_content' => $fullContent,
  15154. 'full_reasoning' => $fullReasoningContent,
  15155. 'usage' => $usage
  15156. ];
  15157. } catch (\Exception $e) {
  15158. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  15159. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  15160. throw $e;
  15161. }
  15162. }
  15163. /**
  15164. * 检查并创建图片生成任务
  15165. *
  15166. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  15167. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  15168. * @param string $nameKey 资源名称字段('role' 或 'scene')
  15169. * @param string $art_style 美术风格
  15170. * @return array 更新后的资源列表
  15171. */
  15172. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  15173. {
  15174. // 确保参数为数组
  15175. $merged_items = is_array($merged_items) ? $merged_items : [];
  15176. $global_items = is_array($global_items) ? $global_items : [];
  15177. // 构建全局资源映射表,用于快速查找
  15178. $global_map = [];
  15179. foreach ($global_items as $item) {
  15180. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  15181. if ($itemKey === '') {
  15182. continue;
  15183. }
  15184. $global_map[$itemKey] = $item;
  15185. }
  15186. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  15187. foreach ($merged_items as &$item) {
  15188. $item_name = getProp($item, $nameKey);
  15189. $item_description = getProp($item, 'description');
  15190. // $item_url = getProp($item, 'url');
  15191. // // 如果已有图片URL,跳过
  15192. // if (!empty($item_url)) {
  15193. // continue;
  15194. // }
  15195. // 如果是旁白角色,跳过
  15196. if ($nameKey === 'role' && $item_name === '旁白') {
  15197. continue;
  15198. }
  15199. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  15200. if ($itemKey === '') {
  15201. continue;
  15202. }
  15203. $need_create_task = false;
  15204. // 条件1:在全局资源中找不到匹配的名称
  15205. if (!isset($global_map[$itemKey])) {
  15206. $need_create_task = true;
  15207. } else {
  15208. // 条件2:名称匹配但描述或 pic_prompt 不一致
  15209. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  15210. $current_description = trim((string)$item_description);
  15211. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  15212. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  15213. // 如果 description 或 pic_prompt 有变化,需要重新生成
  15214. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  15215. $need_create_task = true;
  15216. }
  15217. }
  15218. // 如果需要创建任务,调用图片生成服务
  15219. if ($need_create_task) {
  15220. try {
  15221. // 优先使用 pic_prompt,如果没有则使用 description
  15222. $pic_prompt = getProp($item, 'pic_prompt');
  15223. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  15224. // 添加美术风格前缀
  15225. if ($art_style) {
  15226. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  15227. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  15228. $description = "{$prefix}:{$description}";
  15229. }
  15230. $params = [
  15231. 'prompt' => $description,
  15232. 'ref_img_urls' => []
  15233. ];
  15234. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  15235. $task_id = $task->id;
  15236. if ($task_id) {
  15237. $item['task_id'] = $task_id;
  15238. $item['task_status'] = 'processing';
  15239. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  15240. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  15241. }
  15242. } catch (\Exception $e) {
  15243. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  15244. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  15245. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  15246. // 不抛出异常,继续处理其他资源
  15247. }
  15248. }
  15249. }
  15250. return $merged_items;
  15251. }
  15252. /**
  15253. * 同步新出现的主体和场景到全局
  15254. *
  15255. * @param int $anime_id 动漫ID
  15256. * @param array $merged_roles 合并后的角色列表
  15257. * @param array $merged_scenes 合并后的场景列表
  15258. * @param array $global_roles 全局角色列表
  15259. * @param array $global_scenes 全局场景列表
  15260. * @return void
  15261. */
  15262. private function syncNewResourcesToGlobal(
  15263. int $anime_id,
  15264. array $merged_roles,
  15265. array $merged_scenes,
  15266. array $global_roles,
  15267. array $global_scenes
  15268. ): void {
  15269. // 构建全局角色映射表
  15270. $global_role_map = [];
  15271. foreach ($global_roles as $role) {
  15272. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  15273. if ($roleKey !== '') {
  15274. $global_role_map[$roleKey] = $role;
  15275. }
  15276. }
  15277. // 构建全局场景映射表
  15278. $global_scene_map = [];
  15279. foreach ($global_scenes as $scene) {
  15280. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  15281. if ($sceneKey !== '') {
  15282. $global_scene_map[$sceneKey] = $scene;
  15283. }
  15284. }
  15285. $need_update = false;
  15286. $new_global_roles = $global_roles;
  15287. $new_global_scenes = $global_scenes;
  15288. // 检查并添加新角色到全局
  15289. foreach ($merged_roles as $role) {
  15290. $role_name = getProp($role, 'role');
  15291. // 跳过旁白
  15292. if ($role_name === '旁白') {
  15293. continue;
  15294. }
  15295. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  15296. if ($roleKey === '') {
  15297. continue;
  15298. }
  15299. // 如果全局中不存在该角色,添加到全局
  15300. if (!isset($global_role_map[$roleKey])) {
  15301. $new_global_roles[] = [
  15302. 'role' => $role_name,
  15303. 'description' => getProp($role, 'description', ''),
  15304. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  15305. 'voice_name' => getProp($role, 'voice_name', ''),
  15306. 'voice_type' => getProp($role, 'voice_type', ''),
  15307. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  15308. 'url' => getProp($role, 'url', ''),
  15309. 'task_id' => getProp($role, 'task_id', ''),
  15310. 'task_status' => getProp($role, 'task_status', ''),
  15311. ];
  15312. $global_role_map[$roleKey] = true; // 标记已添加
  15313. $need_update = true;
  15314. dLog('deepseek')->info("新角色同步到全局", [
  15315. 'anime_id' => $anime_id,
  15316. 'role' => $role_name,
  15317. 'task_id' => getProp($role, 'task_id', ''),
  15318. ]);
  15319. }
  15320. // else {
  15321. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  15322. // $global_role = $global_role_map[$roleKey];
  15323. // if (is_array($global_role)) {
  15324. // $updated = false;
  15325. // $update_fields = [];
  15326. // // 检查描述是否更新
  15327. // $current_description = trim((string)getProp($role, 'description'));
  15328. // $global_description = trim((string)getProp($global_role, 'description'));
  15329. // if ($current_description !== '' && $current_description !== $global_description) {
  15330. // $updated = true;
  15331. // $update_fields[] = 'description';
  15332. // }
  15333. // // 检查pic_prompt是否更新
  15334. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  15335. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  15336. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  15337. // $updated = true;
  15338. // $update_fields[] = 'pic_prompt';
  15339. // }
  15340. // // 检查图片任务信息是否更新
  15341. // $current_task_id = getProp($role, 'task_id');
  15342. // $global_task_id = getProp($global_role, 'task_id');
  15343. // if ($current_task_id && $current_task_id !== $global_task_id) {
  15344. // $updated = true;
  15345. // $update_fields[] = 'task_id';
  15346. // }
  15347. // // 如果有更新,同步到全局
  15348. // if ($updated) {
  15349. // foreach ($new_global_roles as &$global_role_item) {
  15350. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  15351. // if ($global_role_key === $roleKey) {
  15352. // if (in_array('description', $update_fields)) {
  15353. // $global_role_item['description'] = $current_description;
  15354. // }
  15355. // if (in_array('pic_prompt', $update_fields)) {
  15356. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  15357. // }
  15358. // if (in_array('task_id', $update_fields)) {
  15359. // $global_role_item['task_id'] = $current_task_id;
  15360. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  15361. // $global_role_item['url'] = getProp($role, 'url', '');
  15362. // }
  15363. // break;
  15364. // }
  15365. // }
  15366. // $need_update = true;
  15367. // dLog('deepseek')->info("角色信息更新到全局", [
  15368. // 'anime_id' => $anime_id,
  15369. // 'role' => $role_name,
  15370. // 'update_fields' => implode(',', $update_fields),
  15371. // ]);
  15372. // }
  15373. // }
  15374. // }
  15375. }
  15376. // 检查并添加新场景到全局
  15377. foreach ($merged_scenes as $scene) {
  15378. $scene_name = getProp($scene, 'scene');
  15379. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  15380. if ($sceneKey === '') {
  15381. continue;
  15382. }
  15383. // 如果全局中不存在该场景,添加到全局
  15384. if (!isset($global_scene_map[$sceneKey])) {
  15385. $new_global_scenes[] = [
  15386. 'scene' => $scene_name,
  15387. 'description' => getProp($scene, 'description', ''),
  15388. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  15389. 'url' => getProp($scene, 'url', ''),
  15390. 'task_id' => getProp($scene, 'task_id', ''),
  15391. 'task_status' => getProp($scene, 'task_status', ''),
  15392. ];
  15393. $global_scene_map[$sceneKey] = true; // 标记已添加
  15394. $need_update = true;
  15395. dLog('deepseek')->info("新场景同步到全局", [
  15396. 'anime_id' => $anime_id,
  15397. 'scene' => $scene_name,
  15398. 'task_id' => getProp($scene, 'task_id', ''),
  15399. ]);
  15400. }
  15401. // else {
  15402. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  15403. // $global_scene = $global_scene_map[$sceneKey];
  15404. // if (is_array($global_scene)) {
  15405. // $updated = false;
  15406. // $update_fields = [];
  15407. // // 检查描述是否更新
  15408. // $current_description = trim((string)getProp($scene, 'description'));
  15409. // $global_description = trim((string)getProp($global_scene, 'description'));
  15410. // if ($current_description !== '' && $current_description !== $global_description) {
  15411. // $updated = true;
  15412. // $update_fields[] = 'description';
  15413. // }
  15414. // // 检查pic_prompt是否更新
  15415. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  15416. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  15417. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  15418. // $updated = true;
  15419. // $update_fields[] = 'pic_prompt';
  15420. // }
  15421. // // 检查图片任务信息是否更新
  15422. // $current_task_id = getProp($scene, 'task_id');
  15423. // $global_task_id = getProp($global_scene, 'task_id');
  15424. // if ($current_task_id && $current_task_id !== $global_task_id) {
  15425. // $updated = true;
  15426. // $update_fields[] = 'task_id';
  15427. // }
  15428. // // 如果有更新,同步到全局
  15429. // if ($updated) {
  15430. // foreach ($new_global_scenes as &$global_scene_item) {
  15431. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  15432. // if ($global_scene_key === $sceneKey) {
  15433. // if (in_array('description', $update_fields)) {
  15434. // $global_scene_item['description'] = $current_description;
  15435. // }
  15436. // if (in_array('pic_prompt', $update_fields)) {
  15437. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  15438. // }
  15439. // if (in_array('task_id', $update_fields)) {
  15440. // $global_scene_item['task_id'] = $current_task_id;
  15441. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  15442. // $global_scene_item['url'] = getProp($scene, 'url', '');
  15443. // }
  15444. // break;
  15445. // }
  15446. // }
  15447. // $need_update = true;
  15448. // dLog('deepseek')->info("场景信息更新到全局", [
  15449. // 'anime_id' => $anime_id,
  15450. // 'scene' => $scene_name,
  15451. // 'update_fields' => implode(',', $update_fields),
  15452. // ]);
  15453. // }
  15454. // }
  15455. // }
  15456. }
  15457. // 如果有新增或更新,更新数据库
  15458. if ($need_update) {
  15459. $update_data = [
  15460. 'roles' => json_encode($new_global_roles, 256),
  15461. 'scenes' => json_encode($new_global_scenes, 256),
  15462. 'updated_at' => date('Y-m-d H:i:s'),
  15463. ];
  15464. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  15465. if ($result !== false) {
  15466. dLog('deepseek')->info("全局角色和场景更新成功", [
  15467. 'anime_id' => $anime_id,
  15468. 'roles_count' => count($new_global_roles),
  15469. 'scenes_count' => count($new_global_scenes),
  15470. ]);
  15471. } else {
  15472. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  15473. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  15474. }
  15475. }
  15476. }
  15477. }