DeepSeekService.php 961 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665
  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. // GPT 上游错误详情缓存(按异常对象 id 缓存,避免流式响应体被重复读取后丢失)
  35. private $gpt_upstream_error_cache = [];
  36. protected $aiImageGenerationService;
  37. protected $pointsService;
  38. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  39. $this->aiImageGenerationService = $aiImageGenerationService;
  40. $this->pointsService = $pointsService;
  41. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  42. $this->api_key = env('DEEPSEEK_API_KEY');
  43. $this->headers = [
  44. 'Authorization' => 'Bearer '.$this->api_key,
  45. 'Content-Type' => 'application/json; charset=UTF-8'
  46. ];
  47. // 火山引擎模型列表
  48. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  49. // GPT文本模型列表
  50. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  51. // Gemini文本模型列表
  52. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  53. // 百度 AI 网关 GLM 文本模型列表
  54. $this->baidu_glm_text_models = BaseConst::BAIDU_GLM_TEXT_MODELS;
  55. $this->sys_message = [
  56. 'role' => 'system',
  57. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  58. 强制要求:\n
  59. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  60. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  61. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  62. 普通要求:\n
  63. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  64. 2.<分集剧本>的要求如下:
  65.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  66.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  67.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  68.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  69. \n\n
  70. 示例如下:\n
  71. ###剧本名:西昆仑
  72. ###故事梗概
  73. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  74. ###剧本亮点
  75. 亮点1:绝境奇药,生死一线
  76. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  77. 亮点2:结拜兄妹,化解尴尬
  78. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  79. 亮点3:纤发夺命,情愫暗涌
  80. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  81. ###人物关系
  82. 阿雪与梁萧之间存在兄妹之情。
  83. ###核心矛盾
  84. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  85. ###主体列表
  86. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  87. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  88. 阴阳球:天地异宝,能化生精气,救人于危难。
  89. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  90. ###美术风格
  91. 基础画风风格词:厚涂古风
  92. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  93. ###场景列表
  94. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  95. ###分集剧本
  96. ##分集01
  97. 第1集: 第一集的标题
  98. 场景描述:地点、时间、场景
  99. 运镜:固定近距离
  100. 出场角色:男主、女主
  101. 台词内容:
  102. 女主: 女主对话
  103. 男主:男主对话
  104. 女主: 女主对话
  105. 男主: 男主对话
  106. ##分集02
  107. 第2集: 第二集的标题
  108. 场景描述:地点、时间、场景
  109. 运镜:固定近距离
  110. 出场角色:男主、女主
  111. 台词内容:
  112. 女主: 女主对话
  113. 男主:男主对话
  114. 女主: 女主对话
  115. 男主: 男主对话"
  116. ];
  117. }
  118. /**
  119. * 通用文生文方法 - 支持多模型流式输出、图片输入;视频输入仅 Gemini 模型支持
  120. *
  121. * @param array $data 请求参数
  122. * @return \Generator 返回生成器,用于流式输出
  123. */
  124. public function generateText($data) {
  125. // 获取请求参数
  126. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  127. $messages = getProp($data, 'messages', []);
  128. $systemPrompt = getProp($data, 'system_prompt', '');
  129. $prompt = getProp($data, 'prompt', '');
  130. $images = getProp($data, 'images', []); // 支持多张图片
  131. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  132. $videos = getProp($data, 'videos', []); // Gemini 支持视频文件
  133. $videoUrls = getProp($data, 'video_urls', []); // Gemini 支持视频URL
  134. $isGeminiModel = in_array($model, $this->gemini_text_models);
  135. if ((!empty($videos) || !empty($videoUrls)) && !$isGeminiModel) {
  136. Utils::throwError('20003:仅Gemini模型支持视频输入');
  137. }
  138. // 计费预检:纯文生文按 normal 档(3);有参考图/视频输入按模型固定价格(图生文)
  139. $uid = Site::getUid();
  140. $chargeModality = '';
  141. $chargePoints = 0;
  142. $hasImageMedia = !empty($images) || !empty($imageUrls)
  143. || $this->messagesContainMedia($messages, ['image_url', 'image']);
  144. $hasVideoMedia = !empty($videos) || !empty($videoUrls)
  145. || $this->messagesContainMedia($messages, ['video_url', 'video']);
  146. if ($hasImageMedia || $hasVideoMedia) {
  147. $chargeModality = $hasVideoMedia ? 'video' : 'image';
  148. $chargePoints = $this->pointsService->getImageChatChargePoints($model);
  149. } else {
  150. $chargeModality = 'text';
  151. $chargePoints = $this->pointsService->getChatChargePoints('', 'normal');
  152. }
  153. if ($chargePoints > 0) {
  154. $this->pointsService->checkUserPointsEnough($chargePoints, $uid);
  155. }
  156. // 如果没有提供messages,则根据system_prompt、content和images构建
  157. if (empty($messages)) {
  158. $messages = [];
  159. // 添加系统提示词
  160. if (!empty($systemPrompt)) {
  161. $messages[] = [
  162. 'role' => 'system',
  163. 'content' => $systemPrompt
  164. ];
  165. }
  166. // 构建用户消息内容(支持文本+图片)
  167. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  168. $userMessage = [
  169. 'role' => 'user',
  170. 'content' => []
  171. ];
  172. // 添加文本内容
  173. if (!empty($prompt)) {
  174. $userMessage['content'][] = [
  175. 'type' => 'text',
  176. 'text' => $prompt
  177. ];
  178. }
  179. // 处理上传的图片文件
  180. if (!empty($images)) {
  181. if (!is_array($images)) {
  182. $images = [$images];
  183. }
  184. foreach ($images as $image) {
  185. $imageBase64 = $this->processImageToBase64($image);
  186. if ($imageBase64) {
  187. $userMessage['content'][] = [
  188. 'type' => 'image_url',
  189. 'image_url' => [
  190. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  191. ]
  192. ];
  193. }
  194. }
  195. }
  196. // 处理图片URL
  197. if (!empty($imageUrls)) {
  198. if (!is_array($imageUrls)) {
  199. $imageUrls = [$imageUrls];
  200. }
  201. foreach ($imageUrls as $url) {
  202. if (!empty($url)) {
  203. $userMessage['content'][] = [
  204. 'type' => 'image_url',
  205. 'image_url' => [
  206. 'url' => $url
  207. ]
  208. ];
  209. }
  210. }
  211. }
  212. // 处理上传的视频文件(仅 Gemini)
  213. if (!empty($videos) && $isGeminiModel) {
  214. if (!is_array($videos)) {
  215. $videos = [$videos];
  216. }
  217. foreach ($videos as $video) {
  218. $inlineData = $this->processMediaToInlineData($video);
  219. if ($inlineData) {
  220. $userMessage['content'][] = [
  221. 'type' => 'video',
  222. 'inline_data' => $inlineData
  223. ];
  224. }
  225. }
  226. }
  227. // 处理视频URL(仅 Gemini)
  228. if (!empty($videoUrls) && $isGeminiModel) {
  229. if (!is_array($videoUrls)) {
  230. $videoUrls = [$videoUrls];
  231. }
  232. foreach ($videoUrls as $url) {
  233. if (!empty($url)) {
  234. $userMessage['content'][] = [
  235. 'type' => 'video_url',
  236. 'video_url' => ['url' => $url]
  237. ];
  238. }
  239. }
  240. }
  241. // 如果只有文本内容,简化为字符串格式
  242. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  243. $userMessage['content'] = $userMessage['content'][0]['text'];
  244. }
  245. $messages[] = $userMessage;
  246. }
  247. }
  248. // 验证messages不为空
  249. if (empty($messages)) {
  250. Utils::throwError('20003:请提供有效的对话内容');
  251. }
  252. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  253. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  254. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  255. if ($model === 'deepseek-chat') {
  256. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  257. $model = 'deepseek-v4-flash';
  258. $thinkingMode = 'disabled';
  259. } elseif ($model === 'deepseek-reasoner') {
  260. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  261. $model = 'deepseek-v4-flash';
  262. $thinkingMode = 'enabled';
  263. }
  264. // 构建请求参数
  265. $post_data = [
  266. 'model' => $model,
  267. 'messages' => $messages,
  268. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  269. 'temperature' => getProp($data, 'temperature', 1),
  270. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  271. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  272. 'thinking' => ['type' => $thinkingMode],
  273. 'stream' => true // 启用流式输出
  274. ];
  275. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  276. // 添加可选参数
  277. if (isset($data['top_p'])) {
  278. $post_data['top_p'] = $data['top_p'];
  279. }
  280. if (isset($data['response_format'])) {
  281. $post_data['response_format'] = $data['response_format'];
  282. }
  283. // 根据模型类型选择流式实现
  284. $streamGenerator = $this->dispatchStreamByModel($post_data);
  285. if ($chargePoints > 0) {
  286. return $this->wrapGenerateTextCharge($streamGenerator, $uid, $model, $chargePoints, $chargeModality);
  287. }
  288. // 免费场景(0 积分):流式生成成功后仅记录 token 使用明细
  289. return $this->wrapGenerateTextTokenRecord($streamGenerator, $uid, $model);
  290. }
  291. /**
  292. * 流式生成成功后仅记录 token 明细(纯文本免费场景,不扣积分)
  293. *
  294. * @param \Generator $generator
  295. * @param int $uid
  296. * @param string $model
  297. * @return \Generator
  298. */
  299. private function wrapGenerateTextTokenRecord(\Generator $generator, int $uid, string $model, string $source = 'generateText'): \Generator
  300. {
  301. $recorded = false;
  302. foreach ($generator as $chunk) {
  303. if (!$recorded && isset($chunk['type']) && $chunk['type'] === 'done') {
  304. $this->recordTextTokenOnly($uid, $this->pointsService->getTokensFromUsage(getProp($chunk, 'usage', [])), [
  305. 'model' => $model,
  306. 'source' => $source,
  307. ], $model);
  308. $recorded = true;
  309. }
  310. yield $chunk;
  311. }
  312. }
  313. /**
  314. * 流式生成成功后再按档位/模型规则扣费(文生文 normal 档 / 图生文按模型固定价格)
  315. *
  316. * @param \Generator $generator
  317. * @param int $uid
  318. * @param string $model
  319. * @param int $points
  320. * @param string $modality
  321. * @return \Generator
  322. */
  323. private function wrapGenerateTextCharge(\Generator $generator, int $uid, string $model, int $points, string $modality): \Generator
  324. {
  325. $charged = false;
  326. foreach ($generator as $chunk) {
  327. if (!$charged && isset($chunk['type']) && $chunk['type'] === 'done') {
  328. $fullContent = (string)getProp($chunk, 'full_content', getProp($chunk, 'answer', ''));
  329. if ($fullContent !== '') {
  330. $this->chargeMultimodal($uid, $model, $points, $modality, getProp($chunk, 'usage', []));
  331. $charged = true;
  332. }
  333. }
  334. yield $chunk;
  335. }
  336. }
  337. /**
  338. * AI 对话(含图片/视频 -> 文本)成功后扣费并记录积分与 token 明细
  339. *
  340. * @param int $uid
  341. * @param string $model
  342. * @param int $points
  343. * @param string $modality
  344. * @param mixed $usage
  345. * @return void
  346. */
  347. private function chargeMultimodal(int $uid, string $model, int $points, string $modality, $usage): void
  348. {
  349. $result = $this->pointsService->recordChatCharge(
  350. $uid,
  351. $points,
  352. $this->pointsService->getTokensFromUsage($usage),
  353. [
  354. 'model' => $model,
  355. 'modality' => $modality,
  356. 'source' => 'generateText',
  357. ],
  358. '',
  359. $model
  360. );
  361. if (empty($result['charged'])) {
  362. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  363. }
  364. }
  365. /**
  366. * 检查 OpenAI 风格消息中是否包含指定媒体类型
  367. *
  368. * @param array $messages
  369. * @param array $mediaTypes
  370. * @return bool
  371. */
  372. private function messagesContainMedia(array $messages, array $mediaTypes): bool
  373. {
  374. foreach ($messages as $message) {
  375. $content = getProp($message, 'content', '');
  376. if (!is_array($content)) {
  377. continue;
  378. }
  379. foreach ($content as $part) {
  380. if (is_array($part) && in_array(getProp($part, 'type', ''), $mediaTypes, true)) {
  381. return true;
  382. }
  383. }
  384. }
  385. return false;
  386. }
  387. public function createGenerateText($data) {
  388. $file = getProp($data, 'file');
  389. $episode_num = getProp($data, 'episode_num');
  390. $uid = Site::getUid();
  391. $cpid = Site::getCpid();
  392. if (!$file) {
  393. Utils::throwError('20003:请上传文件');
  394. }
  395. // 提取文件内容
  396. $content = $this->extractFileContent($file);
  397. if (!$content) {
  398. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  399. }
  400. // 拆分章节并校验章节总数、标题连续性
  401. if ($episode_num) {
  402. $this->validateGenerateTextChapters($content, (int)$episode_num);
  403. }
  404. // 获取原始文件名(不含扩展名)作为script_name
  405. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  406. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  407. // 字节安全剥离,不依赖服务器locale设置
  408. $originalName = $file->getClientOriginalName();
  409. $extension = $file->getClientOriginalExtension();
  410. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  411. ? substr($originalName, 0, -strlen($extension) - 1)
  412. : $originalName;
  413. if ($script_name === '') {
  414. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  415. }
  416. // 如果同一用户的剧本名存在则提示
  417. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  418. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  419. }
  420. // 插入数据到mp_scripts表
  421. $script_id = DB::table('mp_scripts')->insertGetId([
  422. 'script_name' => $script_name,
  423. 'user_id' => $uid,
  424. 'cpid' => $cpid,
  425. 'content' => $content,
  426. 'created_at' => date('Y-m-d H:i:s'),
  427. 'updated_at' => date('Y-m-d H:i:s')
  428. ]);
  429. return [
  430. 'script_id' => $script_id,
  431. 'script_name' => $script_name
  432. ];
  433. }
  434. /**
  435. * AI对话调用成功后的积分扣费(返回结果前调用)
  436. *
  437. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  438. *
  439. * @param int $uid
  440. * @param int $tokens
  441. * @param array $chargeInfo
  442. * @return void
  443. */
  444. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo, string $chargeType = 'special'): void
  445. {
  446. // api_type 记录真实模型名(缺失时回退 deepseek 大类),保证明细与统计口径准确
  447. $model = (string)getProp($chargeInfo, 'model', '');
  448. $result = $this->pointsService->recordChatCharge(
  449. $uid,
  450. $this->pointsService->getChatChargePoints($model, $chargeType),
  451. $tokens,
  452. $chargeInfo,
  453. '',
  454. $model !== '' ? $model : 'deepseek'
  455. );
  456. if (empty($result['charged'])) {
  457. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  458. }
  459. }
  460. /**
  461. * 安全获取当前登录用户ID
  462. *
  463. * 命令行/队列等无用户上下文的场景返回 0,由记录方法自行跳过。
  464. *
  465. * @return int
  466. */
  467. private function getCurrentUid(): int
  468. {
  469. try {
  470. return (int)Site::getUid();
  471. } catch (\Throwable $e) {
  472. return 0;
  473. }
  474. }
  475. /**
  476. * 记录文生文 token 使用明细(仅记录,不扣积分)
  477. *
  478. * 用于不按积分计费的文生文接口;记录失败不影响主流程。
  479. *
  480. * @param int $uid 用户ID(0 时跳过)
  481. * @param int $tokens 消耗 token 数
  482. * @param array $chargeInfo 计费/来源信息(model、source 等)
  483. * @param string $apiType API 类型/模型标识
  484. * @return void
  485. */
  486. private function recordTextTokenOnly(int $uid, int $tokens, array $chargeInfo, string $apiType = ''): void
  487. {
  488. try {
  489. $this->pointsService->recordTokenOnlyDetail(
  490. $uid,
  491. $tokens,
  492. $chargeInfo,
  493. MpUserPointsDetail::TYPE_CHAT,
  494. $apiType,
  495. ''
  496. );
  497. } catch (\Throwable $e) {
  498. dLog('points')->warning('token明细记录异常(不影响主流程): ' . $e->getMessage(), [
  499. 'uid' => $uid,
  500. 'source' => $chargeInfo['source'] ?? '',
  501. ]);
  502. }
  503. }
  504. /**
  505. * 拆分剧本内容并校验章节总数与标题连续性
  506. *
  507. * @param string $content
  508. * @param int $episodeNum
  509. * @return void
  510. */
  511. private function validateGenerateTextChapters($content, $episodeNum)
  512. {
  513. $chapters = splitContent($content);
  514. if (count($chapters) !== $episodeNum) {
  515. Utils::throwError('20003:章节总数与集数不一致,请检查上传内容');
  516. }
  517. if (empty($chapters)) {
  518. return;
  519. }
  520. // 先尝试从标题正则中解析序号,确认是否从1开始连续递增
  521. $numbers = [];
  522. $unparsedIndex = null;
  523. foreach ($chapters as $index => $chapter) {
  524. $num = $this->parseChapterNumber($chapter['title']);
  525. if ($num === null) {
  526. $unparsedIndex = $index;
  527. break;
  528. }
  529. $numbers[] = $num;
  530. }
  531. if ($unparsedIndex === null) {
  532. $expected = 1;
  533. foreach ($numbers as $index => $num) {
  534. if ($num !== $expected) {
  535. $title = mb_substr(trim((string)$chapters[$index]['title']), 0, 40);
  536. Utils::throwError('20003:章节序号不连续:第' . ($index + 1) . '个章节“' . $title . '”序号为' . $num . ',预期为' . $expected);
  537. }
  538. $expected++;
  539. }
  540. return;
  541. }
  542. // 标题格式无法用正则确认时,交给模型分析
  543. $titles = array_column($chapters, 'title');
  544. $aiResult = $this->validateChapterSequenceByAI($titles);
  545. if ($aiResult['valid'] === false) {
  546. $badIndex = $aiResult['invalid_index'] ?: $unparsedIndex + 1;
  547. if (isset($chapters[$badIndex - 1])) {
  548. $title = mb_substr(trim((string)$chapters[$badIndex - 1]['title']), 0, 40);
  549. Utils::throwError('20003:章节序号不连续:第' . $badIndex . '个章节“' . $title . '”序号异常,请检查');
  550. }
  551. Utils::throwError('20003:章节序号不连续,请检查章节标题格式');
  552. }
  553. if ($aiResult['valid'] === null) {
  554. if (isset($chapters[$unparsedIndex])) {
  555. $title = mb_substr(trim((string)$chapters[$unparsedIndex]['title']), 0, 40);
  556. Utils::throwError('20003:无法确认第' . ($unparsedIndex + 1) . '个章节“' . $title . '”的章节序号,请检查标题格式');
  557. }
  558. Utils::throwError('20003:无法确认章节标题连续性,请检查章节标题格式');
  559. }
  560. }
  561. /**
  562. * 从章节标题中解析序号,支持阿拉伯数字和中文数字
  563. *
  564. * @param string $title
  565. * @return int|null
  566. */
  567. private function parseChapterNumber($title)
  568. {
  569. if (!preg_match('/第\s*([一二两三四五六七八九十百千万0-9]+)\s*[章节集幕场回话]/u', $title, $match)) {
  570. return null;
  571. }
  572. return $this->convertChineseNumber($match[1]);
  573. }
  574. /**
  575. * 中文数字转阿拉伯数字(支持到千)
  576. *
  577. * @param string $numStr
  578. * @return int
  579. */
  580. private function convertChineseNumber($numStr)
  581. {
  582. if (preg_match('/^\d+$/', $numStr)) {
  583. return (int)$numStr;
  584. }
  585. $map = [
  586. '零' => 0,
  587. '一' => 1,
  588. '二' => 2,
  589. '两' => 2,
  590. '三' => 3,
  591. '四' => 4,
  592. '五' => 5,
  593. '六' => 6,
  594. '七' => 7,
  595. '八' => 8,
  596. '九' => 9
  597. ];
  598. $total = 0;
  599. $section = 0;
  600. $length = mb_strlen($numStr);
  601. for ($i = 0; $i < $length; $i++) {
  602. $char = mb_substr($numStr, $i, 1);
  603. if (isset($map[$char])) {
  604. $section = $map[$char];
  605. } elseif ($char === '十') {
  606. $total += $section === 0 ? 10 : $section * 10;
  607. $section = 0;
  608. } elseif ($char === '百') {
  609. $total += $section === 0 ? 100 : $section * 100;
  610. $section = 0;
  611. } elseif ($char === '千') {
  612. $total += $section === 0 ? 1000 : $section * 1000;
  613. $section = 0;
  614. }
  615. }
  616. return $total + $section;
  617. }
  618. /**
  619. * 用 deepseek-v4-flash 非流式判断章节标题是否从1开始连续编号
  620. *
  621. * @param array $titles
  622. * @return array{valid: bool|null, invalid_index: int|null}
  623. */
  624. private function validateChapterSequenceByAI($titles)
  625. {
  626. $titleLines = [];
  627. foreach (array_slice($titles, 0, 200) as $index => $title) {
  628. $titleLines[] = ($index + 1) . '. ' . mb_substr(trim((string)$title), 0, 80);
  629. }
  630. $result = [
  631. 'valid' => null,
  632. 'invalid_index' => null
  633. ];
  634. $post_data = [
  635. 'model' => 'deepseek-v4-flash',
  636. 'messages' => [
  637. [
  638. 'role' => 'system',
  639. 'content' => '你是剧本章节校验助手。用户会给出章节标题列表,请判断这些标题中的编号是否从第1章/第1集开始连续递增,支持阿拉伯数字和中文数字。只输出 JSON,格式为 {"valid":true};若不连续则输出 {"valid":false,"invalid_index":N},其中 N 是第一个序号异常的章节序号(从1开始),不要输出其他内容。',
  640. ],
  641. [
  642. 'role' => 'user',
  643. 'content' => implode("\n", $titleLines),
  644. ],
  645. ],
  646. 'temperature' => 0,
  647. 'frequency_penalty' => 0,
  648. 'presence_penalty' => 0,
  649. 'stream' => false,
  650. ];
  651. try {
  652. $result = $this->chatOnly($post_data, 8);
  653. $content = trim((string)($result['fullContent'] ?? ''));
  654. if (preg_match('/"valid"\s*:\s*(true|false)/i', $content, $match)) {
  655. $result['valid'] = strtolower($match[1]) === 'true';
  656. }
  657. if (preg_match('/"invalid_index"\s*:\s*(\d+)/i', $content, $match)) {
  658. $result['invalid_index'] = (int)$match[1];
  659. }
  660. // 仅记录 token 使用明细(不扣积分):该校验为流程内的额外模型调用
  661. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  662. 'model' => 'deepseek-v4-flash',
  663. 'source' => 'validateChapterSequenceByAI',
  664. ], 'deepseek-v4-flash');
  665. } catch (\Exception $e) {
  666. dLog('deepseek')->error('章节连续性AI校验失败: ' . $e->getMessage());
  667. }
  668. return $result;
  669. }
  670. /**
  671. * 通用文生文(流式版本)- newGenerateText 的 stream=1 分支
  672. * 支持与 newGenerateText 相同的参数(模板/剧本/JSON输出/图片输入),
  673. * 输出格式与 generateText 一致:yield type=content / reasoning / done
  674. *
  675. * @param array $data 请求参数
  676. * @return \Generator
  677. */
  678. public function newGenerateTextStream($data, $existingTask = null) {
  679. $model = getProp($data, 'model', 'deepseek-v4-pro');
  680. $messages = getProp($data, 'messages', []);
  681. $systemPrompt = getProp($data, 'system_prompt', '');
  682. $prompt = getProp($data, 'prompt', '');
  683. $images = getProp($data, 'images', []);
  684. $imageUrls = getProp($data, 'image_urls', []);
  685. $responseFormat = getProp($data, 'response_format', 'text');
  686. $templateId = getProp($data, 'template_id', 0);
  687. $script_id = getProp($data, 'script_id', 0);
  688. $sequence = getProp($data, 'sequence', 0);
  689. $generateTaskId = 0;
  690. // 异步 worker 场景直接使用任务记录中的用户,避免命令行下无登录上下文
  691. $uid = $existingTask ? (int)$existingTask->uid : (int)Site::getUid();
  692. if ($script_id > 0 && !$existingTask) {
  693. $runningTask = DB::table('mp_script_generate_tasks')
  694. ->where('uid', $uid)
  695. ->where('script_id', $script_id)
  696. ->orderByDesc('id')
  697. ->first();
  698. if ($runningTask && in_array(getProp($runningTask, 'status'), ['pending', 'processing'])) {
  699. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  700. }
  701. }
  702. // 如果提供了script_id,从数据库获取剧本内容作为原文
  703. $originalContent = '';
  704. $hasValidScript = false;
  705. $rawPrompt = $prompt; // 保存用户原始输入,供模板一致性判断
  706. if ($script_id > 0) {
  707. $script = DB::table('mp_scripts')
  708. ->where('id', $script_id)
  709. ->where('is_deleted', 0)
  710. ->first();
  711. if (!$script) {
  712. Utils::throwError('20003:剧本不存在或已删除');
  713. }
  714. $originalContent = $script->content ?? '';
  715. if (empty($originalContent)) {
  716. Utils::throwError('20003:剧本内容为空');
  717. }
  718. $hasValidScript = true;
  719. if (!empty($prompt)) {
  720. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  721. } else {
  722. $prompt = "原文内容:\n" . $originalContent;
  723. }
  724. }
  725. // 如果提供了template_id,从数据库获取template_prompt
  726. if ($templateId > 0) {
  727. $template = DB::table('mp_prompt_templates')
  728. ->where('id', $templateId)
  729. ->where('is_deleted', 0)
  730. ->first();
  731. if (!$template) {
  732. Utils::throwError('20003:模板不存在或已删除');
  733. }
  734. $templatePrompt = $template->template_prompt ?? '';
  735. if (!empty($templatePrompt)) {
  736. // 模板提示词与用户输入基本一致时只保留一个,避免重复提示词
  737. // 剧本模式下当前 prompt 含原文内容需保留,其余情况以模板内容为准
  738. $trimmedRawPrompt = trim((string)$rawPrompt);
  739. if ($trimmedRawPrompt !== '' && mb_strtolower($trimmedRawPrompt) === mb_strtolower(trim($templatePrompt))) {
  740. if (!$hasValidScript) {
  741. $prompt = $templatePrompt;
  742. }
  743. } elseif (!empty($prompt)) {
  744. $prompt = $templatePrompt . "\n\n" . $prompt;
  745. } else {
  746. $prompt = $templatePrompt;
  747. }
  748. }
  749. }
  750. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  751. if (empty($messages)) {
  752. $messages = [];
  753. if (!empty($systemPrompt)) {
  754. $messages[] = [
  755. 'role' => 'system',
  756. 'content' => $systemPrompt
  757. ];
  758. }
  759. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  760. $userMessage = [
  761. 'role' => 'user',
  762. 'content' => []
  763. ];
  764. if (!empty($prompt)) {
  765. $userMessage['content'][] = [
  766. 'type' => 'text',
  767. 'text' => $prompt
  768. ];
  769. }
  770. if (!empty($images)) {
  771. if (!is_array($images)) {
  772. $images = [$images];
  773. }
  774. foreach ($images as $image) {
  775. $imageBase64 = $this->processImageToBase64($image);
  776. if ($imageBase64) {
  777. $userMessage['content'][] = [
  778. 'type' => 'image_url',
  779. 'image_url' => [
  780. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  781. ]
  782. ];
  783. }
  784. }
  785. }
  786. if (!empty($imageUrls)) {
  787. if (!is_array($imageUrls)) {
  788. $imageUrls = [$imageUrls];
  789. }
  790. foreach ($imageUrls as $url) {
  791. if (!empty($url)) {
  792. $userMessage['content'][] = [
  793. 'type' => 'image_url',
  794. 'image_url' => [
  795. 'url' => $url
  796. ]
  797. ];
  798. }
  799. }
  800. }
  801. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  802. $userMessage['content'] = $userMessage['content'][0]['text'];
  803. }
  804. $messages[] = $userMessage;
  805. }
  806. }
  807. if (empty($messages)) {
  808. Utils::throwError('20003:请提供有效的对话内容');
  809. }
  810. // 模型兼容性处理
  811. $thinkingMode = getProp($data, 'thinking', 'disabled');
  812. $reasoningEffort = getProp($data, 'reasoning_effort', 'high');
  813. if ($model === 'deepseek-chat') {
  814. $model = 'deepseek-v4-flash';
  815. $thinkingMode = 'disabled';
  816. } elseif ($model === 'deepseek-reasoner') {
  817. $model = 'deepseek-v4-flash';
  818. $thinkingMode = 'enabled';
  819. }
  820. // 构建请求参数(流式)
  821. $post_data = [
  822. 'model' => $model,
  823. 'messages' => $messages,
  824. 'temperature' => getProp($data, 'temperature', 1),
  825. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  826. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  827. 'thinking' => ['type' => $thinkingMode],
  828. 'stream' => true
  829. ];
  830. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  831. if (isset($data['top_p'])) {
  832. $post_data['top_p'] = $data['top_p'];
  833. }
  834. // response_format=json 时附加 JSON 说明与响应格式(与 newGenerateText 一致)
  835. if ($responseFormat === 'json') {
  836. $hasJsonKeyword = false;
  837. foreach ($post_data['messages'] as $message) {
  838. if (isset($message['content'])) {
  839. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  840. if (stripos($content, 'json') !== false) {
  841. $hasJsonKeyword = true;
  842. break;
  843. }
  844. }
  845. }
  846. if (!$hasJsonKeyword) {
  847. $lastMessageIndex = count($post_data['messages']) - 1;
  848. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  849. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  850. if (is_string($lastContent)) {
  851. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  852. } elseif (is_array($lastContent)) {
  853. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  854. if ($contentPart['type'] === 'text') {
  855. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  856. break;
  857. }
  858. }
  859. }
  860. }
  861. }
  862. $post_data['response_format'] = ['type' => 'json_object'];
  863. }
  864. // 如果提供了script_id,创建剧本资产生成任务
  865. if ($script_id > 0) {
  866. if ($existingTask) {
  867. // 异步 worker:接管已创建的 pending 任务,不再新建
  868. $generateTaskId = (int)$existingTask->id;
  869. } else {
  870. // 同步调用:保持原行为,创建 processing 任务
  871. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  872. 'uid' => $uid,
  873. 'script_id' => $script_id,
  874. 'sequence' => $sequence,
  875. 'status' => 'processing',
  876. 'prompt' => getProp($data, 'prompt', ''),
  877. 'started_at' => date('Y-m-d H:i:s'),
  878. 'created_at' => date('Y-m-d H:i:s'),
  879. 'updated_at' => date('Y-m-d H:i:s')
  880. ]);
  881. }
  882. }
  883. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  884. if ($hasValidScript) {
  885. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  886. }
  887. // 根据模型类型选择流式实现
  888. $streamGenerator = $this->dispatchStreamByModel($post_data);
  889. // 流式输出包装:done 时更新任务状态、扣费并保存对话记录
  890. return $this->wrapNewGenerateTextStream($streamGenerator, [
  891. 'uid' => $uid,
  892. 'model' => $model,
  893. 'generate_task_id' => $generateTaskId,
  894. 'has_valid_script' => $hasValidScript,
  895. 'script_id' => $script_id,
  896. 'sequence' => $sequence,
  897. 'original_prompt' => getProp($data, 'prompt', ''),
  898. 'response_format' => $responseFormat,
  899. ]);
  900. }
  901. /**
  902. * 流式生成收尾包装:done 时更新剧本资产生成任务、扣除积分并保存对话记录
  903. *
  904. * @param \Generator $generator
  905. * @param array $ctx
  906. * @return \Generator
  907. */
  908. private function wrapNewGenerateTextStream(\Generator $generator, array $ctx): \Generator
  909. {
  910. $fullContent = '';
  911. $usage = [];
  912. $finished = false;
  913. try {
  914. foreach ($generator as $chunk) {
  915. if (isset($chunk['type']) && $chunk['type'] === 'content') {
  916. $fullContent .= (string)getProp($chunk, 'content', '');
  917. }
  918. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  919. $fullContent = (string)getProp($chunk, 'full_content', $fullContent);
  920. $usage = getProp($chunk, 'usage', []);
  921. // 流式场景下部分模型/中转站不强制 JSON 输出,兜底提取标准 JSON
  922. if (($ctx['response_format'] ?? 'text') === 'json') {
  923. $fullContent = $this->extractJsonContent($fullContent);
  924. }
  925. $finished = true;
  926. // 保存对话记录并将 records 附加到 done 消息(无论 script_id 是否有值都返回 records 数组)
  927. $chunk['records'] = [];
  928. if (!empty($ctx['script_id'])) {
  929. try {
  930. $now = now();
  931. // 两条对话记录(user/assistant)在同一事务内写入,保证原子性
  932. $chunk['records'] = DB::transaction(function () use ($ctx, $fullContent, $now) {
  933. DB::table('mp_script_records')->insert([
  934. [
  935. 'uid' => $ctx['uid'],
  936. 'script_id' => $ctx['script_id'],
  937. 'sequence' => $ctx['sequence'],
  938. 'role' => 'user',
  939. 'content' => $ctx['original_prompt'],
  940. 'created_at' => $now,
  941. 'updated_at' => $now,
  942. ],
  943. [
  944. 'uid' => $ctx['uid'],
  945. 'script_id' => $ctx['script_id'],
  946. 'sequence' => $ctx['sequence'],
  947. 'role' => 'assistant',
  948. 'content' => $fullContent,
  949. 'created_at' => $now,
  950. 'updated_at' => $now,
  951. ],
  952. ]);
  953. return DB::table('mp_script_records')
  954. ->where('uid', $ctx['uid'])
  955. ->where('script_id', $ctx['script_id'])
  956. ->where('sequence', $ctx['sequence'])
  957. ->orderBy('id', 'desc')
  958. ->limit(2)
  959. ->get()
  960. ->map(function ($record) {
  961. return [
  962. 'rid' => $record->id,
  963. 'script_id' => $record->script_id,
  964. 'sequence' => $record->sequence,
  965. 'role' => $record->role,
  966. 'content' => $record->content,
  967. 'created_at' => $record->created_at,
  968. ];
  969. })
  970. ->reverse()
  971. ->values()
  972. ->toArray();
  973. });
  974. } catch (\Exception $e) {
  975. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  976. $chunk['records'] = [];
  977. }
  978. }
  979. }
  980. yield $chunk;
  981. }
  982. if ($finished) {
  983. // 任务状态与扣费在同一事务内:扣费失败则任务状态一并回滚,由外层 catch 置为 failed
  984. DB::transaction(function () use ($ctx, $fullContent, $usage) {
  985. if (!empty($ctx['generate_task_id'])) {
  986. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  987. 'status' => 'success',
  988. 'result' => $fullContent,
  989. 'completed_at' => date('Y-m-d H:i:s'),
  990. 'updated_at' => date('Y-m-d H:i:s'),
  991. ]);
  992. }
  993. if ($ctx['has_valid_script'] && $fullContent !== '') {
  994. $this->chargeChatSuccess($ctx['uid'], $this->pointsService->getTokensFromUsage($usage), [
  995. 'model' => $ctx['model'],
  996. 'script_id' => $ctx['script_id'],
  997. 'sequence' => $ctx['sequence'],
  998. 'source' => 'newGenerateText',
  999. ]);
  1000. }
  1001. });
  1002. // JSON 输出结果的安全校验/修复与观察(事务外执行,不改变 result 与 SSE 推送内容)
  1003. if (!empty($ctx['generate_task_id'])) {
  1004. $this->guardScriptGenerateJsonResult(
  1005. (int)$ctx['generate_task_id'],
  1006. (int)($ctx['script_id'] ?? 0),
  1007. (int)($ctx['uid'] ?? 0),
  1008. (string)$fullContent,
  1009. (string)($ctx['response_format'] ?? '')
  1010. );
  1011. }
  1012. }
  1013. } catch (\Throwable $e) {
  1014. if (!empty($ctx['generate_task_id'])) {
  1015. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  1016. 'status' => 'failed',
  1017. 'error_message' => $e->getMessage(),
  1018. 'completed_at' => date('Y-m-d H:i:s'),
  1019. 'updated_at' => date('Y-m-d H:i:s'),
  1020. ]);
  1021. }
  1022. yield [
  1023. 'type' => 'error',
  1024. 'message' => $e->getMessage(),
  1025. ];
  1026. }
  1027. }
  1028. /**
  1029. * 从模型输出中提取标准 JSON(剥离 markdown 代码块及前后说明文字)
  1030. *
  1031. * @param string $content
  1032. * @return string
  1033. */
  1034. private function extractJsonContent(string $content): string
  1035. {
  1036. $content = trim($content);
  1037. if ($content === '') {
  1038. return $content;
  1039. }
  1040. // 剥离 ```json ... ``` 代码块
  1041. if (preg_match('/```(?:json)?\s*(.*?)```/s', $content, $m)) {
  1042. $content = trim($m[1]);
  1043. }
  1044. // 提取第一个 { 到最后一个 } 之间的内容(去除前后说明文字)
  1045. $first = strpos($content, '{');
  1046. $last = strrpos($content, '}');
  1047. if ($first !== false && $last !== false && $last > $first) {
  1048. $content = substr($content, $first, $last - $first + 1);
  1049. }
  1050. // 校验是否为合法 JSON,非法则原样返回(不强行截断)
  1051. json_decode($content, true);
  1052. if (json_last_error() !== JSON_ERROR_NONE) {
  1053. return trim($content);
  1054. }
  1055. return $content;
  1056. }
  1057. /**
  1058. * 剧本资产生成结果的 JSON 安全校验/修复与观察
  1059. *
  1060. * 规则:
  1061. * - result 永远保留模型原文,本方法不修改 result;
  1062. * - 仅当原文非法 JSON 且 JsonSafeRepair 安全修复成功时,才把修复后的标准
  1063. * JSON 写入 mp_script_generate_tasks.json_result;
  1064. * - 每次生成结果都写一条 system_logs(channel=script_generate_json),
  1065. * 用于观察非法 JSON 的发生率与修复率。
  1066. *
  1067. * @param int $taskId 剧本资产生成任务 ID
  1068. * @param int $scriptId 剧本 ID
  1069. * @param int $uid 用户 ID
  1070. * @param string $raw 已落库的 result 原文
  1071. * @param string $responseFormat 请求的 response_format
  1072. * @return void
  1073. */
  1074. private function guardScriptGenerateJsonResult(int $taskId, int $scriptId, int $uid, string $raw, string $responseFormat): void
  1075. {
  1076. if ($taskId <= 0 || $raw === '') {
  1077. return;
  1078. }
  1079. // 仅对"要求 JSON 输出"或"内容明显是 JSON"的结果做校验,避免误伤普通文本结果
  1080. $trimmed = ltrim($raw);
  1081. $looksLikeJson = $responseFormat === 'json'
  1082. || (isset($trimmed[0]) && ($trimmed[0] === '{' || $trimmed[0] === '['));
  1083. if (!$looksLikeJson) {
  1084. return;
  1085. }
  1086. $repair = JsonSafeRepair::repair($raw);
  1087. $common = [
  1088. 'task_id' => $taskId,
  1089. 'script_id' => $scriptId,
  1090. 'uid' => $uid,
  1091. 'raw_length' => strlen($raw),
  1092. ];
  1093. if ($repair['ok'] && $repair['json'] !== $raw) {
  1094. // 原文非法但安全修复成功:修复版另存 json_result,result 仍保留原文
  1095. DB::table('mp_script_generate_tasks')->where('id', $taskId)->update([
  1096. 'json_result' => $repair['json'],
  1097. 'updated_at' => date('Y-m-d H:i:s'),
  1098. ]);
  1099. logDB('script_generate_json', 'warning', '生成JSON修复成功', $common + [
  1100. 'json_state' => 'repaired',
  1101. 'json_length' => strlen((string)$repair['json']),
  1102. 'removed_count' => count($repair['removed_positions']),
  1103. 'removed_positions' => $repair['removed_positions'],
  1104. ]);
  1105. return;
  1106. }
  1107. if ($repair['ok']) {
  1108. // 原文本身就是合法 JSON
  1109. logDB('script_generate_json', 'info', '生成JSON校验通过', $common + [
  1110. 'json_state' => 'valid',
  1111. ]);
  1112. return;
  1113. }
  1114. // 非法 JSON 且不在安全修复范围内:保留原文,只记录观察日志
  1115. logDB('script_generate_json', 'error', '生成JSON修复失败', $common + [
  1116. 'json_state' => 'repair_failed',
  1117. 'reason' => $repair['reason'],
  1118. ]);
  1119. }
  1120. /**
  1121. * 创建剧本资产生成异步任务(stream=1 + script_id 走异步任务模式)
  1122. *
  1123. * @param array $data 原请求参数
  1124. * @return int 任务ID
  1125. */
  1126. public function createScriptGenerateAsyncTask(array $data): int
  1127. {
  1128. $script_id = (int)getProp($data, 'script_id', 0);
  1129. if ($script_id <= 0) {
  1130. Utils::throwError('20003:缺少剧本ID');
  1131. }
  1132. $uid = (int)Site::getUid();
  1133. // 与同步逻辑一致:同一剧本存在生成中任务时直接拒绝
  1134. $runningTask = DB::table('mp_script_generate_tasks')
  1135. ->where('uid', $uid)
  1136. ->where('script_id', $script_id)
  1137. ->orderByDesc('id')
  1138. ->first();
  1139. if ($runningTask && in_array(getProp($runningTask, 'status'), ['pending', 'processing'])) {
  1140. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  1141. }
  1142. // 前置校验剧本存在且内容非空,避免创建无效任务
  1143. $script = DB::table('mp_scripts')
  1144. ->where('id', $script_id)
  1145. ->where('is_deleted', 0)
  1146. ->first();
  1147. if (!$script) {
  1148. Utils::throwError('20003:剧本不存在或已删除');
  1149. }
  1150. if (empty($script->content)) {
  1151. Utils::throwError('20003:剧本内容为空');
  1152. }
  1153. // newGenerateText 请求不含上传文件对象,images/image_urls 以字符串形式传入,可直接序列化
  1154. $paramsJson = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  1155. if ($paramsJson === false) {
  1156. Utils::throwError('20003:请求参数序列化失败');
  1157. }
  1158. $now = date('Y-m-d H:i:s');
  1159. return (int)DB::table('mp_script_generate_tasks')->insertGetId([
  1160. 'uid' => $uid,
  1161. 'script_id' => $script_id,
  1162. 'sequence' => (int)getProp($data, 'sequence', 0),
  1163. 'status' => 'pending',
  1164. 'prompt' => (string)getProp($data, 'prompt', ''),
  1165. 'request_params' => $paramsJson,
  1166. 'started_at' => $now,
  1167. 'created_at' => $now,
  1168. 'updated_at' => $now,
  1169. ]);
  1170. }
  1171. /**
  1172. * 供 SSE 轮询:查询任务状态与增量 chunks
  1173. *
  1174. * @param int $taskId
  1175. * @param int $uid 当前登录用户,防越权
  1176. * @param int $afterSeq 已推送的最大 seq
  1177. * @return array{found:bool, task:?object, chunks:array, status:?string, error_message:?string}
  1178. */
  1179. public function pollScriptGenerateTask(int $taskId, int $uid, int $afterSeq = -1): array
  1180. {
  1181. $task = DB::table('mp_script_generate_tasks')
  1182. ->where('id', $taskId)
  1183. ->where('uid', $uid)
  1184. ->first();
  1185. if (!$task) {
  1186. return ['found' => false, 'task' => null, 'chunks' => [], 'status' => null, 'error_message' => null];
  1187. }
  1188. $rows = DB::table('mp_script_generate_task_chunks')
  1189. ->where('task_id', $taskId)
  1190. ->where('seq', '>', $afterSeq)
  1191. ->orderBy('seq')
  1192. ->get();
  1193. $chunks = [];
  1194. foreach ($rows as $row) {
  1195. $payload = json_decode((string)$row->payload, true);
  1196. if (is_array($payload)) {
  1197. $chunks[] = $payload;
  1198. }
  1199. }
  1200. return [
  1201. 'found' => true,
  1202. 'task' => $task,
  1203. 'chunks' => $chunks,
  1204. 'status' => (string)$task->status,
  1205. 'error_message' => (string)($task->error_message ?? ''),
  1206. ];
  1207. }
  1208. /**
  1209. * 异步 worker 执行入口:抢占 pending 任务并流式请求大模型
  1210. *
  1211. * 由 text:generate:run 命令调用;worker 内完成 chunks 落库,模型结束后
  1212. * 由流式包装(wrapNewGenerateTextStream)完成 records/扣费/任务状态/json 修复收尾。
  1213. *
  1214. * @param int $taskId
  1215. * @return array{ok:bool, task_id:int, status:?string, seq:int, error:?string}
  1216. */
  1217. public function runScriptGenerateTaskAsync(int $taskId): array
  1218. {
  1219. // 原子抢占:只允许 pending -> processing,避免重复执行
  1220. $claimed = DB::table('mp_script_generate_tasks')
  1221. ->where('id', $taskId)
  1222. ->where('status', 'pending')
  1223. ->update([
  1224. 'status' => 'processing',
  1225. 'started_at' => date('Y-m-d H:i:s'),
  1226. 'updated_at' => date('Y-m-d H:i:s'),
  1227. ]);
  1228. if (!$claimed) {
  1229. return ['ok' => false, 'task_id' => $taskId, 'status' => null, 'seq' => 0, 'error' => '任务已被处理或状态异常'];
  1230. }
  1231. $task = DB::table('mp_script_generate_tasks')->where('id', $taskId)->first();
  1232. if (!$task) {
  1233. return ['ok' => false, 'task_id' => $taskId, 'status' => null, 'seq' => 0, 'error' => '任务不存在'];
  1234. }
  1235. $params = json_decode((string)getProp($task, 'request_params', ''), true);
  1236. if (!is_array($params)) {
  1237. DB::table('mp_script_generate_tasks')->where('id', $taskId)->update([
  1238. 'status' => 'failed',
  1239. 'error_message' => '任务请求参数缺失',
  1240. 'completed_at' => date('Y-m-d H:i:s'),
  1241. 'updated_at' => date('Y-m-d H:i:s'),
  1242. ]);
  1243. return ['ok' => false, 'task_id' => $taskId, 'status' => 'failed', 'seq' => 0, 'error' => '任务请求参数缺失'];
  1244. }
  1245. // 兼容旧参数未带 stream 的情况
  1246. $params['stream'] = 1;
  1247. $seq = 0;
  1248. try {
  1249. $generator = $this->newGenerateTextStream($params, $task);
  1250. foreach ($generator as $chunk) {
  1251. DB::table('mp_script_generate_task_chunks')->insert([
  1252. 'task_id' => $taskId,
  1253. 'seq' => $seq,
  1254. 'chunk_type' => (string)getProp($chunk, 'type', 'content'),
  1255. 'payload' => json_encode($chunk, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE),
  1256. 'created_at' => date('Y-m-d H:i:s'),
  1257. ]);
  1258. $seq++;
  1259. }
  1260. $finalStatus = (string)DB::table('mp_script_generate_tasks')->where('id', $taskId)->value('status');
  1261. return ['ok' => $finalStatus === 'success', 'task_id' => $taskId, 'status' => $finalStatus, 'seq' => $seq, 'error' => null];
  1262. } catch (\Throwable $e) {
  1263. // 兜底:正常流程中 wrap 会自行把任务置为 failed,这里防止未知异常导致任务卡死
  1264. DB::table('mp_script_generate_tasks')->where('id', $taskId)->update([
  1265. 'status' => 'failed',
  1266. 'error_message' => $e->getMessage(),
  1267. 'completed_at' => date('Y-m-d H:i:s'),
  1268. 'updated_at' => date('Y-m-d H:i:s'),
  1269. ]);
  1270. return ['ok' => false, 'task_id' => $taskId, 'status' => 'failed', 'seq' => $seq, 'error' => $e->getMessage()];
  1271. }
  1272. }
  1273. /**
  1274. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  1275. *
  1276. * @param array $data 请求参数
  1277. * @return array 返回结果数组
  1278. */
  1279. public function newGenerateText($data) {
  1280. // stream=1 时改为流式请求大模型(输出格式参考 generateText:yield type=content/reasoning/done)
  1281. if ((int)getProp($data, 'stream', 0) === 1) {
  1282. return $this->newGenerateTextStream($data);
  1283. }
  1284. // 获取请求参数
  1285. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  1286. $messages = getProp($data, 'messages', []);
  1287. $systemPrompt = getProp($data, 'system_prompt', '');
  1288. $prompt = getProp($data, 'prompt', '');
  1289. $images = getProp($data, 'images', []); // 支持多张图片
  1290. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  1291. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  1292. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  1293. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  1294. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  1295. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  1296. $generateTaskId = 0;
  1297. $uid = Site::getUid();
  1298. if ($script_id > 0) {
  1299. $existingTask = DB::table('mp_script_generate_tasks')
  1300. ->where('uid', $uid)
  1301. ->where('script_id', $script_id)
  1302. ->orderByDesc('id')
  1303. ->first();
  1304. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  1305. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  1306. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  1307. }
  1308. }
  1309. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  1310. $originalContent = '';
  1311. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  1312. $rawPrompt = $prompt; // 保存用户原始输入,供模板一致性判断
  1313. if ($script_id > 0) {
  1314. $script = DB::table('mp_scripts')
  1315. ->where('id', $script_id)
  1316. ->where('is_deleted', 0)
  1317. ->first();
  1318. if (!$script) {
  1319. Utils::throwError('20003:剧本不存在或已删除');
  1320. }
  1321. $originalContent = $script->content ?? '';
  1322. if (empty($originalContent)) {
  1323. Utils::throwError('20003:剧本内容为空');
  1324. }
  1325. $hasValidScript = true;
  1326. // 将剧本内容添加到提示词前面
  1327. if (!empty($originalContent)) {
  1328. if (!empty($prompt)) {
  1329. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  1330. } else {
  1331. $prompt = "原文内容:\n" . $originalContent;
  1332. }
  1333. }
  1334. }
  1335. // 新增: 如果提供了template_id,从数据库获取template_prompt
  1336. if ($templateId > 0) {
  1337. $template = DB::table('mp_prompt_templates')
  1338. ->where('id', $templateId)
  1339. ->where('is_deleted', 0)
  1340. ->first();
  1341. if (!$template) {
  1342. Utils::throwError('20003:模板不存在或已删除');
  1343. }
  1344. $templatePrompt = $template->template_prompt ?? '';
  1345. // 将模板提示词和用户输入的prompt组合
  1346. // 模板为准,用户输入作为补充要求
  1347. // 模板提示词与用户输入基本一致时只保留一个,避免重复提示词
  1348. // 剧本模式下当前 prompt 含原文内容需保留,其余情况以模板内容为准
  1349. if (!empty($templatePrompt)) {
  1350. $trimmedRawPrompt = trim((string)$rawPrompt);
  1351. if ($trimmedRawPrompt !== '' && mb_strtolower($trimmedRawPrompt) === mb_strtolower(trim($templatePrompt))) {
  1352. if (!$hasValidScript) {
  1353. $prompt = $templatePrompt;
  1354. }
  1355. } elseif (!empty($prompt)) {
  1356. $prompt = $templatePrompt . "\n\n" . $prompt;
  1357. } else {
  1358. $prompt = $templatePrompt;
  1359. }
  1360. }
  1361. }
  1362. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  1363. if (empty($messages)) {
  1364. $messages = [];
  1365. // 添加系统提示词
  1366. if (!empty($systemPrompt)) {
  1367. $messages[] = [
  1368. 'role' => 'system',
  1369. 'content' => $systemPrompt
  1370. ];
  1371. }
  1372. // 构建用户消息内容(支持文本+图片)
  1373. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1374. $userMessage = [
  1375. 'role' => 'user',
  1376. 'content' => []
  1377. ];
  1378. // 添加文本内容
  1379. if (!empty($prompt)) {
  1380. $userMessage['content'][] = [
  1381. 'type' => 'text',
  1382. 'text' => $prompt
  1383. ];
  1384. }
  1385. // 处理上传的图片文件
  1386. if (!empty($images)) {
  1387. if (!is_array($images)) {
  1388. $images = [$images];
  1389. }
  1390. foreach ($images as $image) {
  1391. $imageBase64 = $this->processImageToBase64($image);
  1392. if ($imageBase64) {
  1393. $userMessage['content'][] = [
  1394. 'type' => 'image_url',
  1395. 'image_url' => [
  1396. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  1397. ]
  1398. ];
  1399. }
  1400. }
  1401. }
  1402. // 处理图片URL
  1403. if (!empty($imageUrls)) {
  1404. if (!is_array($imageUrls)) {
  1405. $imageUrls = [$imageUrls];
  1406. }
  1407. foreach ($imageUrls as $url) {
  1408. if (!empty($url)) {
  1409. $userMessage['content'][] = [
  1410. 'type' => 'image_url',
  1411. 'image_url' => [
  1412. 'url' => $url
  1413. ]
  1414. ];
  1415. }
  1416. }
  1417. }
  1418. // 如果只有文本内容,简化为字符串格式
  1419. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  1420. $userMessage['content'] = $userMessage['content'][0]['text'];
  1421. }
  1422. $messages[] = $userMessage;
  1423. }
  1424. }
  1425. // 验证messages不为空
  1426. if (empty($messages)) {
  1427. Utils::throwError('20003:请提供有效的对话内容');
  1428. }
  1429. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1430. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1431. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1432. if ($model === 'deepseek-chat') {
  1433. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1434. $model = 'deepseek-v4-flash';
  1435. $thinkingMode = 'disabled';
  1436. } elseif ($model === 'deepseek-reasoner') {
  1437. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1438. $model = 'deepseek-v4-flash';
  1439. $thinkingMode = 'enabled';
  1440. }
  1441. // 构建请求参数(非流式)
  1442. $post_data = [
  1443. 'model' => $model,
  1444. 'messages' => $messages,
  1445. 'temperature' => getProp($data, 'temperature', 1),
  1446. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  1447. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  1448. 'thinking' => ['type' => $thinkingMode],
  1449. 'stream' => false // 非流式输出
  1450. ];
  1451. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1452. // 添加可选参数
  1453. if (isset($data['top_p'])) {
  1454. $post_data['top_p'] = $data['top_p'];
  1455. }
  1456. // 新增: 根据response_format设置响应格式
  1457. if ($responseFormat === 'json') {
  1458. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  1459. $hasJsonKeyword = false;
  1460. foreach ($post_data['messages'] as $message) {
  1461. if (isset($message['content'])) {
  1462. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  1463. if (stripos($content, 'json') !== false) {
  1464. $hasJsonKeyword = true;
  1465. break;
  1466. }
  1467. }
  1468. }
  1469. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  1470. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  1471. if (!$hasJsonKeyword) {
  1472. $lastMessageIndex = count($post_data['messages']) - 1;
  1473. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  1474. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  1475. // 如果content是字符串,直接追加
  1476. if (is_string($lastContent)) {
  1477. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  1478. }
  1479. // 如果content是数组(包含文本和图片),在文本部分追加
  1480. else if (is_array($lastContent)) {
  1481. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  1482. if ($contentPart['type'] === 'text') {
  1483. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  1484. break;
  1485. }
  1486. }
  1487. }
  1488. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  1489. }
  1490. }
  1491. // 设置response_format参数(所有支持的模型)
  1492. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1493. // DeepSeek模型
  1494. $post_data['response_format'] = ['type' => 'json_object'];
  1495. } else if (in_array($model, $this->gpt_text_models)) {
  1496. // GPT模型
  1497. $post_data['response_format'] = ['type' => 'json_object'];
  1498. } else if (in_array($model, $this->valid_text_models)) {
  1499. // 火山引擎模型
  1500. $post_data['response_format'] = ['type' => 'json_object'];
  1501. }
  1502. }
  1503. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  1504. if ($script_id > 0) {
  1505. $uid = Site::getUid();
  1506. // 创建新的生成任务
  1507. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  1508. 'uid' => $uid,
  1509. 'script_id' => $script_id,
  1510. 'sequence' => $sequence,
  1511. 'status' => 'processing',
  1512. 'prompt' => getProp($data, 'prompt', ''),
  1513. 'started_at' => date('Y-m-d H:i:s'),
  1514. 'created_at' => date('Y-m-d H:i:s'),
  1515. 'updated_at' => date('Y-m-d H:i:s')
  1516. ]);
  1517. }
  1518. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  1519. if ($hasValidScript) {
  1520. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  1521. }
  1522. // 统一分模型调用非流式实现
  1523. try {
  1524. $aiResult = null;
  1525. $result = $this->dispatchChatOnlyByModel($post_data);
  1526. dLog('deepseek')->info('newGenerateText模型调用完成', ['requested_model' => $model]);
  1527. $aiResult = [
  1528. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  1529. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  1530. 'usage' => $result['usage'] ?? [],
  1531. 'model' => $model,
  1532. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  1533. ];
  1534. } catch (\Exception $e) {
  1535. // 生成失败,更新任务状态
  1536. if ($generateTaskId) {
  1537. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1538. 'status' => 'failed',
  1539. 'error_message' => $e->getMessage(),
  1540. 'completed_at' => date('Y-m-d H:i:s'),
  1541. 'updated_at' => date('Y-m-d H:i:s')
  1542. ]);
  1543. }
  1544. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  1545. }
  1546. // 生成成功,更新任务状态
  1547. if ($generateTaskId && $aiResult) {
  1548. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1549. 'status' => 'success',
  1550. 'result' => getProp($aiResult, 'content', ''),
  1551. 'completed_at' => date('Y-m-d H:i:s'),
  1552. 'updated_at' => date('Y-m-d H:i:s')
  1553. ]);
  1554. $aiResult['generate_task_id'] = $generateTaskId;
  1555. // JSON 输出结果的安全校验/修复与观察(不改变 result)
  1556. $this->guardScriptGenerateJsonResult(
  1557. (int)$generateTaskId,
  1558. (int)$script_id,
  1559. (int)$uid,
  1560. (string)getProp($aiResult, 'content', ''),
  1561. (string)$responseFormat
  1562. );
  1563. }
  1564. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  1565. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  1566. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  1567. 'model' => $model,
  1568. 'script_id' => $script_id,
  1569. 'sequence' => $sequence,
  1570. 'source' => 'newGenerateText',
  1571. ]);
  1572. }
  1573. // 新增: 如果提供了script_id,保存对话记录
  1574. if ($script_id > 0 && $aiResult) {
  1575. try {
  1576. $uid = Site::getUid();
  1577. $now = now();
  1578. // 获取用户原始的prompt(不包含剧本内容)
  1579. $originalPrompt = getProp($data, 'prompt', '');
  1580. $recordsToInsert = [
  1581. [
  1582. 'uid' => $uid,
  1583. 'script_id' => $script_id,
  1584. 'sequence' => $sequence,
  1585. 'role' => 'user',
  1586. 'content' => $originalPrompt,
  1587. 'created_at' => $now,
  1588. 'updated_at' => $now,
  1589. ],
  1590. [
  1591. 'uid' => $uid,
  1592. 'script_id' => $script_id,
  1593. 'sequence' => $sequence,
  1594. 'role' => 'assistant',
  1595. 'content' => $aiResult['content'],
  1596. 'created_at' => $now,
  1597. 'updated_at' => $now,
  1598. ]
  1599. ];
  1600. DB::table('mp_script_records')->insert($recordsToInsert);
  1601. // 获取刚插入的记录ID(假设按插入顺序返回)
  1602. $insertedRecords = DB::table('mp_script_records')
  1603. ->where('uid', $uid)
  1604. ->where('script_id', $script_id)
  1605. ->where('sequence', $sequence)
  1606. ->orderBy('id', 'desc')
  1607. ->limit(2)
  1608. ->get()
  1609. ->map(function ($record) {
  1610. return [
  1611. 'rid' => $record->id,
  1612. 'script_id' => $record->script_id,
  1613. 'sequence' => $record->sequence,
  1614. 'role' => $record->role,
  1615. 'content' => $record->content,
  1616. 'created_at' => $record->created_at,
  1617. ];
  1618. })
  1619. ->reverse()
  1620. ->values()
  1621. ->toArray();
  1622. // 将记录信息添加到返回结果中
  1623. $aiResult['records'] = $insertedRecords;
  1624. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  1625. } catch (\Exception $e) {
  1626. // 记录错误但不影响主流程
  1627. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  1628. }
  1629. }
  1630. // 未提供 script_id 或保存失败时,也返回 records 数组(保持返回结构一致)
  1631. if (!isset($aiResult['records'])) {
  1632. $aiResult['records'] = [];
  1633. }
  1634. return $aiResult;
  1635. }
  1636. /**
  1637. * 通用 Gemini 文生文方法(支持流式和非流式)
  1638. *
  1639. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  1640. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  1641. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  1642. * system_prompt 系统提示词(可选)
  1643. * prompt 用户提示词(可选)
  1644. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  1645. * image_urls 图片/视频URL列表(可选,同上)
  1646. * temperature 温度(可选,默认 1)
  1647. * top_p 核采样(可选)
  1648. * max_tokens 最大输出 token(可选,默认 8192)
  1649. * response_format text/json(可选)
  1650. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  1651. * thinking_budget 思考预算(可选,默认 20)
  1652. * stream 是否流式(可选,默认 false)
  1653. *
  1654. * @param array $data 请求参数
  1655. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  1656. */
  1657. public function geminiGenerateText($data) {
  1658. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  1659. $isStream = (bool)getProp($data, 'stream', false);
  1660. if (!in_array($model, $this->gemini_text_models)) {
  1661. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  1662. }
  1663. $requestData = $this->buildGeminiRequestBody($data, $model);
  1664. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  1665. if ($isStream) {
  1666. // 流式返回生成器,成功后记录 token 使用明细(不扣积分)
  1667. return $this->wrapGenerateTextTokenRecord(
  1668. $this->geminiStreamResponse($requestData, $model),
  1669. $this->getCurrentUid(),
  1670. $model,
  1671. 'geminiGenerateText'
  1672. );
  1673. }
  1674. // 非流式:成功后记录 token 使用明细(不扣积分)
  1675. $result = $this->geminiChatOnly($requestData, $model);
  1676. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  1677. 'model' => $model,
  1678. 'source' => 'geminiGenerateText',
  1679. ], $model);
  1680. return $result;
  1681. }
  1682. /**
  1683. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  1684. */
  1685. private function geminiMediaMaxBytes() {
  1686. return 14 * 1024 * 1024;
  1687. }
  1688. /**
  1689. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  1690. */
  1691. private function buildGeminiRequestBody($data, $model) {
  1692. $messages = getProp($data, 'messages', []);
  1693. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  1694. if (empty($messages)) {
  1695. $systemPrompt = getProp($data, 'system_prompt', '');
  1696. $prompt = getProp($data, 'prompt', '');
  1697. $images = getProp($data, 'images', []);
  1698. $imageUrls = getProp($data, 'image_urls', []);
  1699. $messages = [];
  1700. if (!empty($systemPrompt)) {
  1701. $messages[] = [
  1702. 'role' => 'system',
  1703. 'content' => $systemPrompt
  1704. ];
  1705. }
  1706. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1707. $userMessage = ['role' => 'user', 'content' => []];
  1708. if (!empty($prompt)) {
  1709. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  1710. }
  1711. if (!empty($images)) {
  1712. if (!is_array($images)) {
  1713. $images = [$images];
  1714. }
  1715. foreach ($images as $image) {
  1716. $inlineData = $this->processMediaToInlineData($image);
  1717. if ($inlineData) {
  1718. $userMessage['content'][] = [
  1719. 'type' => 'image',
  1720. 'inline_data' => $inlineData
  1721. ];
  1722. }
  1723. }
  1724. }
  1725. if (!empty($imageUrls)) {
  1726. if (!is_array($imageUrls)) {
  1727. $imageUrls = [$imageUrls];
  1728. }
  1729. foreach ($imageUrls as $url) {
  1730. if (!empty($url)) {
  1731. $inlineData = $this->processMediaToInlineData($url);
  1732. if ($inlineData) {
  1733. $userMessage['content'][] = [
  1734. 'type' => 'image',
  1735. 'inline_data' => $inlineData
  1736. ];
  1737. }
  1738. }
  1739. }
  1740. }
  1741. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  1742. $userMessage['content'] = $userMessage['content'][0]['text'];
  1743. }
  1744. $messages[] = $userMessage;
  1745. }
  1746. }
  1747. if (empty($messages)) {
  1748. Utils::throwError('20003:请提供有效的对话内容');
  1749. }
  1750. // 转换为 Gemini contents 格式
  1751. $systemInstruction = '';
  1752. $contents = [];
  1753. foreach ($messages as $message) {
  1754. $role = getProp($message, 'role', 'user');
  1755. $content = getProp($message, 'content', '');
  1756. if ($role === 'system') {
  1757. if (is_array($content)) {
  1758. $systemInstruction = $this->extractGeminiTextFromParts($content);
  1759. } else {
  1760. $systemInstruction = (string)$content;
  1761. }
  1762. continue;
  1763. }
  1764. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  1765. $parts = [];
  1766. if (is_array($content)) {
  1767. foreach ($content as $part) {
  1768. $partType = getProp($part, 'type', 'text');
  1769. if ($partType === 'text') {
  1770. $text = (string)getProp($part, 'text', '');
  1771. if ($text !== '') {
  1772. $parts[] = ['text' => $text];
  1773. }
  1774. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  1775. if (in_array($partType, ['image_url', 'video_url'])) {
  1776. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  1777. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  1778. } elseif (isset($part['inline_data'])) {
  1779. // 已处理过的 inline_data 直接使用
  1780. $parts[] = ['inline_data' => $part['inline_data']];
  1781. continue;
  1782. } else {
  1783. $url = '';
  1784. }
  1785. $inlineData = $this->processMediaToInlineData($url);
  1786. if ($inlineData) {
  1787. $parts[] = ['inline_data' => $inlineData];
  1788. }
  1789. }
  1790. }
  1791. } else {
  1792. $text = (string)$content;
  1793. if ($text !== '') {
  1794. $parts[] = ['text' => $text];
  1795. }
  1796. }
  1797. if (!empty($parts)) {
  1798. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  1799. }
  1800. }
  1801. if (empty($contents)) {
  1802. Utils::throwError('20003:请提供有效的对话内容');
  1803. }
  1804. // 构建生成配置
  1805. $generationConfig = [];
  1806. if (getProp($data, 'temperature', null) !== null) {
  1807. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  1808. }
  1809. if (getProp($data, 'top_p', null) !== null) {
  1810. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  1811. }
  1812. if (getProp($data, 'frequency_penalty', null) !== null) {
  1813. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  1814. }
  1815. if (getProp($data, 'presence_penalty', null) !== null) {
  1816. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  1817. }
  1818. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  1819. if ($maxOutputTokens <= 0) {
  1820. $maxOutputTokens = 8192;
  1821. }
  1822. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  1823. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  1824. $maxOutputTokens = 32768;
  1825. }
  1826. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  1827. // response_format 映射:text -> text/plain,json -> application/json
  1828. $responseFormat = getProp($data, 'response_format', 'text');
  1829. if (is_array($responseFormat)) {
  1830. $responseFormat = getProp($responseFormat, 'type', 'text');
  1831. }
  1832. if (in_array($responseFormat, ['json', 'json_object'])) {
  1833. $generationConfig['responseMimeType'] = 'application/json';
  1834. } else {
  1835. $generationConfig['responseMimeType'] = 'text/plain';
  1836. }
  1837. $requestData = [
  1838. 'contents' => $contents,
  1839. 'generationConfig' => $generationConfig,
  1840. ];
  1841. if ($systemInstruction !== '') {
  1842. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  1843. }
  1844. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  1845. $thinkingMode = getProp($data, 'thinking', null);
  1846. if (is_array($thinkingMode)) {
  1847. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  1848. }
  1849. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  1850. if ($thinkingMode === null) {
  1851. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  1852. }
  1853. if ($thinkingMode === 'enabled') {
  1854. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  1855. if ($thinkingBudget <= 0) {
  1856. $thinkingBudget = 20;
  1857. }
  1858. $requestData['generationConfig']['thinkingConfig'] = [
  1859. 'thinkingBudget' => $thinkingBudget
  1860. ];
  1861. } elseif ($defaultThinking) {
  1862. // 该模型仅支持思考模式,传 0 会返回 400
  1863. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  1864. } else {
  1865. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  1866. }
  1867. return $requestData;
  1868. }
  1869. /**
  1870. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  1871. *
  1872. * 模型名 -> env 变量名映射:
  1873. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  1874. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  1875. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  1876. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  1877. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  1878. */
  1879. private function getGeminiApiKey($model) {
  1880. $map = [
  1881. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  1882. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  1883. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  1884. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  1885. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  1886. ];
  1887. if (isset($map[$model])) {
  1888. $key = env($map[$model]);
  1889. if (!empty($key)) {
  1890. return $key;
  1891. }
  1892. }
  1893. return env('GEMINI_API_KEY', '');
  1894. }
  1895. /**
  1896. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  1897. */
  1898. private function geminiChatOnly($requestData, $model) {
  1899. $apiKey = $this->getGeminiApiKey($model);
  1900. if (empty($apiKey)) {
  1901. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1902. }
  1903. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1904. if (isset($requestData['messages'])) {
  1905. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1906. }
  1907. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1908. . '/models/' . $model . ':generateContent';
  1909. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1910. $headers = [
  1911. 'Authorization' => 'Bearer ' . $apiKey,
  1912. 'Content-Type' => 'application/json'
  1913. ];
  1914. $maxRetries = $this->gptRetryTimes();
  1915. $interval = $this->gptRetryInterval();
  1916. $attempt = 0;
  1917. while (true) {
  1918. try {
  1919. $response = $client->post($url, [
  1920. 'json' => $requestData,
  1921. 'headers' => $headers
  1922. ]);
  1923. $responseArr = json_decode($response->getBody()->getContents(), true);
  1924. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  1925. $fullContent = $this->extractGeminiContent($responseArr);
  1926. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  1927. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  1928. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  1929. ? $responseArr['candidates'][0]['finishReason']
  1930. : '';
  1931. return [
  1932. 'fullContent' => $fullContent,
  1933. 'fullReasoningContent' => $fullReasoningContent,
  1934. 'usage' => $usage,
  1935. 'finish_reason' => $finishReason
  1936. ];
  1937. } catch (\Exception $e) {
  1938. $retryable = true;
  1939. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1940. $status = $e->getResponse()->getStatusCode();
  1941. $retryable = $status >= 500 || $status == 429;
  1942. }
  1943. if (!$retryable || $attempt >= $maxRetries) {
  1944. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  1945. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  1946. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  1947. }
  1948. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  1949. 'retry' => $attempt + 1,
  1950. 'max_retries' => $maxRetries,
  1951. 'error' => $e->getMessage()
  1952. ]);
  1953. sleep($interval);
  1954. $attempt++;
  1955. }
  1956. }
  1957. }
  1958. /**
  1959. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  1960. */
  1961. private function geminiStreamResponse($requestData, $model) {
  1962. $apiKey = $this->getGeminiApiKey($model);
  1963. if (empty($apiKey)) {
  1964. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1965. }
  1966. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1967. if (isset($requestData['messages'])) {
  1968. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1969. }
  1970. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1971. . '/models/' . $model . ':generateContent?alt=sse';
  1972. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1973. $headers = [
  1974. 'Authorization' => 'Bearer ' . $apiKey,
  1975. 'Content-Type' => 'application/json'
  1976. ];
  1977. try {
  1978. $response = $client->post($url, [
  1979. 'json' => $requestData,
  1980. 'headers' => $headers,
  1981. 'stream' => true
  1982. ]);
  1983. $body = $response->getBody();
  1984. $fullContent = '';
  1985. $fullReasoningContent = '';
  1986. $usage = [];
  1987. $buffer = '';
  1988. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1989. while (!$body->eof()) {
  1990. $chunk = $body->read(1024);
  1991. $buffer .= $chunk;
  1992. $lines = explode("\n", $buffer);
  1993. $buffer = array_pop($lines);
  1994. foreach ($lines as $line) {
  1995. $line = trim($line);
  1996. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1997. continue;
  1998. }
  1999. $data = substr($line, 6);
  2000. if ($data === '[DONE]') {
  2001. break 2;
  2002. }
  2003. try {
  2004. $json = json_decode($data, true);
  2005. if (json_last_error() !== JSON_ERROR_NONE) {
  2006. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2007. continue;
  2008. }
  2009. // 思考内容(thoughts)
  2010. $thoughts = $this->extractGeminiThoughts($json);
  2011. if ($thoughts !== '') {
  2012. $fullReasoningContent .= $thoughts;
  2013. yield [
  2014. 'type' => 'reasoning',
  2015. 'content' => $thoughts,
  2016. 'full_reasoning' => $fullReasoningContent
  2017. ];
  2018. }
  2019. // 回答内容
  2020. $partText = $this->extractGeminiContent($json);
  2021. if ($partText !== '') {
  2022. $fullContent .= $partText;
  2023. yield [
  2024. 'type' => 'content',
  2025. 'content' => $partText,
  2026. ];
  2027. }
  2028. // 使用统计
  2029. if (isset($json['usageMetadata'])) {
  2030. $usage = $json['usageMetadata'];
  2031. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  2032. }
  2033. } catch (\Exception $e) {
  2034. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2035. continue;
  2036. }
  2037. }
  2038. }
  2039. dLog('deepseek')->info('Gemini流式读取完成', [
  2040. 'content_length' => strlen($fullContent),
  2041. 'reasoning_length' => strlen($fullReasoningContent)
  2042. ]);
  2043. yield [
  2044. 'type' => 'done',
  2045. 'full_content' => $fullContent,
  2046. 'full_reasoning' => $fullReasoningContent,
  2047. 'usage' => $usage
  2048. ];
  2049. } catch (\Exception $e) {
  2050. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  2051. yield [
  2052. 'type' => 'error',
  2053. 'msg' => $e->getMessage(),
  2054. 'code' => $e->getCode()
  2055. ];
  2056. }
  2057. }
  2058. /**
  2059. * 从 Gemini 响应中提取回答文本
  2060. */
  2061. private function extractGeminiContent($responseArr) {
  2062. $text = '';
  2063. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  2064. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  2065. if (isset($part['text'])) {
  2066. $text .= $part['text'];
  2067. }
  2068. }
  2069. }
  2070. return $text;
  2071. }
  2072. /**
  2073. * 从 Gemini 响应中提取思考内容
  2074. */
  2075. private function extractGeminiReasoningContent($responseArr) {
  2076. $reasoning = '';
  2077. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  2078. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  2079. if (isset($thought['text'])) {
  2080. $reasoning .= $thought['text'];
  2081. }
  2082. }
  2083. }
  2084. return $reasoning;
  2085. }
  2086. /**
  2087. * 从 Gemini 流式响应中提取本次增量思考内容
  2088. */
  2089. private function extractGeminiThoughts($responseArr) {
  2090. $thoughts = '';
  2091. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  2092. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  2093. if (isset($thought['text'])) {
  2094. $thoughts .= $thought['text'];
  2095. }
  2096. }
  2097. }
  2098. return $thoughts;
  2099. }
  2100. /**
  2101. * 提取消息数组中的纯文本
  2102. */
  2103. private function extractGeminiTextFromParts($parts) {
  2104. $text = '';
  2105. if (is_array($parts)) {
  2106. foreach ($parts as $part) {
  2107. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  2108. $text .= (string)getProp($part, 'text', '');
  2109. }
  2110. }
  2111. }
  2112. return $text;
  2113. }
  2114. /**
  2115. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  2116. *
  2117. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  2118. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  2119. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  2120. *
  2121. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  2122. * @return array|null ['mime_type' => string, 'data' => string]
  2123. */
  2124. private function processMediaToInlineData($media) {
  2125. if (empty($media)) {
  2126. return null;
  2127. }
  2128. $localPath = null;
  2129. $isTempFile = false;
  2130. try {
  2131. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  2132. if (is_string($media) && strpos($media, 'data:') === 0) {
  2133. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  2134. return [
  2135. 'mime_type' => $matches[1],
  2136. 'data' => $matches[2]
  2137. ];
  2138. }
  2139. return null;
  2140. }
  2141. // 2. 获取本地文件路径
  2142. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  2143. $localPath = $this->downloadMediaToTemp($media);
  2144. $isTempFile = true;
  2145. } elseif (is_string($media)) {
  2146. $localPath = $media;
  2147. } else {
  2148. // Laravel UploadedFile 对象
  2149. $localPath = $media->getRealPath();
  2150. }
  2151. if (!$localPath || !file_exists($localPath)) {
  2152. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  2153. return null;
  2154. }
  2155. $fileSize = filesize($localPath);
  2156. $maxBytes = $this->geminiMediaMaxBytes();
  2157. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  2158. $mimeType = $this->detectMediaMime($localPath);
  2159. $isVideo = strpos($mimeType, 'video/') === 0;
  2160. $needCompress = $fileSize > $maxBytes;
  2161. $duration = 0;
  2162. if ($isVideo) {
  2163. $duration = $this->getMediaDuration($localPath);
  2164. if ($duration > 300) {
  2165. $needCompress = true;
  2166. }
  2167. }
  2168. $finalPath = $localPath;
  2169. $compressedPath = null;
  2170. if ($needCompress && $this->ffmpegAvailable()) {
  2171. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  2172. if ($compressed && file_exists($compressed)) {
  2173. $compressedPath = $compressed;
  2174. if (filesize($compressed) < $fileSize || $isVideo) {
  2175. $finalPath = $compressed;
  2176. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  2177. } else {
  2178. @unlink($compressed);
  2179. $compressedPath = null;
  2180. }
  2181. }
  2182. }
  2183. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  2184. $finalSize = filesize($finalPath);
  2185. if ($finalSize > $maxBytes) {
  2186. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  2187. 'path' => $localPath,
  2188. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  2189. 'limit_mb' => 14
  2190. ]);
  2191. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  2192. }
  2193. // 兜底校验:视频时长超过5分钟且未能压缩成功
  2194. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  2195. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  2196. }
  2197. $data = base64_encode(file_get_contents($finalPath));
  2198. return [
  2199. 'mime_type' => $mimeType,
  2200. 'data' => $data
  2201. ];
  2202. } catch (\App\Exceptions\ApiException $e) {
  2203. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  2204. throw $e;
  2205. } catch (\Exception $e) {
  2206. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  2207. return null;
  2208. } finally {
  2209. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  2210. @unlink($compressedPath);
  2211. }
  2212. if ($isTempFile && $localPath && file_exists($localPath)) {
  2213. @unlink($localPath);
  2214. }
  2215. }
  2216. }
  2217. /**
  2218. * 下载远程多媒体到临时目录
  2219. *
  2220. * @return string|null 本地临时文件路径
  2221. */
  2222. private function downloadMediaToTemp($url) {
  2223. try {
  2224. $tempDir = storage_path('app/temp/gemini');
  2225. if (!is_dir($tempDir)) {
  2226. mkdir($tempDir, 0775, true);
  2227. }
  2228. $extension = 'tmp';
  2229. $pathInfo = parse_url($url, PHP_URL_PATH);
  2230. if ($pathInfo) {
  2231. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  2232. if ($ext && strlen($ext) <= 10) {
  2233. $extension = strtolower($ext);
  2234. }
  2235. }
  2236. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  2237. $client = new Client(['timeout' => 300, 'verify' => false]);
  2238. $response = $client->get($url, ['sink' => $tmpFile]);
  2239. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  2240. @unlink($tmpFile);
  2241. return null;
  2242. }
  2243. return $tmpFile;
  2244. } catch (\Exception $e) {
  2245. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  2246. return null;
  2247. }
  2248. }
  2249. /**
  2250. * 检测多媒体文件 MIME 类型
  2251. */
  2252. private function detectMediaMime($filePath) {
  2253. $imageInfo = @getimagesize($filePath);
  2254. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  2255. return $imageInfo['mime'];
  2256. }
  2257. // 视频按扩展名粗略判断
  2258. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  2259. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  2260. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  2261. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  2262. if (isset($videoExts[$ext])) {
  2263. return $videoExts[$ext];
  2264. }
  2265. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  2266. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  2267. if (isset($imageExts[$ext])) {
  2268. return $imageExts[$ext];
  2269. }
  2270. return 'application/octet-stream';
  2271. }
  2272. /**
  2273. * 获取多媒体时长(秒),非视频或失败返回 0
  2274. */
  2275. private function getMediaDuration($filePath) {
  2276. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  2277. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  2278. $output = trim((string)shell_exec($cmd));
  2279. $duration = (float)$output;
  2280. return $duration > 0 ? $duration : 0;
  2281. }
  2282. /**
  2283. * 检查 ffmpeg 是否可用
  2284. */
  2285. private function ffmpegAvailable() {
  2286. static $available = null;
  2287. if ($available !== null) {
  2288. return $available;
  2289. }
  2290. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2291. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  2292. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  2293. $available = false;
  2294. return $available;
  2295. }
  2296. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  2297. $output = shell_exec($cmd);
  2298. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  2299. return $available;
  2300. }
  2301. /**
  2302. * 使用 ffmpeg 压缩多媒体文件
  2303. *
  2304. * @param string $inputFile 输入文件路径
  2305. * @param bool $isVideo 是否为视频
  2306. * @param float $duration 视频时长(秒),非视频传 0
  2307. * @return string|null 压缩后的文件路径,失败返回 null
  2308. */
  2309. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  2310. try {
  2311. $tempDir = storage_path('app/temp/gemini');
  2312. if (!is_dir($tempDir)) {
  2313. mkdir($tempDir, 0775, true);
  2314. }
  2315. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2316. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  2317. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  2318. if ($isVideo) {
  2319. // 视频:时长超过5分钟则加速压缩到5分钟以内
  2320. $speedFactor = 1.0;
  2321. if ($duration > 300) {
  2322. $speedFactor = $duration / 300;
  2323. }
  2324. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  2325. $finalDuration = $duration / max(1.0, $speedFactor);
  2326. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  2327. $targetBitrate = max(300, min(6000, $targetBitrate));
  2328. $filters = [];
  2329. $filters[] = 'scale=min(1280,iw):-2';
  2330. $filters[] = 'fps=24';
  2331. if ($speedFactor > 1.0) {
  2332. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  2333. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  2334. $fullCount = (int)ceil($speedFactor / 2.0);
  2335. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2336. if ($lastTempo < 0.5) {
  2337. $fullCount++;
  2338. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2339. }
  2340. for ($i = 0; $i < $fullCount; $i++) {
  2341. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  2342. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  2343. }
  2344. }
  2345. $filterStr = implode(',', $filters);
  2346. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  2347. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  2348. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  2349. } else {
  2350. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  2351. $imageInfo = @getimagesize($inputFile);
  2352. $scaleW = 2048;
  2353. $scaleH = 2048;
  2354. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  2355. if ($imageInfo[0] >= $imageInfo[1]) {
  2356. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  2357. $scaleW = 2048;
  2358. } else {
  2359. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  2360. $scaleH = 2048;
  2361. }
  2362. }
  2363. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  2364. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  2365. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  2366. }
  2367. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  2368. $output = shell_exec($cmd);
  2369. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  2370. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  2371. 'input' => $inputFile,
  2372. 'output' => $output
  2373. ]);
  2374. @unlink($outputFile);
  2375. return null;
  2376. }
  2377. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  2378. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  2379. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  2380. ]);
  2381. return $outputFile;
  2382. } catch (\Exception $e) {
  2383. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  2384. return null;
  2385. }
  2386. }
  2387. /**
  2388. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  2389. *
  2390. * @param array $data
  2391. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  2392. */
  2393. public function getScriptGenerateTasks($data) {
  2394. $uid = Site::getUid();
  2395. return DB::table('mp_script_generate_tasks as t')
  2396. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  2397. ->where('t.uid', $uid)
  2398. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  2399. ->orderByDesc('t.id')
  2400. ->paginate(15);
  2401. }
  2402. public function saveScriptChatHistory($data) {
  2403. $uid = Site::getUid();
  2404. $rid = getProp($data, 'rid');
  2405. $script_id = getProp($data, 'script_id');
  2406. $sequence = getProp($data, 'sequence', 0);
  2407. $content = getProp($data, 'content');
  2408. if (!$rid) {
  2409. Utils::throwError('20003:请选择对话记录ID');
  2410. }
  2411. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  2412. if (!$record) {
  2413. Utils::throwError('20003:对话记录不存在');
  2414. }
  2415. if (!$script_id) {
  2416. Utils::throwError('20003:请选择剧本');
  2417. }
  2418. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  2419. if (!$script) {
  2420. Utils::throwError('20003:剧本不存在');
  2421. }
  2422. // 批量插入数据
  2423. return DB::table('mp_script_records')->where('id', $rid)->update([
  2424. 'content' => $content,
  2425. 'updated_at' => date('Y-m-d H:i:s')
  2426. ]);
  2427. }
  2428. /**
  2429. * 获取剧本的历史对话记录
  2430. *
  2431. * @param array $data 请求参数
  2432. * @return array 返回历史记录数组
  2433. */
  2434. public function getScriptChatHistory($data) {
  2435. $uid = Site::getUid();
  2436. $script_id = getProp($data, 'script_id');
  2437. $rid = getProp($data, 'rid');
  2438. $sequence = getProp($data, 'sequence', null);
  2439. if (!$script_id) {
  2440. Utils::throwError('20003:请提供剧本ID');
  2441. }
  2442. // 验证剧本是否存在
  2443. $script = DB::table('mp_scripts')
  2444. ->where('id', $script_id)
  2445. ->where('is_deleted', 0)
  2446. ->first();
  2447. if (!$script) {
  2448. Utils::throwError('20003:剧本不存在');
  2449. }
  2450. // 构建查询
  2451. $query = DB::table('mp_script_records')
  2452. ->where('script_id', $script_id);
  2453. // ->where('uid', $uid);
  2454. // 如果提供了 sequence,则过滤指定剧集
  2455. if ($sequence !== null) {
  2456. $query->where('sequence', $sequence);
  2457. }
  2458. // 记录ID筛选
  2459. if ($rid) {
  2460. $query->where('id', $rid);
  2461. }
  2462. // 查询记录并按 id 正序排序
  2463. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  2464. ->orderBy('created_at', 'asc')
  2465. ->orderBy('id', 'asc')
  2466. ->get()
  2467. ->map(function ($record) {
  2468. return [
  2469. 'rid' => $record->id,
  2470. 'script_id' => $record->script_id,
  2471. 'sequence' => $record->sequence,
  2472. 'role' => $record->role,
  2473. 'content' => $record->content,
  2474. 'products' => $record->products ? json_decode($record->products) : [],
  2475. 'created_at' => $record->created_at,
  2476. ];
  2477. })
  2478. ->toArray();
  2479. return $records;
  2480. }
  2481. /**
  2482. * 处理图片转换为base64
  2483. *
  2484. * @param mixed $image 图片文件对象或文件路径
  2485. * @return string|null base64编码的图片数据
  2486. */
  2487. private function processImageToBase64($image) {
  2488. try {
  2489. // 获取文件路径
  2490. if (is_string($image)) {
  2491. $filePath = $image;
  2492. } else {
  2493. // Laravel UploadedFile 对象
  2494. $filePath = $image->getRealPath();
  2495. }
  2496. if (!file_exists($filePath)) {
  2497. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  2498. return null;
  2499. }
  2500. // 验证是否为图片文件
  2501. $imageInfo = @getimagesize($filePath);
  2502. if ($imageInfo === false) {
  2503. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  2504. return null;
  2505. }
  2506. // 读取图片并转换为base64
  2507. $imageData = file_get_contents($filePath);
  2508. $base64Image = base64_encode($imageData);
  2509. dLog('deepseek')->info('图片转换成功', [
  2510. 'size' => strlen($imageData),
  2511. 'type' => $imageInfo['mime']
  2512. ]);
  2513. return $base64Image;
  2514. } catch (\Exception $e) {
  2515. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  2516. return null;
  2517. }
  2518. }
  2519. private function getArtStylePromptMappings($art_style='')
  2520. {
  2521. // 优先从画风表读取(入库后以表数据为准,保持原返回结构:['画风名' => ['aliases' => [...], 'prompt' => "..."]]
  2522. $dbRows = DB::table('mp_art_styles')
  2523. ->where('is_deleted', 0)
  2524. ->orderBy('id')
  2525. ->get(['art_style', 'aliases', 'prompt']);
  2526. if ($dbRows->isNotEmpty()) {
  2527. $arr = [];
  2528. foreach ($dbRows as $row) {
  2529. $arr[$row->art_style] = [
  2530. 'aliases' => is_string($row->aliases) ? json_decode($row->aliases, true) : [],
  2531. 'prompt' => (string)$row->prompt,
  2532. ];
  2533. }
  2534. if ($art_style) {
  2535. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2536. }
  2537. return $arr;
  2538. }
  2539. $arr = [
  2540. '唯美真人风格' => [
  2541. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2542. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  2543. ],
  2544. '真人古风风格' => [
  2545. 'aliases' => ['真人古风风格', '真人古风'],
  2546. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  2547. ],
  2548. '日系动漫风格' => [
  2549. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2550. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  2551. ],
  2552. '国漫风格' => [
  2553. 'aliases' => ['国漫风格', '国漫'],
  2554. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  2555. ],
  2556. 'Q版卡通风格' => [
  2557. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2558. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  2559. ],
  2560. '简约扁平风格' => [
  2561. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2562. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  2563. ],
  2564. '武侠风格' => [
  2565. 'aliases' => ['武侠风格', '武侠'],
  2566. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  2567. ],
  2568. '古风仙侠风格' => [
  2569. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2570. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  2571. ],
  2572. '新中式水墨风格' => [
  2573. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2574. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  2575. ],
  2576. '写实插画风格' => [
  2577. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2578. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  2579. ],
  2580. '3D卡通风格' => [
  2581. 'aliases' => ['3D卡通风格', '3D卡通'],
  2582. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  2583. ],
  2584. '条漫风格' => [
  2585. 'aliases' => ['条漫风格', '条漫'],
  2586. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  2587. ],
  2588. '赛博朋克风格' => [
  2589. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2590. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  2591. ],
  2592. '暗黑悬疑风格' => [
  2593. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2594. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  2595. ],
  2596. '治愈清新风格' => [
  2597. 'aliases' => ['治愈清新风格', '治愈清新'],
  2598. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  2599. ],
  2600. '3D真人风格' => [
  2601. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  2602. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  2603. ],
  2604. ];
  2605. if($art_style) {
  2606. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2607. }
  2608. return $arr;
  2609. $arr = [
  2610. '唯美真人风格' => [
  2611. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2612. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  2613. 2. 色彩色调
  2614. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  2615. 3. 画质精度
  2616. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  2617. 4. 画面观感
  2618. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  2619. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  2620. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  2621. ],
  2622. '真人古风风格' => [
  2623. 'aliases' => ['真人古风风格', '真人古风'],
  2624. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  2625. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  2626. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  2627. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  2628. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  2629. ],
  2630. '日系动漫风格' => [
  2631. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2632. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  2633. 正向提示词(中文)
  2634. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  2635. 必须遵守规则
  2636. • 全程保持日系动漫风格,不混入其他画风
  2637. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  2638. • 画面适配所选画面比例,构图居中,主体突出
  2639. • 线条干净、色彩统一,不杂乱、不突兀
  2640. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  2641. ],
  2642. '国漫风格' => [
  2643. 'aliases' => ['国漫风格', '国漫'],
  2644. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  2645. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  2646. 必须遵守规则
  2647. • 严格保持国漫画风,不串风格、不混画风
  2648. • 角色形象统一,不随意改变五官、身材、服饰
  2649. • 画面构图稳定,适合漫剧叙事展示
  2650. • 色调统一,不出现脏色、杂色
  2651. 禁止/避免词汇
  2652. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  2653. ],
  2654. 'Q版卡通风格' => [
  2655. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2656. 'prompt' => "风格说明
  2657. 头大身小,造型可爱圆润,简约干净
  2658. 正向提示词(中文)
  2659. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  2660. 必须遵守规则
  2661. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  2662. • 角色造型统一,表情可爱,不诡异
  2663. • 画面简洁清爽,无多余复杂元素
  2664. • 色彩明亮柔和,不刺眼
  2665. 禁止/避免词汇
  2666. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  2667. ],
  2668. '简约扁平风格' => [
  2669. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2670. 'prompt' => "风格说明
  2671. 色块简洁、无复杂渐变,现代极简风
  2672. 正向提示词(中文)
  2673. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  2674. 必须遵守规则
  2675. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  2676. • 构图简洁,主体突出,无多余装饰
  2677. • 色彩统一、干净,不杂乱
  2678. 禁止/避免词汇
  2679. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  2680. ],
  2681. '武侠风格' => [
  2682. 'aliases' => ['武侠风格', '武侠'],
  2683. 'prompt' => "风格说明
  2684. 江湖气息,线条硬朗,动作感强
  2685. 正向提示词(中文)
  2686. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  2687. 必须遵守规则
  2688. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  2689. • 角色形象、服饰、身材比例统一
  2690. • 画面动作自然,不扭曲、不畸形
  2691. 禁止/避免词汇
  2692. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  2693. ],
  2694. '古风仙侠风格' => [
  2695. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2696. 'prompt' => "风格说明
  2697. 飘逸汉服、云雾仙气、唯美空灵
  2698. 正向提示词(中文)
  2699. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  2700. 必须遵守规则
  2701. • 保持古风仙侠统一画风,不混入现代、科幻元素
  2702. • 角色服饰、发型、形象前后一致
  2703. • 场景仙气飘逸,色调清雅统一
  2704. • 画面唯美柔和,不阴暗、不诡异
  2705. 禁止/避免词汇
  2706. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  2707. ],
  2708. '新中式水墨风格' => [
  2709. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2710. 'prompt' => "风格说明
  2711. 淡墨渲染,毛笔笔触,留白意境
  2712. 正向提示词(中文)
  2713. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  2714. 必须遵守规则
  2715. • 严格保持水墨质感,不混入厚涂、写实、卡通
  2716. • 色调淡雅统一,不浓艳杂乱
  2717. • 画面干净有意境,不堆砌元素
  2718. 禁止/避免词汇
  2719. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  2720. ],
  2721. '写实插画风格' => [
  2722. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2723. 'prompt' => "风格说明
  2724. 接近真人比例,光影真实,质感细腻
  2725. 正向提示词(中文)
  2726. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  2727. 必须遵守规则
  2728. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  2729. • 角色五官、身材、服饰高度统一
  2730. • 画面清晰、光影自然、不扭曲
  2731. 禁止/避免词汇
  2732. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  2733. ],
  2734. '3D卡通风格' => [
  2735. 'aliases' => ['3D卡通风格', '3D卡通'],
  2736. 'prompt' => "风格说明
  2737. 3D建模质感,柔和渲染,圆润可爱
  2738. 正向提示词(中文)
  2739. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  2740. 必须遵守规则
  2741. • 保持3D卡通统一质感,不出现2D杂乱线条
  2742. • 角色模型、比例、形象前后一致
  2743. • 画面干净,不模糊、不穿模
  2744. 禁止/避免词汇
  2745. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  2746. ],
  2747. '条漫风格' => [
  2748. 'aliases' => ['条漫风格', '条漫'],
  2749. 'prompt' => "风格说明
  2750. 纵向分镜,上下滑动阅读,轻量化
  2751. 正向提示词(中文)
  2752. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  2753. 必须遵守规则
  2754. • 保持条漫纵向阅读逻辑,构图简洁
  2755. • 画风统一,不混写实、3D、水墨
  2756. • 画面干净,不杂乱
  2757. 禁止/避免词汇
  2758. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  2759. ],
  2760. '赛博朋克风格' => [
  2761. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2762. 'prompt' => "风格说明
  2763. 霓虹灯光、未来都市、暗色调、科技机械
  2764. 正向提示词(中文)
  2765. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  2766. 必须遵守规则
  2767. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  2768. • 色调以暗调+霓虹为主,色彩统一
  2769. • 画面科技感强,不杂乱
  2770. 禁止/避免词汇
  2771. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  2772. ],
  2773. '暗黑悬疑风格' => [
  2774. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2775. 'prompt' => "风格说明
  2776. 低饱和、冷色调、阴影重、神秘压抑
  2777. 正向提示词(中文)
  2778. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  2779. 必须遵守规则
  2780. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  2781. • 画面氛围压抑神秘,但不低俗、不血腥
  2782. • 角色形象统一,不崩坏
  2783. 禁止/避免词汇
  2784. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  2785. ],
  2786. '治愈清新风格' => [
  2787. 'aliases' => ['治愈清新风格', '治愈清新'],
  2788. 'prompt' => "风格说明
  2789. 马卡龙色系、柔光、温暖干净
  2790. 正向提示词(中文)
  2791. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  2792. 必须遵守规则
  2793. • 保持治愈清新统一色调,不阴暗、不诡异
  2794. • 画面柔和干净,无杂乱元素
  2795. • 角色形象柔和可爱,不狰狞
  2796. 禁止/避免词汇
  2797. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  2798. ],
  2799. ];
  2800. return $arr;
  2801. }
  2802. public function getArtStylePromptByInput($inputArtStyle): string
  2803. {
  2804. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  2805. if ($normalizedInput === '') {
  2806. return '';
  2807. }
  2808. // 按归一化画风名匹配(去除中英文空格等差异),表数据与内置映射通用
  2809. $mappings = $this->getArtStylePromptMappings();
  2810. if (!is_array($mappings)) {
  2811. return '';
  2812. }
  2813. foreach ($mappings as $artStyleName => $mapping) {
  2814. if ($this->normalizeArtStyleInput($artStyleName) === $normalizedInput) {
  2815. return (string)getProp($mapping, 'prompt', '');
  2816. }
  2817. }
  2818. return '';
  2819. }
  2820. public function getArtStyleShortPromptByInput($inputArtStyle) {
  2821. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  2822. if ($normalizedInput === '') {
  2823. return [];
  2824. }
  2825. // 优先从画风表读取(按归一化画风名匹配,停用画风保持可用);
  2826. // character_prefix/scene_prefix 缺失时用通用 prompt 兜底,均缺失则返回空数组
  2827. $row = null;
  2828. $dbRows = DB::table('mp_art_styles')
  2829. ->where('is_deleted', 0)
  2830. ->get(['art_style', 'character_prefix', 'scene_prefix', 'prompt']);
  2831. foreach ($dbRows as $dbRow) {
  2832. if ($this->normalizeArtStyleInput($dbRow->art_style) === $normalizedInput) {
  2833. $row = $dbRow;
  2834. break;
  2835. }
  2836. }
  2837. if ($row) {
  2838. $prompt = (string)$row->prompt;
  2839. $result = [
  2840. 'character_prefix' => (string)$row->character_prefix !== '' ? (string)$row->character_prefix : $prompt,
  2841. 'scene_prefix' => (string)$row->scene_prefix !== '' ? (string)$row->scene_prefix : $prompt,
  2842. ];
  2843. // 前缀与通用提示词均不存在时返回空数组
  2844. if ($result['character_prefix'] === '' && $result['scene_prefix'] === '') {
  2845. return [];
  2846. }
  2847. return $result;
  2848. }
  2849. $stylePrefixes = [
  2850. '唯美真人风格' => [
  2851. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  2852. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强',
  2853. 'prompt' => '唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质'
  2854. ],
  2855. '真人古风风格' => [
  2856. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  2857. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清',
  2858. 'prompt' => '真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清'
  2859. ],
  2860. '日系动漫风格' => [
  2861. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  2862. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强',
  2863. 'prompt' => '日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影'
  2864. ],
  2865. '国漫风格' => [
  2866. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  2867. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染',
  2868. 'prompt' => '国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节'
  2869. ],
  2870. 'Q版卡通风格' => [
  2871. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  2872. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感',
  2873. 'prompt' => 'Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画'
  2874. ],
  2875. '简约扁平风格' => [
  2876. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  2877. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽',
  2878. 'prompt' => '简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽'
  2879. ],
  2880. '武侠风格' => [
  2881. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  2882. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学',
  2883. 'prompt' => '武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制'
  2884. ],
  2885. '古风仙侠风格' => [
  2886. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  2887. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学',
  2888. 'prompt' => '古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面'
  2889. ],
  2890. '新中式水墨风格' => [
  2891. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  2892. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景',
  2893. 'prompt' => '新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感'
  2894. ],
  2895. '写实插画风格' => [
  2896. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  2897. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图',
  2898. 'prompt' => '写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染'
  2899. ],
  2900. '3D卡通风格' => [
  2901. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  2902. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染',
  2903. 'prompt' => '3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富'
  2904. ],
  2905. '条漫风格' => [
  2906. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  2907. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感',
  2908. 'prompt' => '条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制'
  2909. ],
  2910. '赛博朋克风格' => [
  2911. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  2912. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影',
  2913. 'prompt' => '赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染'
  2914. ],
  2915. '暗黑悬疑风格' => [
  2916. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  2917. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图',
  2918. 'prompt' => '暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现'
  2919. ],
  2920. '治愈清新风格' => [
  2921. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  2922. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强',
  2923. 'prompt' => '治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足'
  2924. ]
  2925. ];
  2926. // 内置映射同样按归一化画风名匹配
  2927. foreach ($stylePrefixes as $artStyleName => $item) {
  2928. if ($this->normalizeArtStyleInput($artStyleName) !== $normalizedInput) {
  2929. continue;
  2930. }
  2931. $prompt = (string)($item['prompt'] ?? '');
  2932. // 前缀缺失时用通用 prompt 兜底
  2933. $result = [
  2934. 'character_prefix' => !empty($item['character_prefix']) ? $item['character_prefix'] : $prompt,
  2935. 'scene_prefix' => !empty($item['scene_prefix']) ? $item['scene_prefix'] : $prompt,
  2936. ];
  2937. // 与表分支一致:前缀与通用提示词均不存在时返回空数组
  2938. if ($result['character_prefix'] === '' && $result['scene_prefix'] === '') {
  2939. return [];
  2940. }
  2941. return $result;
  2942. }
  2943. return [];
  2944. }
  2945. private function normalizeArtStyleInput($value): string
  2946. {
  2947. $value = trim((string)$value);
  2948. if ($value === '') {
  2949. return '';
  2950. }
  2951. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  2952. return mb_strtolower($value, 'UTF-8');
  2953. }
  2954. private function replaceArtStyleSection(string $content, string $artStyle): string
  2955. {
  2956. if ($content === '' || $artStyle === '') {
  2957. return $content;
  2958. }
  2959. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  2960. if (!preg_match($pattern, $content)) {
  2961. return $content;
  2962. }
  2963. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  2964. }
  2965. /**
  2966. * 解开模型偶发返回的 JSON 包装内容
  2967. *
  2968. * @param mixed $content 模型返回的原始内容
  2969. * @return mixed 解开后的内容(若无法解开则原样返回)
  2970. */
  2971. private function unwrapJsonWrappedContent($content) {
  2972. $trimmed = ltrim((string)$content);
  2973. if ($trimmed === '' || ($trimmed[0] !== '{' && $trimmed[0] !== '[')) {
  2974. return $content;
  2975. }
  2976. $decoded = json_decode($trimmed, true);
  2977. if (!is_array($decoded)) {
  2978. return $content;
  2979. }
  2980. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2981. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2982. return $decoded[$key];
  2983. }
  2984. }
  2985. return $content;
  2986. }
  2987. /**
  2988. * 流式文生文统一分发:根据模型路由到对应提供商的流式实现
  2989. *
  2990. * @param array $post_data 请求参数(含 model / messages / stream 等)
  2991. * @return \Generator
  2992. */
  2993. public function dispatchStreamByModel($post_data) {
  2994. // 强制按流式模式分发
  2995. $post_data['stream'] = true;
  2996. $model = (string)getProp($post_data, 'model', '');
  2997. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2998. // DeepSeek 官方模型
  2999. return $this->deepSeekStreamResponse($post_data);
  3000. } else if (in_array($model, $this->gpt_text_models)) {
  3001. // GPT 模型
  3002. return $this->gpt54StreamResponse($post_data);
  3003. } else if (in_array($model, $this->gemini_text_models)) {
  3004. // Gemini 模型
  3005. return $this->geminiStreamResponse($post_data, $model);
  3006. } else if (in_array($model, $this->baidu_glm_text_models)) {
  3007. // 百度 AI 网关 GLM 模型
  3008. return $this->baiduGLMStreamResponse($post_data);
  3009. } else if (in_array($model, $this->valid_text_models)) {
  3010. // 火山引擎等其他模型
  3011. return $this->volcEngineChatCompletion($post_data);
  3012. }
  3013. Utils::throwError('20003:不支持的模型: ' . $model);
  3014. }
  3015. /**
  3016. * 非流式文生文统一分发:根据模型路由到对应提供商的非流式实现
  3017. *
  3018. * @param array $post_data 请求参数(含 model / messages / stream 等)
  3019. * @return array
  3020. */
  3021. public function dispatchChatOnlyByModel($post_data) {
  3022. // 强制按非流式模式分发
  3023. $post_data['stream'] = false;
  3024. $model = (string)getProp($post_data, 'model', '');
  3025. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3026. // DeepSeek 官方模型
  3027. return $this->chatOnly($post_data);
  3028. } else if (in_array($model, $this->gpt_text_models)) {
  3029. // GPT 模型
  3030. return $this->gpt54ChatOnly($post_data);
  3031. } else if (in_array($model, $this->gemini_text_models)) {
  3032. // Gemini 模型
  3033. return $this->geminiChatOnly($post_data, $model);
  3034. } else if (in_array($model, $this->baidu_glm_text_models)) {
  3035. // 百度 AI 网关 GLM 模型
  3036. return $this->baiduGLMChatOnly($post_data);
  3037. } else if (in_array($model, $this->valid_text_models)) {
  3038. // 火山引擎等其他模型
  3039. return $this->volcEngineChatCompletion($post_data);
  3040. }
  3041. Utils::throwError('20003:不支持的模型: ' . $model);
  3042. }
  3043. /**
  3044. * 百度 AI 网关 GLM 流式实现(OpenAI Chat Completions 协议)
  3045. *
  3046. * @param array $post_data 请求参数(前端模型名 baidu-glm-5.2 / baidu-glm-5.3)
  3047. * @return \Generator
  3048. */
  3049. private function baiduGLMStreamResponse($post_data) {
  3050. $payload = $this->buildBaiduGLMPayload($post_data, true);
  3051. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3052. try {
  3053. $response = $client->post('https://ai-gateway.baidubce.com/v1/chat/completions', [
  3054. 'json' => $payload,
  3055. 'headers' => $this->baiduGLMHeaders(),
  3056. 'stream' => true,
  3057. ]);
  3058. } catch (\Exception $e) {
  3059. $errorDetail = $this->extractBaiduGLMErrorDetail($e);
  3060. dLog('deepseek')->error('百度GLM流式请求建立失败: ' . $e->getMessage(), [
  3061. 'payload' => $payload,
  3062. 'detail' => $errorDetail,
  3063. ]);
  3064. Utils::throwError('20003:百度GLM流式请求失败: ' . $errorDetail);
  3065. }
  3066. $body = $response->getBody();
  3067. $buffer = '';
  3068. $fullContent = '';
  3069. $fullReasoning = '';
  3070. $usage = [];
  3071. dLog('deepseek')->info('开始读取百度GLM流式响应');
  3072. try {
  3073. while (!$body->eof()) {
  3074. $chunk = $body->read(1024);
  3075. $buffer .= $chunk;
  3076. $lines = explode("\n", $buffer);
  3077. $buffer = array_pop($lines);
  3078. foreach ($lines as $line) {
  3079. $line = trim($line);
  3080. if (empty($line)) {
  3081. continue;
  3082. }
  3083. if (strpos($line, 'data: ') !== 0) {
  3084. dLog('deepseek')->warning('百度GLM非SSE数据行', ['line' => $line]);
  3085. continue;
  3086. }
  3087. $data = substr($line, 6);
  3088. if ($data === '[DONE]') {
  3089. dLog('deepseek')->info('百度GLM收到结束标记');
  3090. break 2;
  3091. }
  3092. try {
  3093. $json = json_decode($data, true);
  3094. if (json_last_error() !== JSON_ERROR_NONE) {
  3095. dLog('deepseek')->warning('百度GLM JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3096. continue;
  3097. }
  3098. if (isset($json['choices'][0]['delta'])) {
  3099. $delta = $json['choices'][0]['delta'];
  3100. // 思考链内容(兼容 reasoning_content / reasoning 两种字段)
  3101. $reasoningDelta = '';
  3102. if (isset($delta['reasoning_content']) && is_string($delta['reasoning_content'])) {
  3103. $reasoningDelta = $delta['reasoning_content'];
  3104. } elseif (isset($delta['reasoning']) && is_string($delta['reasoning'])) {
  3105. $reasoningDelta = $delta['reasoning'];
  3106. }
  3107. if ($reasoningDelta !== '') {
  3108. $fullReasoning .= $reasoningDelta;
  3109. yield [
  3110. 'type' => 'reasoning',
  3111. 'content' => $reasoningDelta,
  3112. 'full_reasoning' => $fullReasoning,
  3113. ];
  3114. }
  3115. // 正文内容
  3116. if (isset($delta['content']) && is_string($delta['content'])) {
  3117. $fullContent .= $delta['content'];
  3118. yield [
  3119. 'type' => 'content',
  3120. 'content' => $delta['content'],
  3121. ];
  3122. }
  3123. }
  3124. if (isset($json['usage'])) {
  3125. $usage = $json['usage'];
  3126. }
  3127. } catch (\Exception $e) {
  3128. dLog('deepseek')->error('百度GLM解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3129. continue;
  3130. }
  3131. }
  3132. }
  3133. } catch (\Exception $e) {
  3134. dLog('deepseek')->error('百度GLM流式读取中断: ' . $e->getMessage());
  3135. throw $e;
  3136. }
  3137. dLog('deepseek')->info('百度GLM流式读取完成', [
  3138. 'content_length' => strlen($fullContent),
  3139. 'reasoning_length' => strlen($fullReasoning),
  3140. ]);
  3141. yield [
  3142. 'type' => 'done',
  3143. 'full_content' => $fullContent,
  3144. 'full_reasoning' => $fullReasoning,
  3145. 'usage' => $usage,
  3146. ];
  3147. }
  3148. /**
  3149. * 百度 AI 网关 GLM 非流式实现(OpenAI Chat Completions 协议)
  3150. *
  3151. * @param array $post_data 请求参数(前端模型名 baidu-glm-5.2 / baidu-glm-5.3)
  3152. * @return array
  3153. */
  3154. private function baiduGLMChatOnly($post_data) {
  3155. $payload = $this->buildBaiduGLMPayload($post_data, false);
  3156. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3157. try {
  3158. $result = $client->post('https://ai-gateway.baidubce.com/v1/chat/completions', [
  3159. 'json' => $payload,
  3160. 'headers' => $this->baiduGLMHeaders(),
  3161. ]);
  3162. $response_arr = json_decode($result->getBody()->getContents(), true);
  3163. dLog('deepseek')->info('百度GLM非流式请求完成', ['response' => $response_arr]);
  3164. $fullContent = '';
  3165. $fullReasoningContent = '';
  3166. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  3167. if (isset($response_arr['choices'][0]['message'])) {
  3168. $message = $response_arr['choices'][0]['message'];
  3169. if (isset($message['content']) && is_string($message['content'])) {
  3170. $fullContent = $message['content'];
  3171. }
  3172. if (isset($message['reasoning_content']) && is_string($message['reasoning_content'])) {
  3173. $fullReasoningContent = $message['reasoning_content'];
  3174. } elseif (isset($message['reasoning']) && is_string($message['reasoning'])) {
  3175. $fullReasoningContent = $message['reasoning'];
  3176. }
  3177. }
  3178. return [
  3179. 'fullContent' => $fullContent,
  3180. 'fullReasoningContent' => $fullReasoningContent,
  3181. 'usage' => $usage,
  3182. ];
  3183. } catch (\Exception $e) {
  3184. $errorDetail = $this->extractBaiduGLMErrorDetail($e);
  3185. dLog('deepseek')->error('百度GLM非流式请求失败: ' . $e->getMessage(), [
  3186. 'payload' => $payload,
  3187. 'detail' => $errorDetail,
  3188. ]);
  3189. Utils::throwError('20003:百度GLM请求失败: ' . $errorDetail);
  3190. }
  3191. }
  3192. /**
  3193. * 组装百度 AI 网关 GLM 请求参数
  3194. *
  3195. * @param array $data 请求参数
  3196. * @param bool $stream 是否流式
  3197. * @return array
  3198. */
  3199. private function buildBaiduGLMPayload(array $data, bool $stream): array
  3200. {
  3201. if (empty(env('BAIDU_GLM_AK'))) {
  3202. Utils::throwError('20003:百度GLM API Key未配置,请检查环境变量BAIDU_GLM_AK');
  3203. }
  3204. $frontModel = (string)getProp($data, 'model', '');
  3205. $externalModel = isset(BaseConst::BAIDU_GLM_MODEL_MAP[$frontModel])
  3206. ? BaseConst::BAIDU_GLM_MODEL_MAP[$frontModel]
  3207. : '';
  3208. if ($externalModel === '') {
  3209. Utils::throwError('20003:不支持的百度GLM模型: ' . $frontModel);
  3210. }
  3211. $messages = getProp($data, 'messages', []);
  3212. if (empty($messages)) {
  3213. Utils::throwError('20003:请提供有效的对话内容');
  3214. }
  3215. // OpenAI Chat Completions 标准参数白名单。
  3216. // 注意:thinking 不在白名单中,由下方按模型单独控制
  3217. // (glm-5.2 支持关闭思考,glm-5.3 强制思考、不接受 thinking 参数)。
  3218. $allowedKeys = [
  3219. 'temperature',
  3220. 'top_p',
  3221. 'max_tokens',
  3222. 'max_completion_tokens',
  3223. 'reasoning_effort',
  3224. 'frequency_penalty',
  3225. 'presence_penalty',
  3226. 'stop',
  3227. 'response_format',
  3228. 'stream_options',
  3229. 'tools',
  3230. 'tool_choice',
  3231. 'user',
  3232. 'seed',
  3233. ];
  3234. $payload = [
  3235. 'model' => $externalModel,
  3236. 'messages' => $messages,
  3237. 'stream' => $stream,
  3238. ];
  3239. foreach ($allowedKeys as $key) {
  3240. if (array_key_exists($key, $data) && $data[$key] !== null && $data[$key] !== '') {
  3241. $payload[$key] = $data[$key];
  3242. }
  3243. }
  3244. // ================= 思考模式策略(仅百度 GLM)=================
  3245. // 规则:调用方传了的参数以其为准,未传则按模型默认策略补齐。
  3246. // glm-5.2:支持关闭思考,默认关闭(thinking.disabled),可显著缩短响应时间
  3247. // glm-5.3:强制思考,网关不接受 thinking 参数(传 disabled 会返回 400),
  3248. // 因此统一不下发 thinking,只下发 reasoning_effort,默认 low
  3249. $validEfforts = ['low', 'high', 'max'];
  3250. // 调用方传入的 thinking(兼容 'enabled' 字符串与 ['type' => 'enabled'] 数组两种写法)
  3251. $inputThinking = null;
  3252. if (array_key_exists('thinking', $data)) {
  3253. $rawThinking = $data['thinking'];
  3254. if (is_array($rawThinking)) {
  3255. $rawThinking = getProp($rawThinking, 'type', null);
  3256. }
  3257. if (in_array($rawThinking, ['enabled', 'disabled'], true)) {
  3258. $inputThinking = $rawThinking;
  3259. }
  3260. }
  3261. // 调用方传入的思考强度;百度网关只接受 low / high / max,其它取值(如 none)视为未传
  3262. $inputEffort = null;
  3263. if (isset($payload['reasoning_effort']) && in_array($payload['reasoning_effort'], $validEfforts, true)) {
  3264. $inputEffort = $payload['reasoning_effort'];
  3265. }
  3266. unset($payload['reasoning_effort']);
  3267. if ($externalModel === 'glm-5.3') {
  3268. // glm-5.3 始终思考:即使传入 disabled(或未传)也强制走 reasoning_effort
  3269. $payload['reasoning_effort'] = $inputEffort ?: 'high';
  3270. } else {
  3271. // glm-5.2 支持关闭思考:未显式开启思考时默认关闭
  3272. $thinkingType = ($inputThinking === 'enabled') ? 'enabled' : 'disabled';
  3273. $payload['thinking'] = ['type' => $thinkingType];
  3274. if ($thinkingType === 'enabled') {
  3275. $payload['reasoning_effort'] = $inputEffort ?: 'high';
  3276. }
  3277. }
  3278. if ($stream && !isset($payload['stream_options'])) {
  3279. $payload['stream_options'] = ['include_usage' => true];
  3280. }
  3281. if (!isset($payload['max_tokens']) && !isset($payload['max_completion_tokens'])) {
  3282. // GLM-5.x 输出上限较高,给长文生成留足空间
  3283. $payload['max_tokens'] = 100000;
  3284. }
  3285. return $payload;
  3286. }
  3287. /**
  3288. * 百度 AI 网关 GLM 鉴权请求头
  3289. *
  3290. * @return array
  3291. */
  3292. private function baiduGLMHeaders(): array
  3293. {
  3294. return [
  3295. 'Authorization' => 'Bearer ' . env('BAIDU_GLM_AK'),
  3296. 'Content-Type' => 'application/json; charset=UTF-8',
  3297. 'Accept' => 'text/event-stream',
  3298. ];
  3299. }
  3300. /**
  3301. * 从 Guzzle 异常响应体中提取百度 AI 网关返回的错误信息
  3302. *
  3303. * @param \Exception $e
  3304. * @return string
  3305. */
  3306. private function extractBaiduGLMErrorDetail(\Exception $e): string
  3307. {
  3308. $detail = $e->getMessage();
  3309. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  3310. try {
  3311. $responseBody = (string)$e->getResponse()->getBody();
  3312. $decoded = json_decode($responseBody, true);
  3313. if (is_array($decoded)) {
  3314. if (isset($decoded['error']['message']) && $decoded['error']['message'] !== '') {
  3315. $detail = $decoded['error']['message'];
  3316. } elseif (isset($decoded['message']) && $decoded['message'] !== '') {
  3317. $detail = $decoded['message'];
  3318. } elseif (isset($decoded['error']) && is_string($decoded['error'])) {
  3319. $detail = $decoded['error'];
  3320. }
  3321. } elseif ($responseBody !== '') {
  3322. $detail = $responseBody;
  3323. }
  3324. } catch (\Throwable $parseError) {
  3325. // 保留原始异常信息
  3326. }
  3327. }
  3328. return mb_substr($detail, 0, 500);
  3329. }
  3330. private function deepSeekStreamResponse($post_data) {
  3331. // 设置最大输出tokens
  3332. $post_data['max_tokens'] = 300000;
  3333. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  3334. $post_data['stream_options'] = ['include_usage' => true];
  3335. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3336. $response = $client->post($this->url, [
  3337. 'json' => $post_data,
  3338. 'headers' => $this->headers,
  3339. 'stream' => true // 启用流式响应
  3340. ]);
  3341. $body = $response->getBody();
  3342. $fullContent = '';
  3343. $fullReasoningContent = '';
  3344. $usage = [];
  3345. $buffer = '';
  3346. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  3347. // 逐行读取流式响应
  3348. while (!$body->eof()) {
  3349. $chunk = $body->read(1024); // 每次读取 1KB
  3350. $buffer .= $chunk;
  3351. // 按行分割
  3352. $lines = explode("\n", $buffer);
  3353. // 保留最后一个不完整的行
  3354. $buffer = array_pop($lines);
  3355. foreach ($lines as $line) {
  3356. $line = trim($line);
  3357. // 跳过空行
  3358. if (empty($line)) {
  3359. continue;
  3360. }
  3361. // 检查是否是 SSE 数据行
  3362. if (strpos($line, 'data: ') !== 0) {
  3363. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  3364. continue;
  3365. }
  3366. $data = substr($line, 6); // 移除 "data: " 前缀
  3367. if ($data === '[DONE]') {
  3368. dLog('deepseek')->info('收到结束标记');
  3369. break 2; // 跳出两层循环
  3370. }
  3371. try {
  3372. $json = json_decode($data, true);
  3373. if (json_last_error() !== JSON_ERROR_NONE) {
  3374. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3375. continue;
  3376. }
  3377. if (isset($json['choices'][0]['delta'])) {
  3378. $delta = $json['choices'][0]['delta'];
  3379. // 处理思维链内容(仅 deepseek-reasoner 模型)
  3380. if (isset($delta['reasoning_content'])) {
  3381. $fullReasoningContent .= $delta['reasoning_content'];
  3382. yield [
  3383. 'type' => 'reasoning',
  3384. 'content' => $delta['reasoning_content'],
  3385. 'full_reasoning' => $fullReasoningContent
  3386. ];
  3387. }
  3388. // 处理最终回答内容
  3389. if (isset($delta['content'])) {
  3390. $fullContent .= $delta['content'];
  3391. yield [
  3392. 'type' => 'content',
  3393. 'content' => $delta['content'],
  3394. ];
  3395. }
  3396. }
  3397. // 获取使用统计信息
  3398. if (isset($json['usage'])) {
  3399. $usage = $json['usage'];
  3400. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  3401. }
  3402. } catch (\Exception $e) {
  3403. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3404. continue;
  3405. }
  3406. }
  3407. }
  3408. dLog('deepseek')->info('流式读取完成', [
  3409. 'content_length' => strlen($fullContent),
  3410. 'reasoning_length' => strlen($fullReasoningContent)
  3411. ]);
  3412. yield [
  3413. 'type' => 'done',
  3414. 'full_content' => $fullContent,
  3415. 'full_reasoning' => $fullReasoningContent,
  3416. 'usage' => $usage
  3417. ];
  3418. }
  3419. /**
  3420. * GPT 重试次数(env 可配置,默认 5 次)
  3421. */
  3422. private function gptRetryTimes()
  3423. {
  3424. return (int)env('GPT_RETRY_TIMES', 5);
  3425. }
  3426. /**
  3427. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  3428. */
  3429. private function gptRetryInterval()
  3430. {
  3431. return (int)env('GPT_RETRY_INTERVAL', 10);
  3432. }
  3433. /**
  3434. * 判断 GPT 请求异常是否可重试
  3435. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  3436. */
  3437. private function isGptRetryableException(\Exception $e)
  3438. {
  3439. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  3440. return false;
  3441. }
  3442. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  3443. $status = $e->getResponse()->getStatusCode();
  3444. return $status >= 500 || $status == 429;
  3445. }
  3446. return true;
  3447. }
  3448. /**
  3449. * 解析 GPT 上游错误详情:状态码、错误码(如 content_filter)、错误信息与响应体
  3450. * 流式响应的 body 不可 seek,Guzzle 自带的 body summary 取不到内容,这里手动读取并截断
  3451. */
  3452. private function resolveGptUpstreamError(\Exception $e)
  3453. {
  3454. // 同一个异常对象可能被内层与外层 catch 多次解析,而流式响应体只能读取一次,这里缓存解析结果
  3455. // 同时持有异常对象引用:spl_object_id 在对象回收后会被复用,仅凭 id 取值可能串到其他异常的数据
  3456. $cacheKey = spl_object_id($e);
  3457. if (isset($this->gpt_upstream_error_cache[$cacheKey]) && $this->gpt_upstream_error_cache[$cacheKey]['exception'] === $e) {
  3458. return $this->gpt_upstream_error_cache[$cacheKey]['detail'];
  3459. }
  3460. $detail = [
  3461. 'status' => 0,
  3462. 'code' => '',
  3463. 'message' => '',
  3464. 'body' => '',
  3465. ];
  3466. if (!($e instanceof \GuzzleHttp\Exception\BadResponseException) || !$e->getResponse()) {
  3467. $this->gpt_upstream_error_cache[$cacheKey] = ['exception' => $e, 'detail' => $detail];
  3468. return $detail;
  3469. }
  3470. $response = $e->getResponse();
  3471. $detail['status'] = (int)$response->getStatusCode();
  3472. try {
  3473. $body = $response->getBody();
  3474. if ($body->isSeekable()) {
  3475. $body->rewind();
  3476. }
  3477. $content = $body->isReadable() ? (string)$body : '';
  3478. } catch (\Throwable $t) {
  3479. $content = '';
  3480. }
  3481. if ($content === '') {
  3482. $this->gpt_upstream_error_cache[$cacheKey] = ['exception' => $e, 'detail' => $detail];
  3483. return $detail;
  3484. }
  3485. $detail['body'] = mb_substr($content, 0, 4000);
  3486. $decoded = json_decode($content, true);
  3487. $decoded_error = is_array($decoded) ? getProp($decoded, 'error') : null;
  3488. if (is_array($decoded_error)) {
  3489. $detail['code'] = (string)getProp($decoded_error, 'code', '');
  3490. // 上游 message 可能超长,截断后再用于模型翻译与展示,避免把整段报错送进模型
  3491. $detail['message'] = mb_substr((string)getProp($decoded_error, 'message', ''), 0, 1000);
  3492. }
  3493. $this->gpt_upstream_error_cache[$cacheKey] = ['exception' => $e, 'detail' => $detail];
  3494. return $detail;
  3495. }
  3496. /**
  3497. * 将上游错误转换为展示给前端的提示:内容安全策略拦截等给出可操作的说明
  3498. */
  3499. private function buildChatErrorForUser(\Exception $e, $upstreamError = null)
  3500. {
  3501. if (!is_array($upstreamError)) {
  3502. $upstreamError = $this->resolveGptUpstreamError($e);
  3503. }
  3504. $code = (string)getProp($upstreamError, 'code', '');
  3505. $message = (string)getProp($upstreamError, 'message', '');
  3506. $status = (int)getProp($upstreamError, 'status', 0);
  3507. if ($code === 'content_filter') {
  3508. return '本集内容被上游模型的内容安全策略拦截,请调整剧本中过于血腥、暴力等敏感描述后重试,或改用其他模型';
  3509. }
  3510. // 其他上游报错复用全局错误映射(已知签名本地命中;未命中时由模型翻译并缓存)
  3511. if ($message !== '') {
  3512. $mapped = mapErrorMessage($message);
  3513. if ($mapped !== '' && $mapped !== '未知异常,请重试') {
  3514. return $mapped;
  3515. }
  3516. // 映射不可用时保留上游原文,便于排查
  3517. return '上游模型返回错误(' . $status . '):' . mb_substr($message, 0, 300);
  3518. }
  3519. // 拿不到上游报文时,仅传输层异常(连接失败、超时等)交给全局映射兜底
  3520. if ($e instanceof \GuzzleHttp\Exception\GuzzleException) {
  3521. return mapErrorMessage($e->getMessage());
  3522. }
  3523. // 业务异常(如参数校验)保持原有文案,避免被模型翻译后丢失关键信息
  3524. return '处理请求时发生异常: ' . $e->getMessage();
  3525. }
  3526. /**
  3527. * GPT 中转站探活:GET /v1/models,5 秒短超时
  3528. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  3529. */
  3530. private function checkGptServiceAvailable($apiKey = null)
  3531. {
  3532. if ($apiKey === null) {
  3533. $apiKey = env('GPT_54_API_KEY');
  3534. }
  3535. if (empty($apiKey)) {
  3536. return false;
  3537. }
  3538. try {
  3539. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  3540. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  3541. 'headers' => [
  3542. 'Authorization' => 'Bearer ' . $apiKey,
  3543. 'Content-Type' => 'application/json'
  3544. ]
  3545. ]);
  3546. $status = $response->getStatusCode();
  3547. return $status < 500 && $status != 429;
  3548. } catch (\Exception $e) {
  3549. return false;
  3550. }
  3551. }
  3552. /**
  3553. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  3554. * 全部失败抛出友好错误
  3555. */
  3556. private function ensureGptServiceAvailable($apiKey = null)
  3557. {
  3558. $maxRetries = $this->gptRetryTimes();
  3559. $interval = $this->gptRetryInterval();
  3560. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  3561. if ($this->checkGptServiceAvailable($apiKey)) {
  3562. return;
  3563. }
  3564. if ($attempt < $maxRetries) {
  3565. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  3566. 'retry' => $attempt + 1,
  3567. 'max_retries' => $maxRetries
  3568. ]);
  3569. sleep($interval);
  3570. }
  3571. }
  3572. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  3573. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  3574. 'max_retries' => $maxRetries,
  3575. 'interval' => $interval
  3576. ]);
  3577. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  3578. }
  3579. /**
  3580. * GPT 流式输出处理方法
  3581. *
  3582. * @param array $post_data GPT API请求参数
  3583. * @return \Generator 返回生成器,用于流式输出
  3584. */
  3585. private function gpt54StreamResponse($post_data) {
  3586. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  3587. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  3588. // gpt-5.4 中转已下线,强制映射到 gpt-5.6-sol
  3589. if ($modelName === 'gpt-5.4') {
  3590. $modelName = 'gpt-5.6-terra';
  3591. $post_data['model'] = $modelName;
  3592. }
  3593. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  3594. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  3595. $usedLunaFallback = false;
  3596. // 流式请求长时间无任何返回(TTFB)超过该秒数时切换备用 Key(env 可配置,默认 600 秒)
  3597. $ttfbTimeoutSeconds = (int)env('GPT_SWITCH_LUNA_AFTER_SECONDS', 600);
  3598. if (empty($apiKey)) {
  3599. Utils::throwError('20003:GPT API Key未配置');
  3600. }
  3601. // 先探活,服务不可用时自动重试
  3602. $this->ensureGptServiceAvailable($apiKey);
  3603. $client = new Client(['timeout' => 1800, 'verify' => false, 'read_timeout' => $ttfbTimeoutSeconds]);
  3604. // 移除 thinking 参数,GPT-5.4 不支持
  3605. if (isset($post_data['thinking'])) {
  3606. unset($post_data['thinking']);
  3607. }
  3608. if (isset($post_data['reasoning_effort'])) {
  3609. unset($post_data['reasoning_effort']);
  3610. }
  3611. // GPT-5.x(推理型上游)只接受默认 temperature(1),传入其他值会返回 400:
  3612. // Unsupported value: 'temperature' does not support 1.35 with this model.
  3613. // Only the default (1) value is supported.
  3614. unset($post_data['temperature']);
  3615. // 流式场景下保留 response_format(json 输出时强制模型输出完整 JSON,与非流式 gpt54ChatOnly 对齐)
  3616. // 中转站对 response_format 的兼容性由请求方控制:仅在需要 json 输出时传入
  3617. $post_data['max_completion_tokens'] = 100000;
  3618. // GPT-5.x 上游仅支持 max_completion_tokens,同时携带 max_tokens 会返回 400:
  3619. // Unsupported parameter: 'max_tokens' is not supported with this model.
  3620. // 这里显式移除,防止调用方在 post_data 中残留 max_tokens。
  3621. unset($post_data['max_tokens']);
  3622. // GPT-5.x(推理型上游)不接受 frequency_penalty / presence_penalty:
  3623. // Unsupported parameter: 'frequency_penalty' is not supported with this model.
  3624. // 调用方默认传 0,移除后采样行为不变,显式清理避免 400。
  3625. unset($post_data['frequency_penalty'], $post_data['presence_penalty']);
  3626. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  3627. $post_data['stream_options'] = ['include_usage' => true];
  3628. $maxRetries = $this->gptRetryTimes();
  3629. $interval = $this->gptRetryInterval();
  3630. $attempt = 0;
  3631. while (true) {
  3632. $fullContent = '';
  3633. $usage = [];
  3634. $buffer = '';
  3635. // JSON 输出场景:不启用"整段正文包成 JSON 字符串"的暂缓缓存,流式过程中直接输出供前端展示
  3636. $isJsonRequest = isset($post_data['response_format'])
  3637. && is_array($post_data['response_format'])
  3638. && ($post_data['response_format']['type'] ?? '') === 'json_object';
  3639. $suspectJsonWrap = false;
  3640. $pendingContent = '';
  3641. $requestStartedAt = microtime(true);
  3642. $headers = [
  3643. 'Authorization' => 'Bearer ' . $apiKey,
  3644. 'Content-Type' => 'application/json',
  3645. 'Accept' => 'text/event-stream'
  3646. ];
  3647. try {
  3648. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  3649. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  3650. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  3651. 'json' => $post_data,
  3652. 'headers' => $headers,
  3653. 'stream' => true // 启用流式响应
  3654. ]);
  3655. $body = $response->getBody();
  3656. dLog('deepseek')->info('开始读取 GPT 流式响应');
  3657. // 逐行读取流式响应
  3658. while (!$body->eof()) {
  3659. // 长时间没有任何内容返回时,切换备用 Key 重试
  3660. if ($fullContent === '' && empty($usage) && (microtime(true) - $requestStartedAt) > $ttfbTimeoutSeconds) {
  3661. throw new \RuntimeException('GPT 流式响应长时间无返回,等待切换备用 Key');
  3662. }
  3663. $chunk = $body->read(1024); // 每次读取 1KB
  3664. $buffer .= $chunk;
  3665. // 按行分割
  3666. $lines = explode("\n", $buffer);
  3667. // 保留最后一个不完整的行
  3668. $buffer = array_pop($lines);
  3669. foreach ($lines as $line) {
  3670. $line = trim($line);
  3671. // 跳过空行
  3672. if (empty($line)) {
  3673. continue;
  3674. }
  3675. // 检查是否是 SSE 数据行
  3676. if (strpos($line, 'data: ') !== 0) {
  3677. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  3678. continue;
  3679. }
  3680. $data = substr($line, 6); // 移除 "data: " 前缀
  3681. if ($data === '[DONE]') {
  3682. dLog('deepseek')->info('收到结束标记');
  3683. break 2; // 跳出 foreach 和流读取循环
  3684. }
  3685. try {
  3686. $json = json_decode($data, true);
  3687. if (json_last_error() !== JSON_ERROR_NONE) {
  3688. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3689. continue;
  3690. }
  3691. if (isset($json['choices'][0]['delta'])) {
  3692. $delta = $json['choices'][0]['delta'];
  3693. // 处理回答内容
  3694. if (isset($delta['content'])) {
  3695. $fullContent .= $delta['content'];
  3696. $trimmed = ltrim($fullContent);
  3697. if (!$suspectJsonWrap && !$isJsonRequest && $trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
  3698. // 可能模型把整段正文包成了 JSON 字符串,先暂缓输出
  3699. $suspectJsonWrap = true;
  3700. }
  3701. if (!$suspectJsonWrap) {
  3702. // 中转可能一次返回大段内容,按小块输出保持流式节奏
  3703. $chunkSize = 256;
  3704. $chunkLength = mb_strlen($delta['content']);
  3705. for ($offset = 0; $offset < $chunkLength; $offset += $chunkSize) {
  3706. yield [
  3707. 'type' => 'content',
  3708. 'content' => mb_substr($delta['content'], $offset, $chunkSize),
  3709. ];
  3710. }
  3711. } else {
  3712. $pendingContent .= $delta['content'];
  3713. }
  3714. }
  3715. }
  3716. // 获取使用统计信息
  3717. if (isset($json['usage'])) {
  3718. $usage = $json['usage'];
  3719. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  3720. }
  3721. } catch (\Exception $e) {
  3722. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3723. continue;
  3724. }
  3725. }
  3726. }
  3727. dLog('deepseek')->info('流式读取完成', [
  3728. 'content_length' => strlen($fullContent)
  3729. ]);
  3730. // 兼容模型偶发把整段正文包裹成 JSON 字符串返回
  3731. if ($suspectJsonWrap) {
  3732. $decoded = json_decode(trim($fullContent), true);
  3733. $unwrapped = null;
  3734. if (is_array($decoded)) {
  3735. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  3736. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  3737. $unwrapped = $decoded[$key];
  3738. break;
  3739. }
  3740. }
  3741. }
  3742. if ($unwrapped !== null) {
  3743. $fullContent = $unwrapped;
  3744. $chunkSize = 256;
  3745. $contentLength = mb_strlen($fullContent);
  3746. for ($offset = 0; $offset < $contentLength; $offset += $chunkSize) {
  3747. yield [
  3748. 'type' => 'content',
  3749. 'content' => mb_substr($fullContent, $offset, $chunkSize),
  3750. ];
  3751. }
  3752. } elseif ($pendingContent !== '') {
  3753. // 误判:补发暂缓内容,避免内容丢失
  3754. yield [
  3755. 'type' => 'content',
  3756. 'content' => $pendingContent,
  3757. ];
  3758. }
  3759. }
  3760. yield [
  3761. 'type' => 'done',
  3762. 'full_content' => $fullContent,
  3763. 'full_reasoning' => '',
  3764. 'usage' => $usage
  3765. ];
  3766. return;
  3767. } catch (\Exception $e) {
  3768. // 提前解析上游错误详情(流式响应体只能读取一次,后续日志与前端提示共用)
  3769. $upstream_error = $this->resolveGptUpstreamError($e);
  3770. // 报错或长时间无返回时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  3771. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  3772. $usedLunaFallback = true;
  3773. $apiKey = $lunaApiKey;
  3774. dLog('deepseek')->warning('GPT 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  3775. continue;
  3776. }
  3777. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  3778. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  3779. // 记录上游返回的错误详情(流式响应 Guzzle 不会自动附带 body,需手动读取)
  3780. $error_context = ['error' => $e->getMessage()];
  3781. if ($upstream_error['status'] || $upstream_error['body'] !== '') {
  3782. $error_context['upstream_status'] = $upstream_error['status'];
  3783. $error_context['upstream_code'] = $upstream_error['code'];
  3784. $error_context['upstream_body'] = $upstream_error['body'];
  3785. }
  3786. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage(), $error_context);
  3787. logDB('deepseek', 'error', 'GPT 流式请求失败', $error_context);
  3788. throw $e;
  3789. }
  3790. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  3791. 'retry' => $attempt + 1,
  3792. 'max_retries' => $maxRetries,
  3793. 'error' => $e->getMessage()
  3794. ]);
  3795. sleep($interval);
  3796. $attempt++;
  3797. }
  3798. }
  3799. }
  3800. // 与推理模型对话
  3801. public function chatWithReasoner($data) {
  3802. // 文生文计费预检(normal 档)
  3803. $uid = Site::getUid();
  3804. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'normal'), $uid);
  3805. $content = getProp($data, 'content');
  3806. $model = getProp($data, 'model', 'r1');
  3807. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3808. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3809. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3810. if ($model == 'r1') {
  3811. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  3812. $thinkingMode = 'disabled';
  3813. } else {
  3814. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  3815. $thinkingMode = 'disabled';
  3816. }
  3817. // 获取可选情感(根据音色可支持情感选)
  3818. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  3819. $emotion_list = [];
  3820. foreach ($timbre_emotion as $emotion) {
  3821. $tmp = explode(',', $emotion);
  3822. $emotion_list = array_merge($emotion_list, $tmp);
  3823. }
  3824. $emotion_list = array_unique($emotion_list);
  3825. $emotion_str = implode('、', $emotion_list);
  3826. // // 获取可选情感
  3827. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  3828. // $emotion_str = implode('、', $emotion_list);
  3829. // 是否启用情感
  3830. $enable_emotion = getProp($data, 'enable_emotion', 0);
  3831. if ($enable_emotion) {
  3832. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  3833. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3834. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  3835. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  3836. }else {
  3837. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  3838. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3839. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  3840. }
  3841. $messages = [
  3842. [
  3843. 'role' => 'system',
  3844. 'content' => $sys_content
  3845. ],
  3846. [
  3847. 'role' => 'user',
  3848. 'content' => $content
  3849. ]
  3850. ];
  3851. $post_data = [
  3852. 'model' => $model,
  3853. 'messages' => $messages,
  3854. // 'max_tokens' => 8192,
  3855. 'temperature' => 1,
  3856. 'frequency_penalty' => 0,
  3857. 'presence_penalty' => 0,
  3858. 'thinking' => ['type' => $thinkingMode],
  3859. 'response_format' => [
  3860. 'type' => 'text'
  3861. ],
  3862. 'stream' => false
  3863. ];
  3864. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3865. // 根据模型类型选择调用方法
  3866. $fullContent = '';
  3867. $usage = [];
  3868. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  3869. if (is_array($chatResult)) {
  3870. $fullContent = $chatResult['fullContent'];
  3871. $usage = $chatResult['usage'];
  3872. }
  3873. // 处理获取到的剧本数据
  3874. $script_content = handleScriptWords($fullContent, $enable_emotion);
  3875. $result = [
  3876. 'origin_content' => $fullContent,
  3877. 'roles' => getProp($script_content, 'roles'),
  3878. 'words' => getProp($script_content, 'words'),
  3879. ];
  3880. // 文生文成功计费(normal 档):同时记录积分与 token 明细
  3881. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  3882. 'model' => $model,
  3883. 'source' => 'chatWithReasoner',
  3884. ], 'normal');
  3885. return $result;
  3886. }
  3887. public function resetParagraphAudio($data) {
  3888. $bid = getProp($data, 'bid');
  3889. $cid = getProp($data, 'cid');
  3890. $version_id = getProp($data, 'version_id');
  3891. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  3892. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  3893. 'generate_status' => '待制作',
  3894. 'updated_at' => date('Y-m-d H:i:s')
  3895. ]);
  3896. }
  3897. public function saveParagraphAudio($data) {
  3898. $bid = getProp($data, 'bid');
  3899. $cid = getProp($data, 'cid');
  3900. $version_id = getProp($data, 'version_id');
  3901. $sequence = getProp($data, 'sequence');
  3902. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  3903. // 获取所有情感
  3904. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3905. $emotion_list = array_flip($emotion_list);
  3906. // 获取音色支持情感
  3907. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  3908. $timbre_emotion = explode(',', $timbre_emotion);
  3909. $emotion = getProp($data, 'emotion');
  3910. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  3911. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3912. $list = [
  3913. 'bid' => $bid,
  3914. 'cid' => $cid,
  3915. 'version_id' => $version_id,
  3916. 'sequence' => $sequence,
  3917. 'role' => getProp($data, 'role'),
  3918. 'gender' => getProp($data, 'gender'),
  3919. 'text' => trim(getProp($data, 'text')),
  3920. 'emotion' => $emotion,
  3921. 'emotion_type' => $emotion_type,
  3922. 'voice_type' => getProp($data, 'voice_type'),
  3923. 'voice_name' => getProp($data, 'voice_name'),
  3924. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  3925. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  3926. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  3927. 'pitch' => getProp($data, 'pitch', 0),
  3928. // 'paragraph_audio_url' => '',
  3929. 'generate_status' => '制作中',
  3930. 'error_msg' => '',
  3931. 'updated_at' => date('Y-m-d H:i:s')
  3932. ];
  3933. $continue = false;
  3934. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  3935. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  3936. $list['generate_status'] = '制作成功';
  3937. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  3938. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  3939. $continue = true;
  3940. }
  3941. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  3942. if ($id) {
  3943. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  3944. }else {
  3945. $list['created_at'] = date('Y-m-d H:i:s');
  3946. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  3947. $boolen = $id ? true : false;
  3948. }
  3949. // 如果更新成功则加入查询队列
  3950. if ($boolen) {
  3951. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  3952. Redis::sadd($redis_key, $id);
  3953. }
  3954. if ($boolen && !$continue) {
  3955. $boolen = false;
  3956. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3957. // 根据ID通过API通知合成音频
  3958. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  3959. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  3960. $response = $result->getBody()->getContents();
  3961. $response_arr = json_decode($response, true);
  3962. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3963. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3964. Log::info('通知火山生成段落音频失败: '.$error_msg);
  3965. Utils::throwError('20003:通知火山生成段落音频失败');
  3966. }
  3967. $boolen = true;
  3968. }
  3969. return $boolen;
  3970. }
  3971. public function insertAudioEffect($data) {
  3972. $audio_id = getProp($data, 'audio_id');
  3973. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3974. $bid = getProp($chapter_audio, 'bid');
  3975. $version_id = getProp($chapter_audio, 'version_id');
  3976. $cid = getProp($chapter_audio, 'cid');
  3977. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3978. $audio_effect_json = getProp($data, 'audio_effect_json');
  3979. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  3980. try {
  3981. DB::beginTransaction();
  3982. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3983. if (!$count) {
  3984. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3985. }else {
  3986. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3987. }
  3988. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3989. 'audio_effect_status' => '添加中',
  3990. 'audio_effect_json' => $audio_effect_json,
  3991. 'updated_at' => date('Y-m-d H:i:s')
  3992. ]);
  3993. if (!$boolen1) {
  3994. DB::rollBack();
  3995. Utils::throwError('20003:更新生成数据失败');
  3996. }
  3997. $id = DB::table('mp_audio_tasks')->insertGetId([
  3998. 'audio_id' => $audio_id,
  3999. 'generate_status' => '执行中',
  4000. 'generate_json' => json_encode([], 256),
  4001. 'bid' => $bid,
  4002. 'book_name' => getProp($chapter_audio, 'book_name'),
  4003. 'version_id' => $version_id,
  4004. 'version_name' => getProp($chapter_audio, 'version_name'),
  4005. 'cid' => $cid,
  4006. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  4007. 'task_name' => $task_name,
  4008. 'created_at' => date('Y-m-d H:i:s'),
  4009. 'updated_at' => date('Y-m-d H:i:s')
  4010. ]);
  4011. if (!$id) {
  4012. DB::rollBack();
  4013. Utils::throwError('20003:创建任务失败');
  4014. }
  4015. }catch (\Exception $e) {
  4016. DB::rollBack();
  4017. Utils::throwError('20003:'.$e->getMessage());
  4018. }
  4019. DB::commit();
  4020. $client = new Client(['timeout' => 1800, 'verify' => false]);
  4021. // 根据ID通过API通知合成音频
  4022. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  4023. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  4024. $response = $result->getBody()->getContents();
  4025. $response_arr = json_decode($response, true);
  4026. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4027. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4028. Log::info('通知火山插入音效失败: '.$error_msg);
  4029. Utils::throwError('20003:通知火山插入音效失败');
  4030. }
  4031. return true;
  4032. }
  4033. public function insertBgm($data) {
  4034. $audio_id = getProp($data, 'audio_id');
  4035. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  4036. $bid = getProp($chapter_audio, 'bid');
  4037. $version_id = getProp($chapter_audio, 'version_id');
  4038. $cid = getProp($chapter_audio, 'cid');
  4039. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  4040. $bgm_json = getProp($data, 'bgm_json');
  4041. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  4042. if (!$bgm_json) {
  4043. $bgm_json = getProp($data, 'audio_effect_json');
  4044. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  4045. }
  4046. try {
  4047. DB::beginTransaction();
  4048. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  4049. if (!$count) {
  4050. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  4051. }else {
  4052. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  4053. }
  4054. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  4055. 'bgm_status' => '添加中',
  4056. 'bgm_json' => $bgm_json,
  4057. 'updated_at' => date('Y-m-d H:i:s')
  4058. ]);
  4059. if (!$boolen1) {
  4060. DB::rollBack();
  4061. Utils::throwError('20003:更新生成数据失败');
  4062. }
  4063. $id = DB::table('mp_audio_tasks')->insertGetId([
  4064. 'audio_id' => $audio_id,
  4065. 'generate_status' => '执行中',
  4066. 'generate_json' => json_encode([], 256),
  4067. 'bid' => $bid,
  4068. 'book_name' => getProp($chapter_audio, 'book_name'),
  4069. 'version_id' => $version_id,
  4070. 'version_name' => getProp($chapter_audio, 'version_name'),
  4071. 'cid' => $cid,
  4072. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  4073. 'task_name' => $task_name,
  4074. 'created_at' => date('Y-m-d H:i:s'),
  4075. 'updated_at' => date('Y-m-d H:i:s')
  4076. ]);
  4077. if (!$id) {
  4078. DB::rollBack();
  4079. Utils::throwError('20003:创建任务失败');
  4080. }
  4081. }catch (\Exception $e) {
  4082. DB::rollBack();
  4083. Utils::throwError('20003:'.$e->getMessage());
  4084. }
  4085. DB::commit();
  4086. $client = new Client(['timeout' => 1800, 'verify' => false]);
  4087. // 根据ID通过API通知合成音频
  4088. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  4089. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  4090. $response = $result->getBody()->getContents();
  4091. $response_arr = json_decode($response, true);
  4092. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4093. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4094. Log::info('通知火山插入bgm失败: '.$error_msg);
  4095. Utils::throwError('20003:通知火山插入bgm失败');
  4096. }
  4097. return true;
  4098. }
  4099. public function getParagraphAudios($data) {
  4100. $bid = getProp($data, 'bid');
  4101. $cid = getProp($data, 'cid');
  4102. $version_id = getProp($data, 'version_id');
  4103. $sequence = getProp($data, 'sequence');
  4104. // 获取已生成的音频
  4105. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  4106. if ($sequence) $query->where('sequence', $sequence);
  4107. $paragraph_audios = $query->orderBy('sequence')->get();
  4108. $result = [];
  4109. foreach($paragraph_audios as $item) {
  4110. $result[] = [
  4111. 'sequence' => getProp($item, 'sequence'),
  4112. 'role' => getProp($item, 'role'),
  4113. 'gender' => getProp($item, 'gender'),
  4114. 'text' => trim(getProp($item, 'text')),
  4115. 'emotion' => getProp($item, 'emotion'),
  4116. 'emotion_type' => getProp($item, 'emotion_type'),
  4117. 'voice_type' => getProp($item, 'voice_type'),
  4118. 'voice_name' => getProp($item, 'voice_name'),
  4119. 'speed_ratio' => getProp($item, 'speed_ratio'),
  4120. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  4121. 'emotion_scale' => getProp($item, 'emotion_scale'),
  4122. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  4123. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  4124. ];
  4125. }
  4126. return $result;
  4127. }
  4128. // 新增合成任务
  4129. public function addGenerateTask($data) {
  4130. $bid = getProp($data, 'bid');
  4131. $cid = getProp($data, 'cid');
  4132. $version_id = getProp($data, 'version_id');
  4133. $generate_json = getProp($data, 'generate_json');
  4134. // 获取已生成的音频
  4135. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  4136. $paragraph_list = [];
  4137. foreach($paragraph_audios as $item) {
  4138. $paragraph_list[getProp($item, 'sequence')] = [
  4139. 'role' => getProp($item, 'role'),
  4140. 'gender' => getProp($item, 'gender'),
  4141. 'text' => trim(getProp($item, 'text')),
  4142. 'emotion' => getProp($item, 'emotion'),
  4143. 'emotion_type' => getProp($item, 'emotion_type'),
  4144. 'voice_type' => getProp($item, 'voice_type'),
  4145. 'voice_name' => getProp($item, 'voice_name'),
  4146. 'speed_ratio' => getProp($item, 'speed_ratio'),
  4147. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  4148. 'emotion_scale' => getProp($item, 'emotion_scale'),
  4149. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  4150. ];
  4151. }
  4152. // 更新角色-音色信息
  4153. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  4154. $existed_role_info = json_decode($existed_role_info, true);
  4155. if (!$existed_role_info) $existed_role_info = [];
  4156. // 获取情感信息
  4157. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  4158. $emotion_list = array_flip($emotion_list);
  4159. // 获取音色对应情感组
  4160. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  4161. $timbre_emotion_list = [];
  4162. foreach($timbre_emotions as $item) {
  4163. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  4164. }
  4165. // 构造生成音频的json
  4166. $words = json_decode($generate_json, true);
  4167. // 最终合成前的参数组
  4168. $mp_chapter_paragraph_audios = [];
  4169. $sequence = 1;
  4170. $complete_paragraph_sequences = [];
  4171. foreach($words as &$word) {
  4172. 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:参数格式有误');
  4173. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  4174. $role = getProp($word, 'role');
  4175. $word['gender'] = (int)$word['gender'];
  4176. // 判断音色对应情感是否支持,不支持则调整为中性
  4177. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  4178. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  4179. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  4180. if (isset($emotion_list[getProp($word, 'emotion')])) {
  4181. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  4182. }else {
  4183. $word['emotion'] = '中性';
  4184. $word['emotion_type'] = 'neutral';
  4185. }
  4186. $existed_role_info[$role] = [
  4187. 'timbre_type' => $word['voice_type'],
  4188. 'timbre_name' => $word['voice_name'],
  4189. 'emotion' => $word['emotion'],
  4190. 'emotion_type' => $word['emotion_type'],
  4191. 'speed_ratio' => $word['speed_ratio'],
  4192. 'loudness_ratio'=> $word['loudness_ratio'],
  4193. 'emotion_scale' => $word['emotion_scale'],
  4194. 'pitch' => $word['pitch']
  4195. ];
  4196. $word['paragraph_audio_url'] = '';
  4197. // 判断生成参数是否相同,相同则直接使用已生成的音频
  4198. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  4199. // 如果音频存在并且参数都未改变则使用已生成的音频
  4200. if (getProp($paragraph, 'paragraph_audio_url')) {
  4201. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  4202. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  4203. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  4204. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  4205. // {
  4206. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  4207. // }
  4208. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  4209. }
  4210. $tmp = $word;
  4211. // 组装章节分句音频数据
  4212. // $tmp['sequence'] = getProp($word, 'sequence');
  4213. // $tmp['text'] = getProp($word, 'text');
  4214. // $tmp['emotion'] = getProp($word, 'emotion');
  4215. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  4216. // $tmp['voice_name'] = getProp($word, 'voice_name');
  4217. // $tmp['voice_type'] = getProp($word, 'voice_type');
  4218. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  4219. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  4220. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  4221. $tmp['bid'] = $bid;
  4222. $tmp['version_id'] = $version_id;
  4223. $tmp['cid'] = $cid;
  4224. $tmp['sequence'] = $sequence;
  4225. $tmp['created_at'] = date('Y-m-d H:i:s');
  4226. $tmp['updated_at'] = date('Y-m-d H:i:s');
  4227. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  4228. $mp_chapter_paragraph_audios[] = $tmp;
  4229. $complete_paragraph_sequences[] = $sequence;
  4230. $sequence++;
  4231. }
  4232. $generate_json = json_encode($words, 256);
  4233. // 判断是否有未生成字幕的段落
  4234. $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();
  4235. if ($no_subtitle_sequences) {
  4236. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  4237. }
  4238. try {
  4239. DB::beginTransaction();
  4240. $role_info = json_encode($existed_role_info, 256);
  4241. $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')]);
  4242. if (!$boolen) {
  4243. DB::rollBack();
  4244. Utils::throwError('20003:更新角色信息失败');
  4245. }
  4246. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  4247. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  4248. if (!$count) {
  4249. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  4250. }else {
  4251. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  4252. }
  4253. $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')]);
  4254. if (!$boolen1) {
  4255. DB::rollBack();
  4256. Utils::throwError('20003:更新生成数据失败');
  4257. }
  4258. $id = DB::table('mp_audio_tasks')->insertGetId([
  4259. 'audio_id' => getProp($chapter_audio, 'id'),
  4260. 'generate_status' => '执行中',
  4261. 'generate_json' => $generate_json,
  4262. 'bid' => $bid,
  4263. 'book_name' => getProp($chapter_audio, 'book_name'),
  4264. 'version_id' => $version_id,
  4265. 'version_name' => getProp($chapter_audio, 'version_name'),
  4266. 'cid' => $cid,
  4267. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  4268. 'task_name' => $task_name,
  4269. 'created_at' => date('Y-m-d H:i:s'),
  4270. 'updated_at' => date('Y-m-d H:i:s')
  4271. ]);
  4272. if (!$id) {
  4273. DB::rollBack();
  4274. Utils::throwError('20003:创建任务失败');
  4275. }
  4276. // 删除不在段落序号范围内的其他数据
  4277. if ($complete_paragraph_sequences) {
  4278. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  4279. }
  4280. // // 删除章节分句音频数据并重新插入
  4281. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  4282. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  4283. // if (!$boolen3) {
  4284. // DB::rollBack();
  4285. // Utils::throwError('20003:更新章节分句音频失败');
  4286. // }
  4287. } catch (\Exception $e) {
  4288. DB::rollBack();
  4289. Utils::throwError('20003:'.$e->getMessage());
  4290. }
  4291. DB::commit();
  4292. // 通知火山生成音频
  4293. $client = new Client(['timeout' => 1800, 'verify' => false]);
  4294. // 根据ID通过API通知合成音频
  4295. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  4296. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  4297. $response = $result->getBody()->getContents();
  4298. $response_arr = json_decode($response, true);
  4299. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4300. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4301. Log::info('通知火山生成音频失败: '.$error_msg);
  4302. Utils::throwError('20003:通知火山生成音频失败');
  4303. }
  4304. return true;
  4305. }
  4306. public function timbreList($data) {
  4307. $gender = getProp($data, 'gender');
  4308. $timbre_name = getProp($data, 'voice_name');
  4309. $category_id = getProp($data, 'category_id');
  4310. $age_stage = getProp($data, 'age_stage');
  4311. $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');
  4312. if ($gender) {
  4313. $query->where('gender', $gender);
  4314. }
  4315. if ($timbre_name) {
  4316. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  4317. }
  4318. if ($category_id) {
  4319. $query->where(function ($query) use ($category_id) {
  4320. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  4321. });
  4322. }
  4323. if ($age_stage) {
  4324. $query->where('age_stage', $age_stage);
  4325. }
  4326. $list = $query->get()->map(function ($value) {
  4327. $value = (array)$value;
  4328. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  4329. return $value;
  4330. })->toArray();
  4331. return $list;
  4332. }
  4333. // 生成火山临时token
  4334. public function setStsToken() {
  4335. // ************* 配置参数 *************
  4336. $method = 'GET';
  4337. $service = 'sts';
  4338. $host = 'open.volcengineapi.com';
  4339. $region = env('VOLC_REGION');
  4340. $endpoint = 'https://open.volcengineapi.com';
  4341. // $endpoint = 'https://tos-cn-beijing.volces.com';
  4342. $access_key = env('VOLC_AK');
  4343. $secret_key = env('VOLC_SK');
  4344. // 获取缓存中的token,如果没有则请求接口
  4345. $token = Redis::get('volc_sts_token');
  4346. if (!$token) {
  4347. // 查询参数
  4348. $query_parameters = [
  4349. 'Action' => 'AssumeRole',
  4350. 'RoleSessionName' => 'user@zw',
  4351. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  4352. 'Version' => '2018-01-01'
  4353. ];
  4354. // 生成URL编码的查询字符串
  4355. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  4356. // 获取签名头信息
  4357. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  4358. // 构建完整URL
  4359. $request_url = $endpoint . '?' . $request_parameters;
  4360. $client = new Client(['verify' => false]);
  4361. $response = $client->get($request_url, ['headers' => $headers]);
  4362. $response_arr = json_decode($response->getBody()->getContents(), true);
  4363. $result = [
  4364. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  4365. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  4366. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  4367. 'Region' => env('VOLC_REGION'),
  4368. 'Endpoint' => env('VOLC_END_POINT'),
  4369. 'Bucket' => env('VOLC_BUCKET'),
  4370. ];
  4371. // 缓存token
  4372. Redis::setex('volc_sts_token', 3000, json_encode($result));
  4373. return $result;
  4374. } else {
  4375. return json_decode($token, true);
  4376. }
  4377. // $response = $response['Response'];
  4378. // $access_key = $response['Credentials']['AccessKeyId'];
  4379. // $secret_key = $response['Credentials']['AccessKeySecret'];
  4380. // $security_token = $response['Credentials']['SecurityToken'];
  4381. // $expiration = $response['Credentials']['Expiration'];
  4382. // dd($response_arr);
  4383. }
  4384. public function emotionGroups($data) {
  4385. $id = getProp($data, 'group_id');
  4386. $group_name = getProp($data, 'group_name');
  4387. $voice_type = getProp($data, 'voice_type');
  4388. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  4389. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  4390. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  4391. if ($group_name) {
  4392. $query->where('group_name', 'like', "%{$group_name}%");
  4393. }
  4394. if ($id) {
  4395. $query->where('id', $id);
  4396. }
  4397. if ($voice_type) {
  4398. $query->where('voice_type', $voice_type);
  4399. }
  4400. return $query->orderBy('id')->get()->map(function ($value) {
  4401. return (array)$value;
  4402. })->toArray();
  4403. }
  4404. private function sign($key, $msg) {
  4405. return hash_hmac('sha256', $msg, $key, true);
  4406. }
  4407. // 生成签名密钥
  4408. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  4409. $kDate = $this->sign($key, $dateStamp);
  4410. $kRegion = $this->sign($kDate, $regionName);
  4411. $kService = $this->sign($kRegion, $serviceName);
  4412. $kSigning = $this->sign($kService, 'request');
  4413. return $kSigning;
  4414. }
  4415. // 获取签名头信息
  4416. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  4417. $contenttype = 'application/x-www-form-urlencoded';
  4418. $accept = 'application/json';
  4419. // 获取当前UTC时间
  4420. $t = new DateTime('now', new DateTimeZone('UTC'));
  4421. $xdate = $t->format('Ymd\THis\Z');
  4422. $datestamp = $t->format('Ymd');
  4423. // 1. 拼接规范请求串
  4424. $canonical_uri = '/';
  4425. $canonical_querystring = $request_parameters;
  4426. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  4427. $signed_headers = 'content-type;host;x-date';
  4428. // 空请求体的SHA256哈希
  4429. $payload_hash = hash('sha256', '');
  4430. $canonical_request = implode("\n", [
  4431. $method,
  4432. $canonical_uri,
  4433. $canonical_querystring,
  4434. $canonical_headers,
  4435. $signed_headers,
  4436. $payload_hash
  4437. ]);
  4438. // 2. 拼接待签名字符串
  4439. $algorithm = 'HMAC-SHA256';
  4440. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  4441. $hashed_canonical_request = hash('sha256', $canonical_request);
  4442. $string_to_sign = implode("\n", [
  4443. $algorithm,
  4444. $xdate,
  4445. $credential_scope,
  4446. $hashed_canonical_request
  4447. ]);
  4448. // 3. 计算签名
  4449. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  4450. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  4451. // 4. 添加签名到请求头
  4452. $authorization_header = sprintf(
  4453. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  4454. $algorithm,
  4455. $access_key,
  4456. $credential_scope,
  4457. $signed_headers,
  4458. $signature
  4459. );
  4460. return [
  4461. 'Accept' => $accept,
  4462. 'Content-Type' => $contenttype,
  4463. 'X-Date' => $xdate,
  4464. 'Authorization' => $authorization_header
  4465. ];
  4466. }
  4467. // 文字合成语音(火山引擎)
  4468. public function tts($data) {
  4469. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  4470. $headers = [
  4471. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  4472. 'Content-Type' => 'application/json; charset=UTF-8'
  4473. ];
  4474. $post_data = [
  4475. 'app' => [
  4476. 'appid' => env('VOLC_APPID'),
  4477. 'token' => env('VOLC_TOKEN'),
  4478. 'cluster' => 'volcano_tts'
  4479. ],
  4480. 'user' => [
  4481. 'uid' => 'mp_audio'
  4482. ],
  4483. // 'audio' => [
  4484. // 'voice_type' =>
  4485. // ],
  4486. ];
  4487. }
  4488. public function scriptList($data) {
  4489. $uid = Site::getUid();
  4490. $script_id = getProp($data, 'script_id');
  4491. $script_name = getProp($data, 'script_name');
  4492. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  4493. if ($script_id) {
  4494. $query->where('id', $script_id);
  4495. }
  4496. if ($script_name) {
  4497. $query->where('script_name', 'like', "%{$script_name}%");
  4498. }
  4499. return $query->orderBy('created_at', 'desc')->paginate(12);
  4500. }
  4501. public function scripts($data) {
  4502. $uid = Site::getUid();
  4503. $script_id = getProp($data, 'script_id');
  4504. $script_name = getProp($data, 'script_name');
  4505. $is_products = getProp($data, 'is_products');
  4506. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  4507. if ($script_id) {
  4508. $query->where('id', $script_id);
  4509. }
  4510. if ($is_products !== '') {
  4511. $query->where('is_products', $is_products);
  4512. }
  4513. if ($script_name) {
  4514. $query->where('script_name', 'like', "%{$script_name}%");
  4515. }
  4516. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  4517. return (array)$value;
  4518. })->toArray();
  4519. }
  4520. public function scriptInfo($data) {
  4521. $uid = Site::getUid();
  4522. $script_id = getProp($data, 'script_id');
  4523. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  4524. // ->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();
  4525. ->selectRaw('id as script_id, script_name')->first();
  4526. if (!$script) Utils::throwError('20003:该剧本不存在!');
  4527. $script = (array)$script;
  4528. // 获取分集组信息
  4529. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  4530. ->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')
  4531. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  4532. $value = (array)$value;
  4533. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  4534. return (array)$value;
  4535. })->toArray();
  4536. $script['group'] = $groups;
  4537. return $script;
  4538. }
  4539. public function createScript($data) {
  4540. $script_name = getProp($data, 'script_name');
  4541. $uid = Site::getUid(); // 获取当前用户ID
  4542. $cpid = Site::getCpid(); // 获取当前公司组ID
  4543. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  4544. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  4545. $script_name .= '_'.date('YmdHis');
  4546. }
  4547. return DB::table('mp_scripts')->insertGetId([
  4548. 'script_name' => $script_name,
  4549. 'user_id' => $uid,
  4550. 'cpid' => $cpid,
  4551. 'created_at' => date('Y-m-d H:i:s'),
  4552. 'updated_at' => date('Y-m-d H:i:s')
  4553. ]);
  4554. }
  4555. public function editScript($data) {
  4556. $script_id = getProp($data, 'script_id');
  4557. $script_name = getProp($data, 'script_name');
  4558. $uid = Site::getUid(); // 获取当前用户ID
  4559. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  4560. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  4561. if ($id && (int)$id !== (int)$script_id) {
  4562. $script_name .= '_'.date('YmdHis');
  4563. }
  4564. return DB::table('mp_scripts')->where('id', $script_id)->update([
  4565. 'script_name' => $script_name,
  4566. 'updated_at' => date('Y-m-d H:i:s')
  4567. ]);
  4568. }
  4569. public function delScript($data) {
  4570. $script_id = getProp($data, 'script_id');
  4571. $uid = Site::getUid(); // 获取当前用户ID
  4572. if (!$script_id) Utils::throwError('20003:请选择剧本');
  4573. return DB::table('mp_scripts')->where('id', $script_id)->update([
  4574. 'is_deleted' => 1,
  4575. 'updated_at' => date('Y-m-d H:i:s')
  4576. ]);
  4577. }
  4578. public function createEpisode($data) {
  4579. $script_id = getProp($data, 'script_id');
  4580. $group_name = getProp($data, 'group_name');
  4581. $remark = getProp($data, 'remark');
  4582. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  4583. $uid = Site::getUid(); // 获取当前用户ID
  4584. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  4585. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  4586. $group_name .= '_'.date('YmdHis');
  4587. }
  4588. return DB::table('mp_script_episode_group')->insertGetId([
  4589. 'script_id' => $script_id,
  4590. 'group_name' => $group_name,
  4591. 'user_id' => $uid,
  4592. 'remark' => $remark,
  4593. 'created_at' => date('Y-m-d H:i:s'),
  4594. 'updated_at' => date('Y-m-d H:i:s')
  4595. ]);
  4596. }
  4597. public function editEpisode($data) {
  4598. $group_id = getProp($data, 'group_id');
  4599. $start_episode_number = getProp($data, 'start_episode_number');
  4600. $end_episode_number = getProp($data, 'end_episode_number');
  4601. $group_name = getProp($data, 'group_name');
  4602. $uid = Site::getUid(); // 获取当前用户ID
  4603. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  4604. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  4605. if ($id && (int)$id !== (int)$group_id) {
  4606. $group_name .= '_'.date('YmdHis');
  4607. }
  4608. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4609. 'group_name' => $group_name,
  4610. 'start_episode_number' => $start_episode_number,
  4611. 'end_episode_number' => $end_episode_number,
  4612. 'updated_at' => date('Y-m-d H:i:s')
  4613. ]);
  4614. }
  4615. public function delEpisode($data) {
  4616. $group_id = getProp($data, 'group_id');
  4617. $uid = Site::getUid(); // 获取当前用户ID
  4618. if (!$group_id) Utils::throwError('20003:请选择分集');
  4619. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4620. 'is_deleted' => 1,
  4621. 'updated_at' => date('Y-m-d H:i:s')
  4622. ]);
  4623. }
  4624. /**
  4625. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4626. *
  4627. * @param array $data 包含以下参数:
  4628. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4629. * - question: 用户问题(可选)
  4630. * - model: 使用的模型(r1 或 v3,默认 v3)
  4631. * @return \Generator 返回生成器,用于流式输出
  4632. */
  4633. public function generateEpisodes($data) {
  4634. // 文生文计费预检(special 档,每次调用扣 10)
  4635. $uid = Site::getUid();
  4636. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  4637. $script_id = getProp($data, 'script_id');
  4638. $group_id = getProp($data, 'group_id');
  4639. // $file = getProp($data, 'file');
  4640. $file = '';
  4641. $content = getProp($data, 'content', '');
  4642. // $bid = getProp($data, 'bid', 0);
  4643. $bid = 0;
  4644. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4645. if (!$group) {
  4646. Utils::throwError('20003:剧本分集不存在');
  4647. }
  4648. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  4649. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  4650. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  4651. $prompt = getProp($data, 'prompt');
  4652. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  4653. $model = getProp($data, 'model');
  4654. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4655. Utils::throwError('20003:该模型不存在!');
  4656. }
  4657. // 检查是否存在重叠的剧集序号范围
  4658. $exists_groups = DB::table('mp_script_episode_group')
  4659. ->where('script_id', $script_id)
  4660. ->where('id', '<>', $group_id) // 排除当前组
  4661. ->where('is_deleted', 0)
  4662. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4663. // 检查新范围是否与现有范围重叠
  4664. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4665. // 新范围的开始在现有范围内
  4666. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4667. ->where('end_episode_number', '>=', $start_episode_sequence);
  4668. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4669. // 新范围的结束在现有范围内
  4670. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4671. ->where('end_episode_number', '>=', $end_episode_sequence);
  4672. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4673. // 新范围完全包含现有范围
  4674. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4675. ->where('end_episode_number', '<=', $end_episode_sequence);
  4676. });
  4677. })
  4678. ->select('start_episode_number', 'end_episode_number')
  4679. ->get();
  4680. if ($exists_groups->isNotEmpty()) {
  4681. $conflict_ranges = [];
  4682. foreach ($exists_groups as $group) {
  4683. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4684. }
  4685. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4686. }
  4687. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4688. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4689. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4690. if ($model === 'deepseek-chat') {
  4691. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4692. $model = 'deepseek-v4-flash';
  4693. $thinkingMode = 'disabled';
  4694. } elseif ($model === 'deepseek-reasoner') {
  4695. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4696. $model = 'deepseek-v4-flash';
  4697. $thinkingMode = 'enabled';
  4698. }
  4699. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4700. if (!$script) {
  4701. Utils::throwError('20003:剧本不存在');
  4702. }
  4703. $content = getProp($group, 'content');
  4704. if (!$file && !$content && !$bid) {
  4705. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4706. }
  4707. // 提取文件内容
  4708. if ($file) {
  4709. $content = $this->extractFileContent($file);
  4710. if (!$content) {
  4711. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4712. }
  4713. } elseif ($bid) {
  4714. $content = $this->getContentByBid($bid);
  4715. if (!$content) {
  4716. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4717. }
  4718. } elseif ($content) {
  4719. $content = filterContent($content);
  4720. } elseif ($prompt) {
  4721. $content = filterContent($prompt);
  4722. } else {
  4723. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4724. }
  4725. // 构建消息
  4726. $messages = [
  4727. $this->sys_message,
  4728. [
  4729. 'role' => 'user',
  4730. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4731. ]
  4732. ];
  4733. $post_data = [
  4734. 'model' => $model,
  4735. 'messages' => $messages,
  4736. // 'max_tokens' => 8192,
  4737. 'temperature' => 0.7,
  4738. 'frequency_penalty' => 0,
  4739. 'presence_penalty' => 0,
  4740. 'thinking' => ['type' => $thinkingMode],
  4741. 'response_format' => ['type' => 'text'],
  4742. 'stream' => true
  4743. ];
  4744. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4745. // 根据模型类型选择调用方法
  4746. $fullContent = '';
  4747. $fullReasoningContent = '';
  4748. $usage = [];
  4749. $streamGenerator = $this->dispatchStreamByModel($post_data);
  4750. // 处理流式输出
  4751. foreach ($streamGenerator as $chunk) {
  4752. if (isset($chunk['type'])) {
  4753. if ($chunk['type'] === 'done') {
  4754. // 最终结果
  4755. $fullContent = $chunk['full_content'];
  4756. $fullReasoningContent = $chunk['full_reasoning'];
  4757. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4758. } else {
  4759. // 逐块yield数据
  4760. yield $chunk;
  4761. }
  4762. }
  4763. }
  4764. dLog('deepseek')->info('完整内容: '.$fullContent);
  4765. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4766. // 处理完整内容并返回最终结果
  4767. $script_arr = [];
  4768. if ($fullContent) {
  4769. $script_arr = extractScriptContent($fullContent);
  4770. }
  4771. logDB('deepseek', 'info', '解析内容', $script_arr);
  4772. if (!$script_arr['episodes']) {
  4773. Utils::throwError('20003:未生成剧本相关信息');
  4774. // yield [
  4775. // 'type' => 'done',
  4776. // 'script' => $script_arr,
  4777. // 'msg' => '未生成剧本相关信息',
  4778. // 'answer' => $fullContent,
  4779. // 'reasoning' => $fullReasoningContent,
  4780. // 'usage' => $usage
  4781. // ];
  4782. // return ;
  4783. }
  4784. try {
  4785. DB::beginTransaction();
  4786. // // 返回前保存剧本内容
  4787. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4788. // 'content' => $content,
  4789. // 'updated_at' => date('Y-m-d H:i:s')
  4790. // ]);
  4791. // if (!$boolen) {
  4792. // Utils::throwError('20003:保存剧本内容失败');
  4793. // }
  4794. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4795. // 'start_episode_number' => $start_episode_sequence,
  4796. // 'end_episode_number' => $end_episode_sequence,
  4797. // 'updated_at' => date('Y-m-d H:i:s')
  4798. // ]);
  4799. // if (!$boolen1) {
  4800. // Utils::throwError('20003:保存分集失败');
  4801. // }
  4802. $episode_content = '';
  4803. $episodes = [];
  4804. foreach ($script_arr['episodes'] as $item) {
  4805. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  4806. // $episodes[] = [
  4807. // 'script_id' => $script_id,
  4808. // 'episode_number' => $item['episode_number'],
  4809. // 'episode_name' => $item['episode_name'],
  4810. // 'episode_content' => $item['episode_content'],
  4811. // 'created_at' => date('Y-m-d H:i:s'),
  4812. // 'updated_at' => date('Y-m-d H:i:s'),
  4813. // ];
  4814. }
  4815. if ($episode_content) {
  4816. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4817. 'episode_content' => $episode_content,
  4818. 'updated_at' => date('Y-m-d H:i:s')
  4819. ]);
  4820. if (!$boolen2) {
  4821. Utils::throwError('20003:保存分集内容失败');
  4822. }
  4823. }else {
  4824. Utils::throwError('20003:分集剧本解析失败');
  4825. }
  4826. // 文生文成功计费(special 档):与落库同事务
  4827. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  4828. 'model' => $model,
  4829. 'script_id' => $script_id,
  4830. 'group_id' => $group_id,
  4831. 'source' => 'generateEpisodes',
  4832. ]);
  4833. }catch (\Exception $e) {
  4834. DB::rollBack();
  4835. Utils::throwError('20003:'.$e->getMessage());
  4836. }
  4837. DB::commit();
  4838. yield [
  4839. 'type' => 'done',
  4840. 'script' => $script_arr,
  4841. 'episode_content' => $episode_content,
  4842. 'answer' => $fullContent,
  4843. 'reasoning' => $fullReasoningContent,
  4844. 'usage' => $usage
  4845. ];
  4846. }
  4847. public function chatWithFileStream($data) {
  4848. // 剧本解析资产表计费预检(special 档)
  4849. $uid = Site::getUid();
  4850. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  4851. $script_id = getProp($data, 'script_id');
  4852. $group_id = getProp($data, 'group_id');
  4853. $file = getProp($data, 'file');
  4854. $content = getProp($data, 'content', '');
  4855. $bid = getProp($data, 'bid', 0);
  4856. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4857. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4858. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  4859. $prompt = getProp($data, 'prompt');
  4860. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4861. if (!empty($prompt)) {
  4862. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4863. }
  4864. $question = getProp($data, 'question', $baseQuestion);
  4865. $model = getProp($data, 'model');
  4866. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4867. Utils::throwError('20003:该模型不存在!');
  4868. }
  4869. // 检查是否存在重叠的剧集序号范围
  4870. $exists_groups = DB::table('mp_script_episode_group')
  4871. ->where('script_id', $script_id)
  4872. ->where('id', '<>', $group_id)
  4873. ->where('is_deleted', 0)
  4874. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4875. // 检查新范围是否与现有范围重叠
  4876. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4877. // 新范围的开始在现有范围内
  4878. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4879. ->where('end_episode_number', '>=', $start_episode_sequence);
  4880. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4881. // 新范围的结束在现有范围内
  4882. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4883. ->where('end_episode_number', '>=', $end_episode_sequence);
  4884. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4885. // 新范围完全包含现有范围
  4886. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4887. ->where('end_episode_number', '<=', $end_episode_sequence);
  4888. });
  4889. })
  4890. ->select('start_episode_number', 'end_episode_number')
  4891. ->get();
  4892. if ($exists_groups->isNotEmpty()) {
  4893. $conflict_ranges = [];
  4894. foreach ($exists_groups as $group) {
  4895. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4896. }
  4897. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4898. }
  4899. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4900. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4901. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4902. if ($model === 'deepseek-chat') {
  4903. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4904. $model = 'deepseek-v4-flash';
  4905. $thinkingMode = 'disabled';
  4906. } elseif ($model === 'deepseek-reasoner') {
  4907. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4908. $model = 'deepseek-v4-flash';
  4909. $thinkingMode = 'enabled';
  4910. }
  4911. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4912. if (!$script) {
  4913. Utils::throwError('20003:剧本不存在');
  4914. }
  4915. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4916. if (!$group) {
  4917. Utils::throwError('20003:剧本分集不存在');
  4918. }
  4919. if (!$file && !$content && !$bid) {
  4920. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4921. }
  4922. // 提取文件内容
  4923. if ($file) {
  4924. $content = $this->extractFileContent($file);
  4925. if (!$content) {
  4926. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4927. }
  4928. } elseif ($bid) {
  4929. $content = $this->getContentByBid($bid);
  4930. if (!$content) {
  4931. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4932. }
  4933. } elseif ($content) {
  4934. $content = filterContent($content);
  4935. } elseif ($prompt) {
  4936. $content = filterContent($prompt);
  4937. } else {
  4938. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4939. }
  4940. // 构建消息
  4941. $messages = [
  4942. [
  4943. 'role' => 'system',
  4944. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4945. 强制要求:\n
  4946. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4947. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4948. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  4949. 普通要求:\n
  4950. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  4951. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  4952. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  4953. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  4954. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  4955. 示例如下:\n
  4956. ###剧本名:西昆仑
  4957. ###故事梗概
  4958. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4959. ###剧本亮点
  4960. 亮点1:绝境奇药,生死一线
  4961. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4962. 亮点2:结拜兄妹,化解尴尬
  4963. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4964. 亮点3:纤发夺命,情愫暗涌
  4965. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4966. ###人物关系
  4967. 阿雪与梁萧之间存在兄妹之情。
  4968. ###核心矛盾
  4969. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4970. ###主体列表
  4971. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  4972. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  4973. 阴阳球:天地异宝,能化生精气,救人于危难。
  4974. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  4975. ###美术风格
  4976. 基础画风风格词:厚涂古风
  4977. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4978. ###场景列表
  4979. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  4980. [
  4981. 'role' => 'user',
  4982. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4983. ]
  4984. ];
  4985. $post_data = [
  4986. 'model' => $model,
  4987. 'messages' => $messages,
  4988. // 'max_tokens' => 8192,
  4989. 'temperature' => 0.7,
  4990. 'frequency_penalty' => 0,
  4991. 'presence_penalty' => 0,
  4992. 'thinking' => ['type' => $thinkingMode],
  4993. 'response_format' => ['type' => 'text'],
  4994. 'stream' => true
  4995. ];
  4996. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4997. // 根据模型类型选择调用方法
  4998. $fullContent = '';
  4999. $fullReasoningContent = '';
  5000. $usage = [];
  5001. $streamGenerator = $this->dispatchStreamByModel($post_data);
  5002. // 处理流式输出
  5003. foreach ($streamGenerator as $chunk) {
  5004. if (isset($chunk['type'])) {
  5005. if ($chunk['type'] === 'done') {
  5006. // 最终结果
  5007. $fullContent = $chunk['full_content'];
  5008. $fullReasoningContent = $chunk['full_reasoning'];
  5009. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5010. } else {
  5011. // 逐块yield数据
  5012. yield $chunk;
  5013. }
  5014. }
  5015. }
  5016. dLog('deepseek')->info('完整内容: '.$fullContent);
  5017. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  5018. // 处理完整内容并返回最终结果
  5019. $script_arr = [];
  5020. if ($fullContent) {
  5021. $script_arr = extractScriptContent($fullContent);
  5022. }
  5023. logDB('deepseek', 'info', '解析内容', $script_arr);
  5024. if (!$script_arr['roles']) {
  5025. Utils::throwError('20003:未生成剧本相关信息');
  5026. // yield [
  5027. // 'type' => 'done',
  5028. // 'script' => $script_arr,
  5029. // 'msg' => '未生成剧本相关信息',
  5030. // 'answer' => $fullContent,
  5031. // 'reasoning' => $fullReasoningContent,
  5032. // 'usage' => $usage
  5033. // ];
  5034. }
  5035. try {
  5036. DB::beginTransaction();
  5037. // // 返回前保存剧本内容
  5038. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  5039. // 'content' => $content,
  5040. // 'status' => '解析完成',
  5041. // 'updated_at' => date('Y-m-d H:i:s')
  5042. // ]);
  5043. // if (!$boolen) {
  5044. // Utils::throwError('20003:保存剧本内容失败');
  5045. // }
  5046. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  5047. 'start_episode_number' => $start_episode_sequence,
  5048. 'end_episode_number' => $end_episode_sequence,
  5049. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5050. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5051. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5052. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5053. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5054. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5055. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5056. 'status' => '解析完成',
  5057. 'content' => $content,
  5058. 'updated_at' => date('Y-m-d H:i:s')
  5059. ]);
  5060. if (!$boolen1) {
  5061. Utils::throwError('20003:保存分集失败');
  5062. }
  5063. // 剧本解析资产表成功计费(special 档):与落库同事务
  5064. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5065. 'model' => $model,
  5066. 'script_id' => $script_id,
  5067. 'group_id' => $group_id,
  5068. 'source' => 'chatWithFileStream',
  5069. ], 'special');
  5070. // $episodes = [];
  5071. // foreach ($script_arr['episodes'] as $item) {
  5072. // $episodes[] = [
  5073. // 'script_id' => $script_id,
  5074. // 'episode_number' => $item['episode_number'],
  5075. // 'episode_name' => $item['episode_name'],
  5076. // 'episode_content' => $item['episode_content'],
  5077. // 'created_at' => date('Y-m-d H:i:s'),
  5078. // 'updated_at' => date('Y-m-d H:i:s'),
  5079. // ];
  5080. // }
  5081. // if ($episodes) {
  5082. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  5083. // if (!$boolen2) {
  5084. // Utils::throwError('20003:保存分集内容失败');
  5085. // }
  5086. // }else {
  5087. // Utils::throwError('20003:分集剧本解析失败');
  5088. // }
  5089. }catch (\Exception $e) {
  5090. DB::rollBack();
  5091. Utils::throwError('20003:'.$e->getMessage());
  5092. }
  5093. DB::commit();
  5094. yield [
  5095. 'type' => 'done',
  5096. 'script' => $script_arr,
  5097. 'answer' => $fullContent,
  5098. 'reasoning' => $fullReasoningContent,
  5099. 'usage' => $usage
  5100. ];
  5101. }
  5102. /**
  5103. * 上传文件识别文字内容并与 DeepSeek 进行对话
  5104. *
  5105. * @param array $data 包含以下参数:
  5106. * - file: 上传的文件(UploadedFile 对象)或文件路径
  5107. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  5108. * - model: 使用的模型(r1 或 v3,默认 v3)
  5109. * @return array
  5110. */
  5111. public function chatWithFile($data) {
  5112. // 剧本解析资产表计费预检(special 档)
  5113. $uid = Site::getUid();
  5114. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  5115. $script_id = getProp($data, 'script_id');
  5116. $file = getProp($data, 'file');
  5117. $content = getProp($data, 'content', '');
  5118. $bid = getProp($data, 'bid', 0);
  5119. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  5120. $total_episode_num = getProp($data, 'total_episode_num', 30);
  5121. $prompt = getProp($data, 'prompt');
  5122. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  5123. if (!empty($prompt)) {
  5124. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  5125. }
  5126. $question = getProp($data, 'question', $baseQuestion);
  5127. // 处理文本模型
  5128. $model = getProp($data, 'model');
  5129. if (!$model) {
  5130. // 用户没有输入,使用默认值
  5131. $model = 'doubao-seed-2-0-mini-260215';
  5132. }
  5133. // 验证模型是否在可用模型表中
  5134. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5135. $model = 'doubao-seed-2-0-mini-260215';
  5136. }
  5137. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5138. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5139. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5140. if ($model === 'deepseek-chat') {
  5141. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5142. $model = 'deepseek-v4-flash';
  5143. $thinkingMode = 'disabled';
  5144. } elseif ($model === 'deepseek-reasoner') {
  5145. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5146. $model = 'deepseek-v4-flash';
  5147. $thinkingMode = 'enabled';
  5148. }
  5149. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  5150. if (!$script) {
  5151. Utils::throwError('20003:剧本不存在');
  5152. }
  5153. if (!$file && !$content && !$bid) {
  5154. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5155. }
  5156. // 提取文件内容
  5157. if ($file) {
  5158. $content = $this->extractFileContent($file);
  5159. if (!$content) {
  5160. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5161. }
  5162. } elseif ($bid) {
  5163. $content = $this->getContentByBid($bid);
  5164. if (!$content) {
  5165. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5166. }
  5167. } elseif ($content) {
  5168. $content = filterContent($content);
  5169. } elseif ($prompt) {
  5170. $content = filterContent($prompt);
  5171. } else {
  5172. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5173. }
  5174. // 构建消息
  5175. $messages = [
  5176. $this->sys_message,
  5177. [
  5178. 'role' => 'user',
  5179. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  5180. ]
  5181. ];
  5182. $post_data = [
  5183. 'model' => $model,
  5184. 'messages' => $messages,
  5185. // 'max_tokens' => 8192,
  5186. 'temperature' => 0.7,
  5187. 'frequency_penalty' => 0,
  5188. 'presence_penalty' => 0,
  5189. 'thinking' => ['type' => $thinkingMode],
  5190. 'response_format' => ['type' => 'text'],
  5191. 'stream' => false
  5192. ];
  5193. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5194. // 根据模型类型选择调用方法
  5195. $fullContent = '';
  5196. $usage = [];
  5197. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  5198. if (is_array($chatResult)) {
  5199. $fullContent = $chatResult['fullContent'];
  5200. $usage = $chatResult['usage'];
  5201. }
  5202. $script_arr = [];
  5203. // 处理结果
  5204. if ($fullContent) {
  5205. $script_arr = extractScriptContent($fullContent);
  5206. }
  5207. // 返回前保存剧本内容
  5208. DB::table('mp_scripts')->where('id', $script_id)->update([
  5209. 'content' => $content,
  5210. 'updated_at' => date('Y-m-d H:i:s')
  5211. ]);
  5212. // 剧本解析资产表成功计费(special 档):同时记录积分与 token 明细
  5213. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5214. 'model' => $model,
  5215. 'script_id' => $script_id,
  5216. 'source' => 'chatWithFile',
  5217. ], 'special');
  5218. return [
  5219. 'script' => $script_arr,
  5220. 'answer' => $fullContent,
  5221. 'usage' => $usage
  5222. ];
  5223. }
  5224. public function getEpisodeContent($data) {
  5225. $group_id = getProp($data, 'group_id');
  5226. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  5227. }
  5228. public function saveEpisodeContent($data) {
  5229. $script_id = getProp($data, 'script_id');
  5230. $group_id = getProp($data, 'group_id');
  5231. $start_episode_sequence = getProp($data, 'start_episode_number');
  5232. $end_episode_sequence = getProp($data, 'end_episode_number');
  5233. // 检查是否存在重叠的剧集序号范围
  5234. $exists_groups = DB::table('mp_script_episode_group')
  5235. ->where('script_id', $script_id)
  5236. ->where('id', '<>', $group_id) // 排除当前组
  5237. ->where('is_deleted', 0)
  5238. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  5239. // 检查新范围是否与现有范围重叠
  5240. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5241. // 新范围的开始在现有范围内
  5242. $q->where('start_episode_number', '<=', $start_episode_sequence)
  5243. ->where('end_episode_number', '>=', $start_episode_sequence);
  5244. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5245. // 新范围的结束在现有范围内
  5246. $q->where('start_episode_number', '<=', $end_episode_sequence)
  5247. ->where('end_episode_number', '>=', $end_episode_sequence);
  5248. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5249. // 新范围完全包含现有范围
  5250. $q->where('start_episode_number', '>=', $start_episode_sequence)
  5251. ->where('end_episode_number', '<=', $end_episode_sequence);
  5252. });
  5253. })
  5254. ->select('start_episode_number', 'end_episode_number')
  5255. ->get();
  5256. if ($exists_groups->isNotEmpty()) {
  5257. $conflict_ranges = [];
  5258. foreach ($exists_groups as $group) {
  5259. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  5260. }
  5261. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  5262. }
  5263. $episode_content = getProp($data, 'episode_content');
  5264. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  5265. 'content' => $episode_content,
  5266. 'start_episode_number' => $start_episode_sequence,
  5267. 'end_episode_number' => $end_episode_sequence,
  5268. 'updated_at' => date('Y-m-d H:i:s')
  5269. ]);
  5270. $script_arr =getProp($data, 'script', []);
  5271. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  5272. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  5273. $script_id = getProp($data, 'script_id');
  5274. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  5275. try {
  5276. DB::beginTransaction();
  5277. $update_data = [
  5278. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5279. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5280. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5281. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5282. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5283. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5284. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5285. 'status' => 3,
  5286. 'start_episode_sequence' => $start_episode_sequence,
  5287. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  5288. 'episode_num' => count($script_arr['episodes']),
  5289. 'updated_at' => date('Y-m-d H:i:s')
  5290. ];
  5291. // 保存剧本内容
  5292. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  5293. if (!$boolen) {
  5294. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  5295. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  5296. Utils::throwError('20003:剧本内容保存失败');
  5297. }
  5298. // 保存分集内容
  5299. // 删除历史分集内容
  5300. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  5301. $episodes = [];
  5302. $sequence = 1;
  5303. foreach ($script_arr['episodes'] as $episode) {
  5304. $segment_number = 1;
  5305. foreach($episode['segments'] as $segment) {
  5306. $episodes[] = [
  5307. 'script_id' => $script_id,
  5308. 'episode_number' => $episode['episode_number'],
  5309. 'title' => $episode['title'],
  5310. // 'content' => $episode['content'],
  5311. 'content' => '',
  5312. 'segment_number' => $segment_number,
  5313. 'segment_content' => $segment['segment_content'],
  5314. 'sequence' => $sequence,
  5315. 'created_at' => date('Y-m-d H:i:s'),
  5316. 'updated_at' => date('Y-m-d H:i:s')
  5317. ];
  5318. $sequence++;
  5319. $segment_number++;
  5320. }
  5321. }
  5322. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  5323. if (!$boolen2) {
  5324. dLog('deepseek')->info('分集内容保存失败', $episodes);
  5325. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  5326. Utils::throwError('20003:分集内容保存失败');
  5327. }
  5328. } catch (\Exception $e) {
  5329. DB::rollBack();
  5330. Utils::throwError('20003:'.$e->getMessage());
  5331. }
  5332. DB::commit();
  5333. return true;
  5334. }
  5335. public function getBookContent($data) {
  5336. $bid = getProp($data, 'bid');
  5337. $start_sequence = getProp($data, 'start_sequence');
  5338. $end_sequence = getProp($data, 'end_sequence');
  5339. $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])
  5340. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  5341. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  5342. return $return_content;
  5343. }
  5344. public function exportScript($data) {
  5345. $filename = getProp($data, 'filename');
  5346. $script_id = getProp($data, 'script_id');
  5347. $group_id = getProp($data, 'group_id');
  5348. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  5349. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  5350. if (!$script) Utils::throwError('20003:该剧本不存在!');
  5351. $script = (array)$script;
  5352. // 获取分集组信息
  5353. if ($group_id) {
  5354. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  5355. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  5356. ->get()->map(function($value) {
  5357. return (array)$value;
  5358. })->toArray();
  5359. }else {
  5360. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  5361. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  5362. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  5363. return (array)$value;
  5364. })->toArray();
  5365. }
  5366. if (!$groups) Utils::throwError('20003:分集不存在');
  5367. $script['group'] = $groups;
  5368. $export_type = getProp($data, 'export_type', 'txt');
  5369. // 生成文件名
  5370. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  5371. // 根据导出类型生成不同格式的文件
  5372. switch ($export_type) {
  5373. case 'txt':
  5374. return $this->exportScriptAsTxt($script, $filename);
  5375. case 'pdf':
  5376. return $this->exportScriptAsPdf($script, $filename);
  5377. default:
  5378. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  5379. }
  5380. }
  5381. /**
  5382. * 导出剧本为TXT格式
  5383. */
  5384. private function exportScriptAsTxt($script, $filename) {
  5385. // 构建TXT内容
  5386. $content = $this->buildScriptContent($script);
  5387. // 设置响应头,直接下载
  5388. header('Content-Type: text/plain; charset=utf-8');
  5389. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  5390. header('Content-Length: ' . strlen($content));
  5391. // 输出内容并结束
  5392. echo $content;
  5393. exit();
  5394. }
  5395. /**
  5396. * 导出剧本为PDF格式
  5397. */
  5398. private function exportScriptAsPdf($script, $filename) {
  5399. // 使用HTML转PDF的方式来更好地支持中文
  5400. $htmlContent = $this->buildScriptHtmlForPdf($script);
  5401. // 创建PDF实例
  5402. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  5403. // 设置文档信息
  5404. $pdf->SetCreator('剧本导出系统');
  5405. $pdf->SetAuthor('系统');
  5406. $pdf->SetTitle($script['script_name']);
  5407. $pdf->SetSubject('剧本导出');
  5408. // 设置边距
  5409. $pdf->SetMargins(15, 15, 15);
  5410. $pdf->SetAutoPageBreak(TRUE, 15);
  5411. // 添加页面
  5412. $pdf->AddPage();
  5413. // 注册并使用 simsun.ttf 字体
  5414. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  5415. // 使用HTML内容生成PDF
  5416. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  5417. // 直接输出PDF文件供下载
  5418. header('Content-Type: application/pdf');
  5419. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  5420. // 直接输出PDF内容
  5421. $pdf->Output($filename . '.pdf', 'D');
  5422. exit();
  5423. }
  5424. /**
  5425. * 构建用于PDF的HTML内容
  5426. */
  5427. private function buildScriptHtmlForPdf($script) {
  5428. $html = '<style>
  5429. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  5430. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  5431. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  5432. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  5433. .info { margin-bottom: 8px; }
  5434. .group { margin-bottom: 30px; page-break-inside: avoid; }
  5435. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  5436. .segment { margin-bottom: 10px; margin-left: 20px; }
  5437. .episode-content { white-space: pre-wrap; }
  5438. </style>';
  5439. // 标题
  5440. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  5441. // 处理分组数据
  5442. if (!empty($script['group']) && is_array($script['group'])) {
  5443. $groups = (array)$script['group'];
  5444. foreach ($groups as $group) {
  5445. $html .= '<div class="group">';
  5446. // 分组标题
  5447. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  5448. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  5449. // 故事梗概
  5450. if (!empty($group['intro'])) {
  5451. $html .= '<h3>故事梗概</h3>';
  5452. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  5453. }
  5454. // 剧本亮点
  5455. if (!empty($group['highlights'])) {
  5456. $html .= '<h3>剧本亮点</h3>';
  5457. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  5458. }
  5459. // 人物关系
  5460. if (!empty($group['role_relationship'])) {
  5461. $html .= '<h3>人物关系</h3>';
  5462. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  5463. }
  5464. // 核心矛盾
  5465. if (!empty($group['core_contradiction'])) {
  5466. $html .= '<h3>核心矛盾</h3>';
  5467. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  5468. }
  5469. // 主体列表
  5470. if (!empty($group['roles']) && is_array($group['roles'])) {
  5471. $html .= '<h3>主体列表</h3>';
  5472. $html .= '<ul>';
  5473. foreach ($group['roles'] as $role) {
  5474. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  5475. }
  5476. $html .= '</ul>';
  5477. }
  5478. // 美术风格
  5479. if (!empty($group['art_style'])) {
  5480. $html .= '<h3>美术风格</h3>';
  5481. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  5482. }
  5483. // 场景列表
  5484. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  5485. $html .= '<h3>场景列表</h3>';
  5486. $html .= '<ul>';
  5487. foreach ($group['scenes'] as $scene) {
  5488. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  5489. }
  5490. $html .= '</ul>';
  5491. }
  5492. // 分集剧本
  5493. if (!empty($group['episode_content'])) {
  5494. $html .= '<h3>分集剧本</h3>';
  5495. // 去除零宽字符和其他不可见字符
  5496. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  5497. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  5498. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  5499. }
  5500. $html .= '</div>';
  5501. }
  5502. }
  5503. return $html;
  5504. }
  5505. /**
  5506. * 构建PDF内容
  5507. */
  5508. private function buildPdfContent($pdf, $script) {
  5509. // 标题
  5510. $pdf->SetFont('dejavusans', 'B', 18);
  5511. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  5512. $pdf->Ln(5);
  5513. // 基本信息
  5514. $pdf->SetFont('dejavusans', '', 12);
  5515. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  5516. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  5517. $pdf->Ln(5);
  5518. // 剧本简介
  5519. if (!empty($script['intro'])) {
  5520. $pdf->SetFont('dejavusans', 'B', 14);
  5521. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  5522. $pdf->SetFont('dejavusans', '', 12);
  5523. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  5524. $pdf->Ln(3);
  5525. }
  5526. // 亮点
  5527. if (!empty($script['highlights'])) {
  5528. $pdf->SetFont('dejavusans', 'B', 14);
  5529. $pdf->Cell(0, 10, '亮点', 0, 1);
  5530. $pdf->SetFont('dejavusans', '', 12);
  5531. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  5532. $pdf->Ln(3);
  5533. }
  5534. // 核心矛盾
  5535. if (!empty($script['core_contradiction'])) {
  5536. $pdf->SetFont('dejavusans', 'B', 14);
  5537. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  5538. $pdf->SetFont('dejavusans', '', 12);
  5539. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  5540. $pdf->Ln(3);
  5541. }
  5542. // 艺术风格
  5543. if (!empty($script['art_style'])) {
  5544. $pdf->SetFont('dejavusans', 'B', 14);
  5545. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  5546. $pdf->SetFont('dejavusans', '', 12);
  5547. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  5548. $pdf->Ln(3);
  5549. }
  5550. // 备注
  5551. if (!empty($script['remark'])) {
  5552. $pdf->SetFont('dejavusans', 'B', 14);
  5553. $pdf->Cell(0, 10, '备注', 0, 1);
  5554. $pdf->SetFont('dejavusans', '', 12);
  5555. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  5556. $pdf->Ln(3);
  5557. }
  5558. // 角色列表
  5559. if (!empty($script['roles']) && is_array($script['roles'])) {
  5560. $pdf->SetFont('dejavusans', 'B', 14);
  5561. $pdf->Cell(0, 10, '角色列表', 0, 1);
  5562. $pdf->SetFont('dejavusans', '', 12);
  5563. foreach ($script['roles'] as $index => $role) {
  5564. if (is_array($role) || is_object($role)) {
  5565. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  5566. } else {
  5567. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  5568. }
  5569. }
  5570. $pdf->Ln(3);
  5571. }
  5572. // 角色关系
  5573. if (!empty($script['role_relationship'])) {
  5574. $pdf->SetFont('dejavusans', 'B', 14);
  5575. $pdf->Cell(0, 10, '角色关系', 0, 1);
  5576. $pdf->SetFont('dejavusans', '', 12);
  5577. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  5578. $pdf->Ln(3);
  5579. }
  5580. // 场景列表
  5581. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  5582. $pdf->SetFont('dejavusans', 'B', 14);
  5583. $pdf->Cell(0, 10, '场景列表', 0, 1);
  5584. $pdf->SetFont('dejavusans', '', 12);
  5585. foreach ($script['scenes'] as $index => $scene) {
  5586. if (is_array($scene) || is_object($scene)) {
  5587. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  5588. } else {
  5589. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  5590. }
  5591. }
  5592. $pdf->Ln(5);
  5593. }
  5594. // 分集内容
  5595. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  5596. $pdf->SetFont('dejavusans', 'B', 16);
  5597. $pdf->Cell(0, 12, '分集内容', 0, 1);
  5598. $pdf->Ln(3);
  5599. foreach ($script['episodes'] as $episode) {
  5600. // 检查是否需要新页面
  5601. if ($pdf->GetY() > 250) {
  5602. $pdf->AddPage();
  5603. }
  5604. $pdf->SetFont('dejavusans', 'B', 14);
  5605. $episodeTitle = '第' . $episode['episode_number'] . '集';
  5606. if (!empty($episode['title'])) {
  5607. $episodeTitle .= ':' . $episode['title'];
  5608. }
  5609. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  5610. // 处理分段内容
  5611. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  5612. $pdf->SetFont('dejavusans', '', 12);
  5613. foreach ($episode['segments'] as $segment) {
  5614. if (!empty($segment['segment_content'])) {
  5615. // 如果有分段编号,显示分段标题
  5616. if (!empty($segment['segment_number'])) {
  5617. $pdf->SetFont('dejavusans', 'B', 12);
  5618. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  5619. $pdf->SetFont('dejavusans', '', 12);
  5620. }
  5621. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  5622. $pdf->Ln(2);
  5623. }
  5624. }
  5625. }
  5626. $pdf->Ln(5);
  5627. }
  5628. }
  5629. }
  5630. /**
  5631. * 构建剧本文本内容
  5632. */
  5633. private function buildScriptContent($script) {
  5634. $content = '';
  5635. $groups = $script['group'];
  5636. $groups = (array)$groups;
  5637. foreach ($groups as $group) {
  5638. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  5639. // 剧本基本信息
  5640. if (!empty($group['intro'])) {
  5641. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  5642. }
  5643. if (!empty($group['highlights'])) {
  5644. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  5645. }
  5646. if (!empty($group['role_relationship'])) {
  5647. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  5648. }
  5649. if (!empty($group['core_contradiction'])) {
  5650. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  5651. }
  5652. if (!empty($group['roles']) && is_array($group['roles'])) {
  5653. $content .= "###主体列表\n";
  5654. foreach ($group['roles'] as $role) {
  5655. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  5656. }
  5657. $content .= "\n\n";
  5658. }
  5659. if (!empty($group['art_style'])) {
  5660. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  5661. }
  5662. // 场景信息
  5663. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  5664. $content .= "###场景列表\n";
  5665. foreach ($group['scenes'] as $scene) {
  5666. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  5667. }
  5668. $content .= "\n\n";
  5669. }
  5670. // 分集内容
  5671. if (!empty($group['episode_content'])) {
  5672. $content .= "###分集剧本\n";
  5673. $content .= $group['episode_content'];
  5674. // foreach ($script['episodes'] as $episode) {
  5675. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  5676. // // if (!empty($episode['episode_name'])) {
  5677. // // $content .= ":" . $episode['episode_name'];
  5678. // // }
  5679. // // $content .= "\n";
  5680. // $content .= $episode['episode_content'] . "\n\n";
  5681. // }
  5682. }
  5683. }
  5684. return $content;
  5685. }
  5686. /**
  5687. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  5688. *
  5689. * @param array $data 包含以下参数:
  5690. * - file: 上传的文件(UploadedFile 对象)或文件路径
  5691. * - question: 用户问题(可选)
  5692. * - model: 使用的模型(r1 或 v3,默认 v3)
  5693. * @return \Generator 返回生成器,用于流式输出
  5694. */
  5695. public function addChat($data) {
  5696. $uid = Site::getUid();
  5697. $anime_id = getProp($data, 'anime_id');
  5698. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5699. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5700. if (!$anime) Utils::throwError('20003:对话不存在');
  5701. $file = getProp($data, 'file');
  5702. $content = getProp($data, 'content', '');
  5703. $bid = getProp($data, 'bid', 0);
  5704. $script_id = getProp($data, 'script_id', 0);
  5705. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5706. $prompt = getProp($data, 'prompt');
  5707. $user_anime_name = getProp($anime, 'anime_name');
  5708. // 处理文本模型
  5709. $model = getProp($data, 'model');
  5710. if (!$model) {
  5711. // 用户没有输入,从anime表获取
  5712. $model = getProp($anime, 'model');
  5713. if (!$model) {
  5714. // anime表也没有,使用默认值
  5715. $model = 'doubao-seed-2-0-mini-260215';
  5716. }
  5717. }
  5718. // 验证模型是否在可用模型表中
  5719. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5720. $model = 'doubao-seed-2-0-mini-260215';
  5721. }
  5722. $is_multi = getProp($anime, 'is_multi');
  5723. $is_single = (int)$is_multi !== 1;
  5724. // 积分余额预检(仅单剧集模式收费)
  5725. if ($is_single) {
  5726. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5727. }
  5728. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5729. if ($prompt) {
  5730. $question .= "本次修改要求如下:\n{$prompt}";
  5731. }
  5732. // if (!$file && !$content && !$bid) {
  5733. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5734. // }
  5735. // 提取文件内容
  5736. if ($file) {
  5737. $content = $this->extractFileContent($file);
  5738. if (!$content) {
  5739. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5740. }
  5741. } elseif ($script_id) {
  5742. $content = $this->getContentByScriptId($script_id);
  5743. if (!$content) {
  5744. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5745. }
  5746. } elseif ($bid) {
  5747. $content = $this->getContentByBid($bid);
  5748. if (!$content) {
  5749. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5750. }
  5751. } elseif ($content) {
  5752. $content = filterContent($content);
  5753. } else {
  5754. $content = getProp($anime, 'content');
  5755. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5756. $need_generate_content = true;
  5757. }
  5758. }
  5759. // 美术风格
  5760. $input_art_style = getProp($data, 'art_style');
  5761. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5762. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5763. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5764. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5765. 中年女:邻居阿姨
  5766. 老年男:幽默大爷
  5767. 老年女:婆婆
  5768. 萌娃:奶气萌娃";
  5769. // 判断是否需要生成原文内容
  5770. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5771. // 如果需要生成原文内容,添加额外的要求
  5772. $content_generation_requirement = $need_generate_content
  5773. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5774. : "";
  5775. // 美术风格
  5776. if (!$mappedArtStyle) {
  5777. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5778. }else {
  5779. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5780. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5781. }else {
  5782. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5783. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5784. }
  5785. }
  5786. $systemPrompt = $is_single
  5787. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5788. 强制要求:
  5789. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5790. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5791. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5792. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5793. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5794. 普通要求:
  5795. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5796. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5797. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  5798. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5799. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5800. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5801. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5802. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5803. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5804. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5805. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5806. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5807. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5808. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5809. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5810. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5811. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5812. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5813. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5814. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5815. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5816. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5817. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5818. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5819. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5820. 5.{$mappedArtStyle_prompt}\n\n
  5821. 示例如下:\n
  5822. ###剧本名:西昆仑
  5823. ###故事梗概
  5824. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5825. ###剧本亮点
  5826. 亮点1:绝境奇药,生死一线
  5827. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5828. 亮点2:结拜兄妹,化解尴尬
  5829. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5830. 亮点3:纤发夺命,情愫暗涌
  5831. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5832. ###人物关系
  5833. 阿雪与梁萧之间存在兄妹之情。
  5834. ###核心矛盾
  5835. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5836. ###主体列表
  5837. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5838. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5839. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5840. 姿态:站立。}{{甜心小美}}
  5841. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5842. 全景,正面拍摄,青年女性,亚洲人。
  5843. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5844. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5845. 姿态:站立。}{{阳光青年}}
  5846. ###美术风格
  5847. 基础画风风格词:厚涂古风
  5848. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5849. ###场景列表
  5850. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5851. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5852. 无人物。}
  5853. ###分镜剧本
  5854. ##第1幕:徐家老旧厨房 白天 室内
  5855. 分镜1
  5856. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5857. 场景:徐家老旧厨房
  5858. 构图设计:全景,低角度仰视
  5859. 运镜调度:手持拍摄
  5860. 配音角色:旁白
  5861. 出镜角色:许芸-校服装、徐母
  5862. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5863. 画面类型:普通画面
  5864. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5865. 分镜2
  5866. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5867. 场景:徐家老旧厨房
  5868. 构图设计:近景,徐母面部特写
  5869. 运镜调度:固定镜头
  5870. 配音角色:徐母
  5871. 出镜角色:徐母
  5872. 台词内容:问我夜不归宿死哪儿去了。
  5873. 画面类型:对口型
  5874. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5875. ##第2幕:徐家简陋客厅 黄昏 室内
  5876. 分镜3
  5877. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5878. 场景:徐家简陋客厅
  5879. 构图设计:全景,景深虚化
  5880. 运镜调度:固定镜头
  5881. 配音角色:旁白
  5882. 出镜角色:无
  5883. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5884. 画面类型:普通画面
  5885. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5886. 分镜4
  5887. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5888. 场景:徐家简陋客厅
  5889. 构图设计:特写,火车票
  5890. 运镜调度:固定镜头
  5891. 配音角色:旁白
  5892. 出镜角色:无
  5893. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5894. 画面类型:普通画面
  5895. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5896. "
  5897. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5898. 强制要求:\n
  5899. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5900. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5901. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5902. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5903. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5904. 普通要求:\n
  5905. 1.剧本名(必须生成)必须与文档内容高度相关
  5906. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5907. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5908. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5909. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5910. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5911. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5912. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5913. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5914. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5915. 4.{$mappedArtStyle_prompt}\n\n
  5916. 示例如下:\n
  5917. ###剧本名:西昆仑
  5918. ###故事梗概
  5919. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5920. ###剧本亮点
  5921. 亮点1:绝境奇药,生死一线
  5922. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5923. 亮点2:结拜兄妹,化解尴尬
  5924. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5925. 亮点3:纤发夺命,情愫暗涌
  5926. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5927. ###人物关系
  5928. 阿雪与梁萧之间存在兄妹之情。
  5929. ###核心矛盾
  5930. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5931. ###主体列表
  5932. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5933. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5934. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5935. 姿态:站立。}{{甜心小美}}
  5936. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5937. 全景,正面拍摄,青年女性,亚洲人。
  5938. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5939. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5940. 姿态:站立。}{{阳光青年}}
  5941. ###美术风格
  5942. 基础画风风格词:厚涂古风
  5943. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5944. ###场景列表
  5945. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5946. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5947. 无人物。}";
  5948. // 构建消息
  5949. $messages = [
  5950. [
  5951. 'role' => 'system',
  5952. 'content' => $systemPrompt
  5953. ],
  5954. [
  5955. 'role' => 'user',
  5956. 'content' => "以下是文档内容:
  5957. {$content}
  5958. 用户问题:
  5959. {$question}"
  5960. ]
  5961. ];
  5962. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5963. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5964. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5965. if ($model === 'deepseek-chat') {
  5966. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5967. $model = 'deepseek-v4-flash';
  5968. $thinkingMode = 'disabled';
  5969. } elseif ($model === 'deepseek-reasoner') {
  5970. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5971. $model = 'deepseek-v4-flash';
  5972. $thinkingMode = 'enabled';
  5973. }
  5974. $post_data = [
  5975. 'model' => $model,
  5976. 'messages' => $messages,
  5977. // 'max_tokens' => 8192,
  5978. 'temperature' => 0.7,
  5979. 'frequency_penalty' => 0,
  5980. 'presence_penalty' => 0,
  5981. 'response_format' => ['type' => 'text'],
  5982. 'thinking' => ['type'=>$thinkingMode],
  5983. 'stream' => true // 启用流式输出
  5984. ];
  5985. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5986. // 根据模型类型选择调用方法
  5987. $fullContent = '';
  5988. $fullReasoningContent = '';
  5989. $usage = [];
  5990. try {
  5991. $streamGenerator = $this->dispatchStreamByModel($post_data);
  5992. // 验证返回值类型
  5993. if (!is_iterable($streamGenerator)) {
  5994. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5995. dLog('deepseek')->error('addChat流式生成器无效', [
  5996. 'generator_type' => $errorType,
  5997. 'model' => $model,
  5998. 'anime_id' => $anime_id
  5999. ]);
  6000. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  6001. 'type' => $errorType,
  6002. 'model' => $model
  6003. ]);
  6004. yield [
  6005. 'type' => 'error',
  6006. 'script' => [],
  6007. 'episode' => [],
  6008. 'answer' => '',
  6009. 'reasoning' => '',
  6010. 'usage' => [],
  6011. 'error' => '接口返回数据异常,请重新请求'
  6012. ];
  6013. return;
  6014. }
  6015. // 处理流式输出
  6016. foreach ($streamGenerator as $chunk) {
  6017. if (isset($chunk['type'])) {
  6018. if ($chunk['type'] === 'done') {
  6019. // 最终结果
  6020. $fullContent = $chunk['full_content'];
  6021. $fullReasoningContent = $chunk['full_reasoning'];
  6022. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6023. } else {
  6024. // 逐块yield数据
  6025. yield $chunk;
  6026. }
  6027. }
  6028. }
  6029. } catch (\Exception $e) {
  6030. // 解析上游错误详情(如 content_filter),便于日志定位与前端提示
  6031. $upstream_error = $this->resolveGptUpstreamError($e);
  6032. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  6033. 'model' => $model,
  6034. 'anime_id' => $anime_id,
  6035. 'upstream_status' => $upstream_error['status'],
  6036. 'upstream_code' => $upstream_error['code'],
  6037. 'upstream_body' => $upstream_error['body'],
  6038. 'trace' => $e->getTraceAsString()
  6039. ]);
  6040. logDB('deepseek', 'error', 'addChat流式处理失败', [
  6041. 'error' => $e->getMessage(),
  6042. 'model' => $model,
  6043. 'upstream_status' => $upstream_error['status'],
  6044. 'upstream_code' => $upstream_error['code'],
  6045. 'upstream_body' => $upstream_error['body']
  6046. ]);
  6047. yield [
  6048. 'type' => 'error',
  6049. 'script' => [],
  6050. 'episode' => [],
  6051. 'answer' => '',
  6052. 'reasoning' => '',
  6053. 'usage' => [],
  6054. 'error' => $this->buildChatErrorForUser($e, $upstream_error)
  6055. ];
  6056. return;
  6057. }
  6058. dLog('deepseek')->info('完整内容: '.$fullContent);
  6059. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6060. // 处理完整内容并返回最终结果
  6061. $script_arr = [];
  6062. if ($fullContent) {
  6063. $script_arr = handleScriptContent($fullContent);
  6064. dLog('deepseek')->info('解析内容', $script_arr);
  6065. logDB('deepseek', 'info', '解析内容', $script_arr);
  6066. }
  6067. if (empty($script_arr['roles'])) {
  6068. // 未生成剧本相关内容,保存对话记录并返回提示
  6069. dLog('deepseek')->info('未生成剧本相关的内容');
  6070. try {
  6071. DB::beginTransaction();
  6072. $now = date('Y-m-d H:i:s');
  6073. // 保存对话记录
  6074. $records = [
  6075. [
  6076. 'uid' => $uid,
  6077. 'anime_id' => $anime_id,
  6078. 'sequence' => 0,
  6079. 'role' => 'user',
  6080. 'content' => $prompt,
  6081. 'created_at' => $now,
  6082. 'updated_at' => $now
  6083. ],
  6084. [
  6085. 'uid' => $uid,
  6086. 'anime_id' => $anime_id,
  6087. 'sequence' => 0,
  6088. 'role' => 'assistant',
  6089. // 'content' => $fullContent,
  6090. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  6091. 'created_at' => $now,
  6092. 'updated_at' => $now
  6093. ]
  6094. ];
  6095. DB::table('mp_anime_records')->insert($records);
  6096. DB::commit();
  6097. } catch (\Exception $e) {
  6098. DB::rollBack();
  6099. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6100. }
  6101. yield [
  6102. 'type' => 'done',
  6103. 'script' => [],
  6104. 'episode' => [],
  6105. 'answer' => $fullContent,
  6106. 'reasoning' => $fullReasoningContent,
  6107. 'usage' => $usage,
  6108. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6109. ];
  6110. return;
  6111. }
  6112. // 如果需要生成原文内容,从script_arr中提取
  6113. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6114. $content = $script_arr['content'];
  6115. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  6116. if (!$content) {
  6117. yield [
  6118. 'type' => 'done',
  6119. 'script' => [],
  6120. 'episode' => [],
  6121. 'answer' => $fullContent,
  6122. 'reasoning' => $fullReasoningContent,
  6123. 'usage' => $usage,
  6124. 'error' => '未生成剧本内容,请调整提示词再试'
  6125. ];
  6126. return;
  6127. }
  6128. }
  6129. // 替换美术风格
  6130. if ($mappedArtStyle !== '') {
  6131. $script_arr['art_style'] = $mappedArtStyle;
  6132. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6133. }
  6134. // 新建动漫
  6135. if ($user_anime_name == '新剧本策划') {
  6136. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6137. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6138. // if (!$anime_name) {
  6139. // // 未识别到剧本名,保存对话记录并返回提示
  6140. // dLog('deepseek')->info('未能识别到剧本名称');
  6141. // try {
  6142. // DB::beginTransaction();
  6143. // $now = date('Y-m-d H:i:s');
  6144. // // 保存对话记录
  6145. // $records = [
  6146. // [
  6147. // 'uid' => $uid,
  6148. // 'anime_id' => $anime_id,
  6149. // 'sequence' => 0,
  6150. // 'role' => 'user',
  6151. // 'content' => $prompt,
  6152. // 'created_at' => $now,
  6153. // 'updated_at' => $now
  6154. // ],
  6155. // [
  6156. // 'uid' => $uid,
  6157. // 'anime_id' => $anime_id,
  6158. // 'sequence' => 0,
  6159. // 'role' => 'assistant',
  6160. // 'content' => '未能生成剧本名称,请重试',
  6161. // 'created_at' => $now,
  6162. // 'updated_at' => $now
  6163. // ]
  6164. // ];
  6165. // DB::table('mp_anime_records')->insert($records);
  6166. // DB::commit();
  6167. // } catch (\Exception $e) {
  6168. // DB::rollBack();
  6169. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6170. // }
  6171. // yield [
  6172. // 'type' => 'done',
  6173. // 'script' => [],
  6174. // 'episode' => [],
  6175. // 'answer' => $fullContent,
  6176. // 'reasoning' => $fullReasoningContent,
  6177. // 'usage' => $usage,
  6178. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  6179. // ];
  6180. // return;
  6181. // }
  6182. // 确认对话名称唯一性
  6183. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6184. $anime_name = $anime_name . '_' . date('YmdHis');
  6185. }
  6186. }else {
  6187. $anime_name = $user_anime_name;
  6188. }
  6189. $table_data = [
  6190. 'user_id' => $uid,
  6191. 'anime_name' => $anime_name,
  6192. 'model' => $model,
  6193. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6194. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6195. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6196. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6197. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6198. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6199. 'art_style_type' => $input_art_style,
  6200. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6201. 'status' => '解析完成',
  6202. 'content' => $content,
  6203. 'is_multi' => $is_multi,
  6204. 'ace_mode' => $ace_mode,
  6205. 'generate_status' => '待执行',
  6206. 'updated_at' => date('Y-m-d H:i:s')
  6207. ];
  6208. if ($table_data['content']) {
  6209. $chapters = splitContent($table_data['content']);
  6210. $chapter_count = count($chapters);
  6211. if ($chapter_count > 0) {
  6212. $table_data['start_episode_sequence'] = 1;
  6213. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6214. }
  6215. }
  6216. // 如果有剧本ID则进行绑定
  6217. if ($script_id) {
  6218. $table_data['script_id'] = $script_id;
  6219. }
  6220. $single_episode = [];
  6221. try {
  6222. DB::beginTransaction();
  6223. $now = date('Y-m-d H:i:s');
  6224. // 更新动漫大纲
  6225. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6226. if (!$boolen) {
  6227. dLog('deepseek')->info('动漫保存失败', $table_data);
  6228. Utils::throwError('20003:动漫保存失败');
  6229. }
  6230. // 保存对话记录
  6231. $records = [
  6232. [
  6233. 'uid' => $uid,
  6234. 'anime_id' => $anime_id,
  6235. 'sequence' => 0,
  6236. 'role' => 'user',
  6237. 'content' => $prompt,
  6238. 'created_at' => date('Y-m-d H:i:s'),
  6239. 'updated_at' => date('Y-m-d H:i:s')
  6240. ],
  6241. [
  6242. 'uid' => $uid,
  6243. 'anime_id' => $anime_id,
  6244. 'sequence' => 0,
  6245. 'role' => 'assistant',
  6246. 'content' => $fullContent,
  6247. 'created_at' => date('Y-m-d H:i:s'),
  6248. 'updated_at' => date('Y-m-d H:i:s')
  6249. ]
  6250. ];
  6251. // 保存对话记录
  6252. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6253. if (!$boolen3) {
  6254. Utils::throwError('20003:对话记录保存失败');
  6255. }
  6256. if ($is_single) {
  6257. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6258. if (empty($episode_arr['acts'])) {
  6259. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6260. }
  6261. $saveResult = $this->saveEpisodeVersionData(
  6262. $anime_id,
  6263. 1,
  6264. $episode_arr,
  6265. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6266. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6267. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6268. null,
  6269. null,
  6270. false,
  6271. $content,
  6272. $now
  6273. );
  6274. $single_episode = $saveResult['episode'];
  6275. $episode_id = $saveResult['episode_id'];
  6276. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6277. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6278. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6279. 'props' => json_encode($saveResult['merged_props'], 256),
  6280. 'updated_at' => $now
  6281. ]);
  6282. if ($boolen5 === false) {
  6283. Utils::throwError('20003:单剧集主表资源同步失败');
  6284. }
  6285. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6286. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6287. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6288. $episode_record_content = '确认分镜大纲';
  6289. if ($content !== '') {
  6290. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6291. }
  6292. $episode_records = [
  6293. [
  6294. 'uid' => $uid,
  6295. 'anime_id' => $anime_id,
  6296. 'role' => 'user',
  6297. 'content' => $episode_record_content,
  6298. 'sequence' => 1,
  6299. 'episode_id' => $episode_id,
  6300. 'created_at' => $now,
  6301. 'updated_at' => $now
  6302. ],
  6303. [
  6304. 'uid' => $uid,
  6305. 'anime_id' => $anime_id,
  6306. 'role' => 'assistant',
  6307. 'content' => $fullContent,
  6308. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6309. 'sequence' => 1,
  6310. 'episode_id' => $episode_id,
  6311. 'created_at' => $now,
  6312. 'updated_at' => $now
  6313. ]
  6314. ];
  6315. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6316. if (!$boolen4) {
  6317. Utils::throwError('20003:单剧集分镜记录保存失败');
  6318. }
  6319. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6320. if ($is_single && !empty($single_episode)) {
  6321. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6322. 'anime_id' => $anime_id,
  6323. 'episode_id' => $episode_id ?? 0,
  6324. 'model' => $model,
  6325. 'source' => 'addChat',
  6326. ]);
  6327. }
  6328. }
  6329. }catch (\Exception $e) {
  6330. DB::rollBack();
  6331. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6332. yield [
  6333. 'type' => 'done',
  6334. 'answer' => $fullContent,
  6335. 'reasoning' => $fullReasoningContent,
  6336. 'usage' => $usage,
  6337. 'error' => $e->getMessage(),
  6338. ];
  6339. return;
  6340. }
  6341. DB::commit();
  6342. dLog('deepseek')->info('保存完毕');
  6343. if ($is_single && !empty($single_episode)) {
  6344. // $this->batchSetGlobalRoleImg([
  6345. // 'anime_id' => $anime_id,
  6346. // ]);
  6347. // $this->batchSetGlobalSceneImg([
  6348. // 'anime_id' => $anime_id,
  6349. // ]);
  6350. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6351. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6352. }
  6353. $table_data['anime_id'] = $anime_id;
  6354. $table_data['roles'] = json_decode($table_data['roles'], true);
  6355. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6356. // $table_data['episodes'] = $script_arr['episodes'];
  6357. unset($table_data['created_at']);
  6358. unset($table_data['updated_at']);
  6359. unset($table_data['status']);
  6360. dLog('deepseek')->info('开始返回');
  6361. yield [
  6362. 'type' => 'done',
  6363. 'script' => $table_data,
  6364. 'episode' => $single_episode,
  6365. 'answer' => $fullContent,
  6366. 'reasoning' => $fullReasoningContent,
  6367. 'usage' => $usage
  6368. ];
  6369. }
  6370. public function reGenerateAnime($data) {
  6371. $uid = Site::getUid();
  6372. $file = getProp($data, 'file');
  6373. $content = getProp($data, 'content', '');
  6374. $bid = getProp($data, 'bid', 0);
  6375. $script_id = getProp($data, 'script_id', 0);
  6376. $anime_id = getProp($data, 'anime_id');
  6377. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6378. if (!$anime) {
  6379. Utils::throwError('20003:该对话不存在');
  6380. }
  6381. $user_anime_name = getProp($anime, 'anime_name');
  6382. $prompt = getProp($data, 'prompt');
  6383. // 处理文本模型
  6384. $model = getProp($data, 'model');
  6385. if (!$model) {
  6386. // 用户没有输入,从anime表获取
  6387. $model = getProp($anime, 'model');
  6388. if (!$model) {
  6389. // anime表也没有,使用默认值
  6390. $model = 'doubao-seed-2-0-mini-260215';
  6391. }
  6392. }
  6393. // 验证模型是否在可用模型表中
  6394. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6395. $model = 'doubao-seed-2-0-mini-260215';
  6396. }
  6397. $is_multi = getProp($anime, 'is_multi', 1);
  6398. $is_single = (int)$is_multi !== 1;
  6399. // 积分余额预检(仅单剧集模式收费)
  6400. if ($is_single) {
  6401. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  6402. }
  6403. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  6404. if ($is_single) {
  6405. $episode_exists = DB::table('mp_anime_episodes')
  6406. ->where('anime_id', $anime_id)
  6407. ->where('sequence', 1)
  6408. ->exists();
  6409. if ($episode_exists) {
  6410. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  6411. }
  6412. }
  6413. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  6414. if ($prompt) {
  6415. $question .= "本次修改要求如下:\n{$prompt}";
  6416. }
  6417. // 提取文件内容
  6418. if ($file) {
  6419. $content = $this->extractFileContent($file);
  6420. if (!$content) {
  6421. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6422. }
  6423. } elseif ($script_id) {
  6424. $content = $this->getContentByScriptId($script_id);
  6425. if (!$content) {
  6426. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6427. }
  6428. } elseif ($bid) {
  6429. $content = $this->getContentByBid($bid);
  6430. if (!$content) {
  6431. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6432. }
  6433. } elseif ($content) {
  6434. $content = filterContent($content);
  6435. }else {
  6436. $content = filterContent(getProp($anime, 'content'));
  6437. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6438. $need_generate_content = true;
  6439. }
  6440. }
  6441. // 判断是否需要生成原文内容
  6442. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6443. // 如果需要生成原文内容,添加额外的要求
  6444. $content_generation_requirement = $need_generate_content
  6445. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6446. : "";
  6447. // 美术风格
  6448. $input_art_style = getProp($anime, 'art_style');
  6449. if (!$input_art_style) {
  6450. $input_art_style = getProp($data, 'art_style');
  6451. }
  6452. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6453. // 美术风格
  6454. if (!$mappedArtStyle) {
  6455. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6456. }else {
  6457. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6458. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6459. }else {
  6460. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6461. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6462. }
  6463. }
  6464. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  6465. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  6466. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  6467. 中年女:邻居阿姨
  6468. 老年男:幽默大爷
  6469. 老年女:婆婆
  6470. 萌娃:奶气萌娃";
  6471. $system_message = ['role'=>'system', 'content'=>$is_single
  6472. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6473. 强制要求:
  6474. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6475. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6476. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6477. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6478. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6479. 普通要求:
  6480. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6481. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6482. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6483. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6484. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6485. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6486. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6487. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6488. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6489. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6490. 3.$mappedArtStyle_prompt\n\n
  6491. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6492. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6493. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6494. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  6495. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  6496. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6497. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6498. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6499. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6500. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6501. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6502. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6503. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6504. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6505. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  6506. 示例如下:\n
  6507. ###剧本名:西昆仑
  6508. ###故事梗概
  6509. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6510. ###剧本亮点
  6511. 亮点1:绝境奇药,生死一线
  6512. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6513. 亮点2:结拜兄妹,化解尴尬
  6514. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6515. 亮点3:纤发夺命,情愫暗涌
  6516. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6517. ###人物关系
  6518. 阿雪与梁萧之间存在兄妹之情。
  6519. ###核心矛盾
  6520. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6521. ###主体列表
  6522. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6523. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6524. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6525. 姿态:站立。}{{甜心小美}}
  6526. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6527. 全景,正面拍摄,青年女性,亚洲人。
  6528. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6529. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6530. 姿态:站立。}{{阳光青年}}
  6531. ###美术风格
  6532. 基础画风风格词:厚涂古风
  6533. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6534. ###场景列表
  6535. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6536. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6537. 无人物。}
  6538. ###分镜剧本
  6539. ##第1幕:徐家老旧厨房 白天 室内
  6540. 分镜1
  6541. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6542. 场景:徐家老旧厨房
  6543. 构图设计:全景,低角度仰视
  6544. 运镜调度:手持拍摄
  6545. 配音角色:旁白
  6546. 出镜角色:许芸-校服装、徐母
  6547. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6548. 画面类型:普通画面
  6549. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6550. 分镜2
  6551. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6552. 场景:徐家老旧厨房
  6553. 构图设计:近景,徐母面部特写
  6554. 运镜调度:固定镜头
  6555. 配音角色:徐母
  6556. 出镜角色:徐母
  6557. 台词内容:问我夜不归宿死哪儿去了。
  6558. 画面类型:对口型
  6559. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6560. ##第2幕:徐家简陋客厅 黄昏 室内
  6561. 分镜3
  6562. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6563. 场景:徐家简陋客厅
  6564. 构图设计:全景,景深虚化
  6565. 运镜调度:固定镜头
  6566. 配音角色:旁白
  6567. 出镜角色:无
  6568. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6569. 画面类型:普通画面
  6570. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6571. 分镜4
  6572. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6573. 场景:徐家简陋客厅
  6574. 构图设计:特写,火车票
  6575. 运镜调度:固定镜头
  6576. 配音角色:旁白
  6577. 出镜角色:无
  6578. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6579. 画面类型:普通画面
  6580. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  6581. "
  6582. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6583. 强制要求:\n
  6584. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6585. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6586. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6587. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6588. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6589. 普通要求:\n
  6590. 1.剧本名(必须生成)必须与文档内容高度相关
  6591. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6592. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6593. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6594. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6595. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6596. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6597. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6598. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6599. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6600. 4.$mappedArtStyle_prompt\n\n
  6601. 示例如下:\n
  6602. ###剧本名:西昆仑
  6603. ###故事梗概
  6604. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6605. ###剧本亮点
  6606. 亮点1:绝境奇药,生死一线
  6607. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6608. 亮点2:结拜兄妹,化解尴尬
  6609. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6610. 亮点3:纤发夺命,情愫暗涌
  6611. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6612. ###人物关系
  6613. 阿雪与梁萧之间存在兄妹之情。
  6614. ###核心矛盾
  6615. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6616. ###主体列表
  6617. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6618. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6619. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6620. 姿态:站立。}{{甜心小美}}
  6621. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6622. 全景,正面拍摄,青年女性,亚洲人。
  6623. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6624. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6625. 姿态:站立。}{{阳光青年}}
  6626. ###美术风格
  6627. 基础画风风格词:厚涂古风
  6628. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6629. ###场景列表
  6630. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6631. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6632. 无人物。}"];
  6633. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6634. $episode_count = $this->extractEpisodeNumber($prompt);
  6635. if ((int)getProp($anime, 'is_multi') !== 1) {
  6636. yield [
  6637. 'type' => 'done',
  6638. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6639. 'reasoning' => '',
  6640. 'usage' => []
  6641. ];
  6642. return;
  6643. }
  6644. if ($episode_count) {
  6645. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6646. $system_message = [
  6647. 'role' => 'system',
  6648. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6649. 强制要求:\n
  6650. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6651. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6652. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6653. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6654. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6655. 普通要求:\n
  6656. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6657. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6658. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6659. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6660. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6661. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6662. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6663. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6664. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6665. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6666. 示例如下:\n
  6667. ###剧本名:西昆仑
  6668. ###故事梗概
  6669. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6670. ###剧本亮点
  6671. 亮点1:绝境奇药,生死一线
  6672. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6673. 亮点2:结拜兄妹,化解尴尬
  6674. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6675. 亮点3:纤发夺命,情愫暗涌
  6676. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6677. ###人物关系
  6678. 阿雪与梁萧之间存在兄妹之情。
  6679. ###核心矛盾
  6680. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6681. ###主体列表
  6682. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6683. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6684. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6685. 姿态:站立。}{{甜心小美}}
  6686. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6687. 全景,正面拍摄,青年女性,亚洲人。
  6688. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6689. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6690. 姿态:站立。}{{阳光青年}}
  6691. ###美术风格
  6692. 基础画风风格词:厚涂古风
  6693. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6694. ###场景列表
  6695. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6696. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6697. 无人物。}
  6698. ###分集详细内容
  6699. ##第1章 重生
  6700. 我重生了。
  6701. 源于一个男人偏执的暗恋。
  6702. ##第2章 相救
  6703. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6704. 我眼睛扫向站在锅炉后的卞大伟。"
  6705. ];
  6706. // 构建消息
  6707. $messages = [
  6708. $system_message,
  6709. [
  6710. 'role' => 'user',
  6711. 'content' => "以下是文档内容:
  6712. {$content}
  6713. 用户问题:
  6714. {$question}"
  6715. ]
  6716. ];
  6717. }else {
  6718. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6719. // 构建消息
  6720. $messages = [
  6721. $system_message,
  6722. [
  6723. 'role' => 'user',
  6724. 'content' => "以下是文档内容:
  6725. {$content}
  6726. 用户问题:
  6727. {$question}"
  6728. ]
  6729. ];
  6730. }else {
  6731. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6732. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6733. return (array)$value;
  6734. })->toArray();
  6735. array_unshift($messages, $system_message);
  6736. $messages[] = [
  6737. 'role' => 'user',
  6738. 'content' => $prompt
  6739. ];
  6740. }
  6741. }
  6742. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6743. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6744. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6745. if ($model === 'deepseek-chat') {
  6746. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6747. $model = 'deepseek-v4-flash';
  6748. $thinkingMode = 'disabled';
  6749. } elseif ($model === 'deepseek-reasoner') {
  6750. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6751. $model = 'deepseek-v4-flash';
  6752. $thinkingMode = 'enabled';
  6753. }
  6754. $post_data = [
  6755. 'model' => $model,
  6756. 'messages' => $messages,
  6757. // 'max_tokens' => 8192,
  6758. 'temperature' => 0.7,
  6759. 'frequency_penalty' => 0,
  6760. 'presence_penalty' => 0,
  6761. 'response_format' => ['type' => 'text'],
  6762. 'thinking' => ['type' => $thinkingMode],
  6763. 'stream' => true // 启用流式输出
  6764. ];
  6765. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6766. // 根据模型类型选择调用方法
  6767. $fullContent = '';
  6768. $fullReasoningContent = '';
  6769. $usage = [];
  6770. // dd($post_data);
  6771. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6772. try {
  6773. $streamGenerator = $this->dispatchStreamByModel($post_data);
  6774. // 验证返回值类型
  6775. if (!is_iterable($streamGenerator)) {
  6776. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6777. dLog('deepseek')->error('方法名流式生成器无效', [
  6778. 'generator_type' => $errorType,
  6779. 'model' => $model,
  6780. // 添加其他上下文信息
  6781. ]);
  6782. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6783. 'type' => $errorType,
  6784. 'model' => $model
  6785. ]);
  6786. yield [
  6787. 'type' => 'error',
  6788. // 根据方法返回相应的空数据结构
  6789. 'answer' => '',
  6790. 'reasoning' => '',
  6791. 'usage' => [],
  6792. 'error' => '接口返回数据异常,请重新请求'
  6793. ];
  6794. return;
  6795. }
  6796. // 处理流式输出
  6797. foreach ($streamGenerator as $chunk) {
  6798. if (isset($chunk['type'])) {
  6799. if ($chunk['type'] === 'done') {
  6800. $fullContent = $chunk['full_content'];
  6801. $fullReasoningContent = $chunk['full_reasoning'];
  6802. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6803. } else {
  6804. yield $chunk;
  6805. }
  6806. }
  6807. }
  6808. } catch (\Exception $e) {
  6809. // 解析上游错误详情(如 content_filter),便于日志定位与前端提示
  6810. $upstream_error = $this->resolveGptUpstreamError($e);
  6811. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6812. 'model' => $model,
  6813. 'upstream_status' => $upstream_error['status'],
  6814. 'upstream_code' => $upstream_error['code'],
  6815. 'upstream_body' => $upstream_error['body'],
  6816. 'trace' => $e->getTraceAsString()
  6817. ]);
  6818. logDB('deepseek', 'error', '方法名流式处理失败', [
  6819. 'error' => $e->getMessage(),
  6820. 'model' => $model,
  6821. 'upstream_status' => $upstream_error['status'],
  6822. 'upstream_code' => $upstream_error['code'],
  6823. 'upstream_body' => $upstream_error['body']
  6824. ]);
  6825. yield [
  6826. 'type' => 'error',
  6827. // 根据方法返回相应的空数据结构
  6828. 'answer' => '',
  6829. 'reasoning' => '',
  6830. 'usage' => [],
  6831. 'error' => $this->buildChatErrorForUser($e, $upstream_error)
  6832. ];
  6833. return;
  6834. }
  6835. dLog('deepseek')->info('完整内容: '.$fullContent);
  6836. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6837. // 处理完整内容并返回最终结果
  6838. $script_arr = [];
  6839. if ($fullContent) {
  6840. $script_arr = handleScriptContent($fullContent);
  6841. dLog('deepseek')->info('解析内容', $script_arr);
  6842. logDB('deepseek', 'info', '解析内容', $script_arr);
  6843. }
  6844. if (empty($script_arr['roles'])) {
  6845. // 未生成剧本相关内容,保存对话记录并返回提示
  6846. dLog('deepseek')->info('未生成剧本相关的内容');
  6847. try {
  6848. $now = date('Y-m-d H:i:s');
  6849. // 保存对话记录
  6850. $records = [
  6851. [
  6852. 'uid' => $uid,
  6853. 'anime_id' => $anime_id,
  6854. 'sequence' => 0,
  6855. 'role' => 'user',
  6856. 'content' => $prompt,
  6857. 'created_at' => $now,
  6858. 'updated_at' => $now
  6859. ],
  6860. [
  6861. 'uid' => $uid,
  6862. 'anime_id' => $anime_id,
  6863. 'sequence' => 0,
  6864. 'role' => 'assistant',
  6865. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6866. 'created_at' => $now,
  6867. 'updated_at' => $now
  6868. ]
  6869. ];
  6870. DB::table('mp_anime_records')->insert($records);
  6871. } catch (\Exception $e) {
  6872. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6873. }
  6874. yield [
  6875. 'type' => 'done',
  6876. 'script' => [],
  6877. 'episode' => [],
  6878. 'answer' => $fullContent,
  6879. 'reasoning' => $fullReasoningContent,
  6880. 'usage' => $usage,
  6881. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6882. ];
  6883. return;
  6884. }
  6885. // 替换美术风格
  6886. if ($mappedArtStyle !== '') {
  6887. $script_arr['art_style'] = $mappedArtStyle;
  6888. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6889. }
  6890. if ($user_anime_name != '新剧本策划') {
  6891. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6892. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6893. // 确认对话名称唯一性
  6894. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6895. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6896. }
  6897. }else {
  6898. $anime_name = $user_anime_name;
  6899. }
  6900. $table_data = [
  6901. 'user_id' => $uid,
  6902. 'model' => $model,
  6903. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6904. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6905. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6906. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6907. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6908. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6909. 'art_style_type' => $input_art_style,
  6910. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6911. 'status' => '解析完成',
  6912. 'generate_status' => '待执行',
  6913. 'updated_at' => date('Y-m-d H:i:s')
  6914. ];
  6915. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6916. // 如果是修改集数,则将content内容更新(会改变原文)
  6917. if (isset($episode_count) && $episode_count > 0) {
  6918. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6919. $table_data['start_episode_sequence'] = 1;
  6920. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6921. }else {
  6922. // 如果需要生成原文内容,从script_arr中提取
  6923. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6924. $table_data['content'] = $script_arr['content'];
  6925. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6926. if (!$table_data['content']) {
  6927. yield [
  6928. 'type' => 'done',
  6929. 'script' => [],
  6930. 'episode' => [],
  6931. 'answer' => $fullContent,
  6932. 'reasoning' => $fullReasoningContent,
  6933. 'usage' => $usage,
  6934. 'error' => '未生成剧本内容,请调整提示词再试'
  6935. ];
  6936. return;
  6937. }
  6938. }
  6939. if (isset($table_data['content']) && $table_data['content']) {
  6940. $chapters = splitContent($table_data['content']);
  6941. $chapter_count = count($chapters);
  6942. if ($chapter_count > 0) {
  6943. $table_data['start_episode_sequence'] = 1;
  6944. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6945. }
  6946. }
  6947. }
  6948. $single_episode = [];
  6949. try {
  6950. DB::beginTransaction();
  6951. $now = date('Y-m-d H:i:s');
  6952. // 更新动漫大纲
  6953. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6954. if (!$boolen) {
  6955. dLog('deepseek')->info('对话修改失败', $table_data);
  6956. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6957. Utils::throwError('20003:对话修改失败');
  6958. }
  6959. // 保存对话记录
  6960. $records = [
  6961. [
  6962. 'uid' => $uid,
  6963. 'anime_id' => $anime_id,
  6964. 'sequence' => 0,
  6965. 'role' => 'user',
  6966. 'content' => $prompt,
  6967. 'created_at' => $now,
  6968. 'updated_at' => $now
  6969. ],
  6970. [
  6971. 'uid' => $uid,
  6972. 'anime_id' => $anime_id,
  6973. 'sequence' => 0,
  6974. 'role' => 'assistant',
  6975. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6976. 'content' => $fullContent,
  6977. 'created_at' => $now,
  6978. 'updated_at' => $now
  6979. ]
  6980. ];
  6981. // 保存对话记录
  6982. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6983. if (!$boolen3) {
  6984. Utils::throwError('20003:对话记录保存失败');
  6985. }
  6986. // 单剧集模式:生成并保存剧集信息
  6987. if ($is_single) {
  6988. $anime_name = getProp($anime, 'anime_name', '未命名');
  6989. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6990. if (empty($episode_arr['acts'])) {
  6991. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6992. }
  6993. $saveResult = $this->saveEpisodeVersionData(
  6994. $anime_id,
  6995. 1,
  6996. $episode_arr,
  6997. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6998. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6999. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7000. null,
  7001. null,
  7002. false,
  7003. $content,
  7004. $now
  7005. );
  7006. $single_episode = $saveResult['episode'];
  7007. $episode_id = $saveResult['episode_id'];
  7008. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7009. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7010. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7011. 'props' => json_encode($saveResult['merged_props'], 256),
  7012. 'updated_at' => $now
  7013. ]);
  7014. if ($boolen5 === false) {
  7015. Utils::throwError('20003:单剧集主表资源同步失败');
  7016. }
  7017. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7018. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7019. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7020. $episode_record_content = '确认分镜大纲';
  7021. if ($content !== '') {
  7022. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7023. }
  7024. $episode_records = [
  7025. [
  7026. 'uid' => $uid,
  7027. 'anime_id' => $anime_id,
  7028. 'role' => 'user',
  7029. 'content' => $episode_record_content,
  7030. 'sequence' => 1,
  7031. 'episode_id' => $episode_id,
  7032. 'created_at' => $now,
  7033. 'updated_at' => $now
  7034. ],
  7035. [
  7036. 'uid' => $uid,
  7037. 'anime_id' => $anime_id,
  7038. 'role' => 'assistant',
  7039. 'content' => $fullContent,
  7040. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7041. 'sequence' => 1,
  7042. 'episode_id' => $episode_id,
  7043. 'created_at' => $now,
  7044. 'updated_at' => $now
  7045. ]
  7046. ];
  7047. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7048. if (!$boolen4) {
  7049. Utils::throwError('20003:单剧集分镜记录保存失败');
  7050. }
  7051. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7052. if ($is_single && !empty($single_episode)) {
  7053. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7054. 'anime_id' => $anime_id,
  7055. 'episode_id' => $episode_id ?? 0,
  7056. 'model' => $model,
  7057. 'source' => 'reGenerateAnime',
  7058. ]);
  7059. }
  7060. }
  7061. }catch (\Exception $e) {
  7062. DB::rollBack();
  7063. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  7064. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  7065. yield [
  7066. 'type' => 'done',
  7067. 'answer' => $fullContent,
  7068. 'reasoning' => $fullReasoningContent,
  7069. 'usage' => $usage,
  7070. 'error' => $e->getMessage(),
  7071. ];
  7072. return;
  7073. }
  7074. DB::commit();
  7075. dLog('deepseek')->info('保存完毕');
  7076. if ($is_single && !empty($single_episode)) {
  7077. // $this->batchSetGlobalRoleImg([
  7078. // 'anime_id' => $anime_id,
  7079. // ]);
  7080. // $this->batchSetGlobalSceneImg([
  7081. // 'anime_id' => $anime_id,
  7082. // ]);
  7083. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7084. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7085. }
  7086. $table_data['anime_id'] = $anime_id;
  7087. $table_data['roles'] = json_decode($table_data['roles'], true);
  7088. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7089. unset($table_data['updated_at']);
  7090. unset($table_data['status']);
  7091. yield [
  7092. 'type' => 'done',
  7093. 'script' => $table_data,
  7094. 'episode' => $single_episode,
  7095. 'answer' => $fullContent,
  7096. 'reasoning' => $fullReasoningContent,
  7097. 'usage' => $usage
  7098. ];
  7099. }
  7100. public function chat($data) {
  7101. $uid = Site::getUid();
  7102. // 积分余额预检(不足直接报错)
  7103. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  7104. $anime_id = getProp($data, 'anime_id');
  7105. $file = getProp($data, 'file');
  7106. $content = getProp($data, 'content', '');
  7107. $bid = getProp($data, 'bid', 0);
  7108. $script_id = getProp($data, 'script_id', 0);
  7109. $episode_number = getProp($data, 'episode_number', 1);
  7110. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7111. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7112. if (!$anime) Utils::throwError('20003:该对话不存在!');
  7113. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  7114. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  7115. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  7116. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  7117. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  7118. $roles = is_array($roles) ? $roles : [];
  7119. $scenes = is_array($scenes) ? $scenes : [];
  7120. // 获取最后一集序号
  7121. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  7122. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  7123. // 转换主体列表和场景列表的格式
  7124. // 获取参考主体或场景
  7125. if ((int)$episode_number === 1) {
  7126. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  7127. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  7128. }else {
  7129. $prev_episode_number = $episode_number - 1;
  7130. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  7131. }
  7132. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  7133. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  7134. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  7135. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  7136. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  7137. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  7138. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  7139. 中年女:邻居阿姨
  7140. 老年男:幽默大爷
  7141. 老年女:婆婆
  7142. 萌娃:奶气萌娃";
  7143. if ($roles_content) {
  7144. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  7145. 主体范围:\n {$roles_content}\n
  7146. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  7147. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  7148. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7149. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7150. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  7151. }else {
  7152. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7153. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  7154. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7155. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7156. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  7157. }
  7158. if ($scenes_content) {
  7159. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7160. 场景范围:\n {$scenes_content}\n
  7161. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  7162. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7163. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7164. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  7165. }else {
  7166. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7167. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7168. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7169. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  7170. }
  7171. // 提取文件内容
  7172. if ($file) {
  7173. $uploaded_content = $this->extractFileContent($file);
  7174. if (!$uploaded_content) {
  7175. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7176. }
  7177. } elseif ($script_id) {
  7178. $uploaded_content = $this->getContentByScriptId($script_id);
  7179. if (!$uploaded_content) {
  7180. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7181. }
  7182. } elseif ($bid) {
  7183. $uploaded_content = $this->getContentByBid($bid);
  7184. if (!$uploaded_content) {
  7185. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7186. }
  7187. } elseif ($content) {
  7188. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  7189. }
  7190. // elseif ($prompt) {
  7191. // $uploaded_content = filterContent($prompt);
  7192. // }
  7193. else {
  7194. $uploaded_content = '';
  7195. }
  7196. $input_art_style = getProp($anime, 'art_style');
  7197. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7198. // 美术风格
  7199. if (!$mappedArtStyle) {
  7200. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7201. }else {
  7202. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7203. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7204. }else {
  7205. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7206. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7207. }
  7208. }
  7209. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7210. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7211. // 强制要求:
  7212. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7213. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7214. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7215. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  7216. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  7217. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  7218. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  7219. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  7220. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  7221. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  7222. // - 分镜要和场景列表、人物主体保持一致\n
  7223. // 普通要求:
  7224. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7225. // {$role_demo}
  7226. // {$scene_demo}
  7227. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  7228. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  7229. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  7230. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  7231. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  7232. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  7233. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  7234. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  7235. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  7236. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  7237. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  7238. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  7239. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  7240. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  7241. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  7242. // 5.$mappedArtStyle_prompt\n\n
  7243. // 示例格式:\n
  7244. // 第1集:隐形的守护者
  7245. // ###故事梗概
  7246. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7247. // ###美术风格
  7248. // 基础画风风格词:韩漫二次元
  7249. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  7250. // ###主体列表
  7251. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  7252. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  7253. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  7254. // ###场景列表
  7255. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  7256. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7257. // 无人物。}
  7258. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  7259. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  7260. // 无人物。}
  7261. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  7262. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  7263. // 无人物。}
  7264. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  7265. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  7266. // 无人物。}
  7267. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  7268. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  7269. // 无人物。}
  7270. // ###分镜剧本
  7271. // ##第1幕:徐家老旧厨房 白天 室内
  7272. // 分镜1
  7273. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  7274. // 场景:徐家老旧厨房
  7275. // 构图设计:全景,低角度仰视
  7276. // 运镜调度:手持拍摄
  7277. // 配音角色:旁白
  7278. // 出镜角色:许芸-校服装、徐母
  7279. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  7280. // 画面类型:普通画面
  7281. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  7282. // 分镜2
  7283. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  7284. // 场景:徐家老旧厨房
  7285. // 构图设计:近景,徐母面部特写
  7286. // 运镜调度:固定镜头
  7287. // 配音角色:徐母
  7288. // 出镜角色:徐母
  7289. // 台词内容:问我夜不归宿死哪儿去了。
  7290. // 画面类型:对口型
  7291. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  7292. // ##第2幕:徐家简陋客厅 黄昏 室内
  7293. // 分镜3
  7294. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  7295. // 场景:徐家简陋客厅
  7296. // 构图设计:全景,景深虚化
  7297. // 运镜调度:固定镜头
  7298. // 配音角色:旁白
  7299. // 出镜角色:无
  7300. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  7301. // 画面类型:普通画面
  7302. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  7303. // 分镜4
  7304. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  7305. // 场景:徐家简陋客厅
  7306. // 构图设计:特写,火车票
  7307. // 运镜调度:固定镜头
  7308. // 配音角色:旁白
  7309. // 出镜角色:无
  7310. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  7311. // 画面类型:普通画面
  7312. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  7313. // \n\n";
  7314. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7315. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7316. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  7317. 普通要求:
  7318. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7319. {$role_demo}
  7320. {$scene_demo}
  7321. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  7322. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  7323. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  7324. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7325. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  7326. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  7327. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  7328. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  7329. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  7330. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  7331. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  7332. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  7333. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  7334. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  7335. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  7336. 5.$mappedArtStyle_prompt
  7337. 6.《情绪-视听语言映射表》:
  7338. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7339. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7340. -----|---------|------------|----------------
  7341. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7342. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7343. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7344. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7345. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7346. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7347. -----|---------|------------|----------------
  7348. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7349. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7350. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7351. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7352. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7353. --------|---------|--------------|-------------
  7354. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7355. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7356. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7357. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7358. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7359. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7360. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7361. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7362. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7363. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7364. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7365. -----|---------|------------|------------
  7366. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7367. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7368. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7369. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7370. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7371. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7372. --------|---------|--------------|----------
  7373. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7374. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7375. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7376. 6.6 声音设计与潜意识影响 (Soundscape)
  7377. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7378. -----|---------|------------|------------------
  7379. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7380. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7381. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7382. 理论基石:
  7383. - The Five C's of Cinematography by Joseph V. Mascelli
  7384. - Film Art: An Introduction by David Bordwell
  7385. - Sight, Sound, Motion by Herbert Zettl
  7386. - Notes on the Cinematograph by Robert Bresson
  7387. \n\n
  7388. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  7389. 示例格式:\n
  7390. 第1集:隐形的守护者
  7391. ###故事梗概
  7392. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7393. ###美术风格
  7394. 基础画风风格词:韩漫二次元
  7395. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  7396. ###主体列表
  7397. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  7398. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  7399. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  7400. ###场景列表
  7401. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  7402. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7403. 无人物。}
  7404. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  7405. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  7406. 无人物。}
  7407. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  7408. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  7409. 无人物。}
  7410. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  7411. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  7412. 无人物。}
  7413. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  7414. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  7415. 无人物。}
  7416. ###分镜剧本
  7417. ##第1幕:徐家老旧厨房 白天 室内
  7418. 分镜1
  7419. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  7420. 场景:徐家老旧厨房
  7421. 构图设计:全景,低角度仰视
  7422. 运镜调度:手持拍摄
  7423. 配音角色:旁白
  7424. 出镜角色:许芸-校服装、徐母
  7425. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  7426. 画面类型:普通画面
  7427. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  7428. 分镜2
  7429. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  7430. 场景:徐家老旧厨房
  7431. 构图设计:近景,徐母面部特写
  7432. 运镜调度:固定镜头
  7433. 配音角色:徐母
  7434. 出镜角色:徐母
  7435. 台词内容:问我夜不归宿死哪儿去了。
  7436. 画面类型:对口型
  7437. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  7438. ##第2幕:徐家简陋客厅 黄昏 室内
  7439. 分镜3
  7440. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  7441. 场景:徐家简陋客厅
  7442. 构图设计:全景,景深虚化
  7443. 运镜调度:固定镜头
  7444. 配音角色:旁白
  7445. 出镜角色:无
  7446. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  7447. 画面类型:普通画面
  7448. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  7449. 分镜4
  7450. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  7451. 场景:徐家简陋客厅
  7452. 构图设计:特写,火车票
  7453. 运镜调度:固定镜头
  7454. 配音角色:旁白
  7455. 出镜角色:无
  7456. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  7457. 画面类型:普通画面
  7458. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  7459. \n\n";
  7460. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7461. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  7462. $is_regenerate_version = true;
  7463. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7464. $prompt = $origin_prompt;
  7465. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7466. // 获取章节内容
  7467. $full_content = getProp($anime, 'content');
  7468. if ($uploaded_content) {
  7469. $full_content = $uploaded_content;
  7470. }
  7471. // 根据章节内容拆分章节
  7472. $chapters = splitContent($full_content);
  7473. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7474. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7475. $messages = [];
  7476. if ($prompt == '确认分镜大纲') {
  7477. // 暂时保留
  7478. $content = $chapter_content;
  7479. if ($is_single) $content = $full_content; // 单剧集使用全文
  7480. if (!$content) {
  7481. Utils::throwError('20003:章节内容无法获取,请确认');
  7482. }
  7483. $question = $is_single
  7484. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7485. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7486. // 构建消息
  7487. $messages[] =
  7488. [
  7489. 'role' => 'user',
  7490. 'content' => $question
  7491. ];
  7492. }else if ($prompt == '继续策划下一集') {
  7493. if ($is_single) {
  7494. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7495. }
  7496. $content = $chapter_content;
  7497. if (!$content) {
  7498. Utils::throwError('20003:章节内容无法获取,请确认');
  7499. }
  7500. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7501. // 获取上一集最后记录
  7502. $prev_sequence = $episode_number - 1;
  7503. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7504. // 构建消息
  7505. $messages[] =
  7506. [
  7507. 'role' => 'user',
  7508. 'content' => $question
  7509. ];
  7510. }else {
  7511. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7512. if (!$content) {
  7513. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7514. }
  7515. if (!$content) {
  7516. Utils::throwError('20003:章节内容无法获取,请确认');
  7517. }
  7518. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7519. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7520. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7521. if ($origin_prompt) {
  7522. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  7523. }
  7524. $messages[] =
  7525. [
  7526. 'role' => 'user',
  7527. 'content' => $question
  7528. ];
  7529. }
  7530. // 处理文本模型
  7531. $model = getProp($data, 'model');
  7532. if (!$model) {
  7533. // 用户没有输入,从anime表获取
  7534. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7535. $model = getProp($anime, 'model');
  7536. if (!$model) {
  7537. // anime表也没有,使用默认值
  7538. $model = 'doubao-seed-2-0-mini-260215';
  7539. }
  7540. }
  7541. // 验证模型是否在可用模型表中
  7542. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7543. $model = 'doubao-seed-2-0-mini-260215';
  7544. }
  7545. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7546. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7547. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7548. if ($model === 'deepseek-chat') {
  7549. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7550. $model = 'deepseek-v4-flash';
  7551. $thinkingMode = 'disabled';
  7552. } elseif ($model === 'deepseek-reasoner') {
  7553. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7554. $model = 'deepseek-v4-flash';
  7555. $thinkingMode = 'enabled';
  7556. }
  7557. $post_data = [
  7558. 'model' => $model,
  7559. 'messages' => $messages,
  7560. // 'max_tokens' => 8192,
  7561. 'temperature' => 0.2,
  7562. 'frequency_penalty' => 0,
  7563. 'presence_penalty' => 0,
  7564. 'response_format' => ['type' => 'text'],
  7565. 'thinking' => ['type' => $thinkingMode],
  7566. 'stream' => true // 启用流式输出
  7567. ];
  7568. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7569. // 根据模型类型选择调用方法
  7570. $fullContent = '';
  7571. $fullReasoningContent = '';
  7572. $usage = [];
  7573. try {
  7574. $streamGenerator = $this->dispatchStreamByModel($post_data);
  7575. // 验证返回值类型
  7576. if (!is_iterable($streamGenerator)) {
  7577. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7578. dLog('deepseek')->error('chat流式生成器无效', [
  7579. 'generator_type' => $errorType,
  7580. 'model' => $model,
  7581. 'anime_id' => $anime_id,
  7582. 'episode_number' => $episode_number
  7583. ]);
  7584. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7585. 'type' => $errorType,
  7586. 'model' => $model
  7587. ]);
  7588. yield [
  7589. 'type' => 'error',
  7590. 'episode' => [],
  7591. 'answer' => '',
  7592. 'reasoning' => '',
  7593. 'usage' => [],
  7594. 'error' => '接口返回数据异常,请重新请求'
  7595. ];
  7596. return;
  7597. }
  7598. // 处理流式输出
  7599. foreach ($streamGenerator as $chunk) {
  7600. if (isset($chunk['type'])) {
  7601. if ($chunk['type'] === 'done') {
  7602. // 最终结果
  7603. $fullContent = $chunk['full_content'];
  7604. $fullReasoningContent = $chunk['full_reasoning'];
  7605. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7606. } else {
  7607. // 逐块yield数据
  7608. yield $chunk;
  7609. }
  7610. }
  7611. }
  7612. } catch (\Exception $e) {
  7613. // 解析上游错误详情(如 content_filter),便于日志定位与前端提示
  7614. $upstream_error = $this->resolveGptUpstreamError($e);
  7615. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7616. 'model' => $model,
  7617. 'anime_id' => $anime_id,
  7618. 'episode_number' => $episode_number,
  7619. 'upstream_status' => $upstream_error['status'],
  7620. 'upstream_code' => $upstream_error['code'],
  7621. 'upstream_body' => $upstream_error['body'],
  7622. 'trace' => $e->getTraceAsString()
  7623. ]);
  7624. logDB('deepseek', 'error', 'chat流式处理失败', [
  7625. 'error' => $e->getMessage(),
  7626. 'model' => $model,
  7627. 'upstream_status' => $upstream_error['status'],
  7628. 'upstream_code' => $upstream_error['code'],
  7629. 'upstream_body' => $upstream_error['body']
  7630. ]);
  7631. yield [
  7632. 'type' => 'error',
  7633. 'episode' => [],
  7634. 'answer' => '',
  7635. 'reasoning' => '',
  7636. 'usage' => [],
  7637. 'error' => $this->buildChatErrorForUser($e, $upstream_error)
  7638. ];
  7639. return;
  7640. }
  7641. dLog('deepseek')->info('完整内容: '.$fullContent);
  7642. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7643. // 处理完整内容并返回最终结果
  7644. $episode_arr = handleEpisodeContent($fullContent);
  7645. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7646. if (empty($episode_arr['acts'])) {
  7647. // 未生成剧本相关内容,保存对话记录并返回提示
  7648. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  7649. try {
  7650. $now = date('Y-m-d H:i:s');
  7651. // 保存对话记录
  7652. $records = [
  7653. [
  7654. 'uid' => $uid,
  7655. 'anime_id' => $anime_id,
  7656. 'sequence' => $episode_number,
  7657. 'role' => 'user',
  7658. 'content' => $prompt,
  7659. 'created_at' => $now,
  7660. 'updated_at' => $now
  7661. ],
  7662. [
  7663. 'uid' => $uid,
  7664. 'anime_id' => $anime_id,
  7665. 'sequence' => $episode_number,
  7666. 'role' => 'assistant',
  7667. 'content' => $fullContent,
  7668. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7669. 'created_at' => $now,
  7670. 'updated_at' => $now
  7671. ]
  7672. ];
  7673. DB::table('mp_anime_records')->insert($records);
  7674. } catch (\Exception $e) {
  7675. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7676. }
  7677. yield [
  7678. 'type' => 'done',
  7679. 'episode' => [],
  7680. 'answer' => $fullContent,
  7681. 'reasoning' => $fullReasoningContent,
  7682. 'usage' => $usage,
  7683. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  7684. ];
  7685. return;
  7686. }
  7687. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  7688. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  7689. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  7690. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  7691. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  7692. $existing_props = is_array($existing_props) ? $existing_props : [];
  7693. $now = date('Y-m-d H:i:s');
  7694. try {
  7695. DB::beginTransaction();
  7696. $saveResult = $this->saveEpisodeVersionData(
  7697. $anime_id,
  7698. $episode_number,
  7699. $episode_arr,
  7700. $existing_roles,
  7701. $existing_scenes,
  7702. $existing_props,
  7703. $current_episode,
  7704. $base_episode,
  7705. $is_regenerate_version,
  7706. $content,
  7707. $now
  7708. );
  7709. $episode = $saveResult['episode'];
  7710. $episode_id = $saveResult['episode_id'];
  7711. $merged_roles = $saveResult['merged_roles'];
  7712. $merged_scenes = $saveResult['merged_scenes'];
  7713. $merged_props = $saveResult['merged_props'];
  7714. $record_content = $origin_prompt;
  7715. if ($uploaded_content !== '') {
  7716. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  7717. }
  7718. $records = [
  7719. [
  7720. 'uid' => $uid,
  7721. 'anime_id' => $anime_id,
  7722. 'role' => 'user',
  7723. 'content' => $record_content,
  7724. 'sequence' => $episode_number,
  7725. 'episode_id' => $episode_id,
  7726. 'created_at' => $now,
  7727. 'updated_at' => $now
  7728. ],
  7729. [
  7730. 'uid' => $uid,
  7731. 'anime_id' => $anime_id,
  7732. 'role' => 'assistant',
  7733. 'content' => $fullContent,
  7734. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7735. 'sequence' => $episode_number,
  7736. 'episode_id' => $episode_id,
  7737. 'created_at' => $now,
  7738. 'updated_at' => $now
  7739. ]
  7740. ];
  7741. $boolen4 = DB::table('mp_anime_records')->insert($records);
  7742. if (!$boolen4) {
  7743. Utils::throwError('20003:对话记录保存失败');
  7744. }
  7745. // 保存模型和内容到anime表
  7746. $update_anime_data = [
  7747. 'model' => $model,
  7748. 'updated_at' => $now
  7749. ];
  7750. if ($uploaded_content) {
  7751. $update_anime_data['content'] = $uploaded_content;
  7752. }
  7753. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  7754. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7755. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7756. 'anime_id' => $anime_id,
  7757. 'episode_number' => $episode_number,
  7758. 'model' => $model,
  7759. 'source' => 'chat',
  7760. ]);
  7761. }catch (\Exception $e) {
  7762. DB::rollBack();
  7763. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7764. yield [
  7765. 'type' => 'done',
  7766. 'answer' => $fullContent,
  7767. 'reasoning' => $fullReasoningContent,
  7768. 'usage' => $usage,
  7769. 'error' => $e->getMessage(),
  7770. ];
  7771. return;
  7772. }
  7773. DB::commit();
  7774. if ($is_global_generate_pics) {
  7775. // // 批量生成全局角色图片
  7776. // $this->batchSetGlobalRoleImg([
  7777. // 'anime_id' => $anime_id,
  7778. // ], true);
  7779. // // 批量生成全局场景图片
  7780. // $this->batchSetGlobalSceneImg([
  7781. // 'anime_id' => $anime_id,
  7782. // ], true);
  7783. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7784. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7785. }
  7786. $episode['episode_id'] = $episode_id;
  7787. $episode['roles'] = $merged_roles;
  7788. $episode['scenes'] = $merged_scenes;
  7789. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  7790. yield [
  7791. 'type' => 'done',
  7792. 'episode' => $episode,
  7793. 'answer' => $fullContent,
  7794. 'reasoning' => $fullReasoningContent,
  7795. 'usage' => $usage
  7796. ];
  7797. }
  7798. public function addChatForAce($data) {
  7799. $uid = Site::getUid();
  7800. $anime_id = getProp($data, 'anime_id');
  7801. if (!$anime_id) Utils::throwError('20003:请选择对话');
  7802. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  7803. if (!$anime) Utils::throwError('20003:对话不存在');
  7804. $file = getProp($data, 'file');
  7805. $content = getProp($data, 'content', '');
  7806. $bid = getProp($data, 'bid', 0);
  7807. $script_id = getProp($data, 'script_id', 0);
  7808. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  7809. $prompt = getProp($data, 'prompt');
  7810. $is_multi = getProp($anime, 'is_multi');
  7811. $is_single = (int)$is_multi !== 1;
  7812. // 积分余额预检(仅单剧集模式收费)
  7813. if ($is_single) {
  7814. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  7815. }
  7816. $extra_products = getProp($data, 'products', []);
  7817. if (!$extra_products) {
  7818. $extra_products = getProp($anime, 'extra_products');
  7819. if ($extra_products) {
  7820. $extra_products = json_decode($extra_products, true);
  7821. }else {
  7822. $extra_products = [];
  7823. }
  7824. }else {
  7825. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7826. }
  7827. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7828. $anime_script_id = getProp($anime, 'script_id');
  7829. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  7830. $cpid = Site::getCpid();
  7831. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7832. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7833. ->where('mapping.script_id', $anime_script_id)
  7834. ->where('product.cpid', $cpid)
  7835. ->where('product.is_deleted', 0);
  7836. $mappings = $script_products_mappings->select(
  7837. 'mapping.product_id',
  7838. 'mapping.episode_number',
  7839. 'product.product_name',
  7840. 'product.type',
  7841. 'product.product',
  7842. 'product.pic_prompt',
  7843. 'product.url',
  7844. 'product.pic_task_id',
  7845. 'product.pic_task_status',
  7846. 'product.three_view_image_url'
  7847. )
  7848. ->get();
  7849. // 按 product_id 分组,合并 episode_number
  7850. $productMap = [];
  7851. foreach ($mappings as $item) {
  7852. $product_id = $item->product_id;
  7853. $product_name = $item->product_name;
  7854. // 处理product_name两边的符号
  7855. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7856. if (!isset($productMap[$product_id])) {
  7857. $productMap[$product_id] = [
  7858. 'product_id' => $product_id,
  7859. 'product_name' => $product_name,
  7860. 'type' => (int)$item->type,
  7861. 'product' => (int)$item->product,
  7862. 'pic_prompt' => $item->pic_prompt,
  7863. 'url' => $item->url,
  7864. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7865. 'pic_task_id' => $item->pic_task_id,
  7866. 'pic_task_status' => $item->pic_task_status,
  7867. 'episode_numbers' => [],
  7868. ];
  7869. }
  7870. // 添加 episode_number(去重)
  7871. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7872. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7873. }
  7874. }
  7875. // 将查询到的剧本资产合并到extra_products中
  7876. // 先构建extra_products的索引(以product_id为key,用于去重)
  7877. $extraProductsMap = [];
  7878. foreach ($extra_products as $item) {
  7879. $key = getProp($item, 'product_id');
  7880. if ($key) {
  7881. $extraProductsMap[$key] = $item;
  7882. }
  7883. }
  7884. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7885. foreach ($productMap as $product) {
  7886. $product_id = $product['product_id'];
  7887. // 如果不存在则添加(不带episode_number信息)
  7888. if (!isset($extraProductsMap[$product_id])) {
  7889. $extraProductsMap[$product_id] = [
  7890. 'product_id' => $product['product_id'],
  7891. 'product_name' => $product['product_name'],
  7892. 'type' => $product['type'],
  7893. 'product' => $product['product'],
  7894. 'pic_prompt' => $product['pic_prompt'],
  7895. 'url' => $product['url'],
  7896. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  7897. 'pic_task_id' => $product['pic_task_id'],
  7898. 'pic_task_status' => $product['pic_task_status'],
  7899. ];
  7900. }
  7901. }
  7902. // 重新赋值给extra_products
  7903. $extra_products = array_values($extraProductsMap);
  7904. }
  7905. $user_anime_name = getProp($anime, 'anime_name');
  7906. // 处理提示词
  7907. if ($prompt && $extra_products) {
  7908. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7909. foreach($extra_products as $item) {
  7910. $product_name = getProp($item, 'product_name');
  7911. if ($product_name) {
  7912. // 替换 {product_name} 为 product_name
  7913. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7914. }
  7915. }
  7916. }
  7917. // 处理文本模型
  7918. $model = getProp($data, 'model');
  7919. if (!$model) {
  7920. // 用户没有输入,从anime表获取
  7921. $model = getProp($anime, 'model');
  7922. if (!$model) {
  7923. // anime表也没有,使用默认值
  7924. $model = 'deepseek-v4-pro';
  7925. }
  7926. }
  7927. // 验证模型是否在可用模型表中
  7928. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7929. $model = 'deepseek-v4-pro';
  7930. }
  7931. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7932. if ($prompt) {
  7933. $question .= "本次修改要求如下:\n{$prompt}";
  7934. }
  7935. // if (!$file && !$content && !$bid) {
  7936. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  7937. // }
  7938. // 提取文件内容
  7939. if ($file) {
  7940. $content = $this->extractFileContent($file);
  7941. if (!$content) {
  7942. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7943. }
  7944. } elseif ($script_id) {
  7945. $content = $this->getContentByScriptId($script_id);
  7946. if (!$content) {
  7947. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7948. }
  7949. } elseif ($bid) {
  7950. $content = $this->getContentByBid($bid);
  7951. if (!$content) {
  7952. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7953. }
  7954. } elseif ($content) {
  7955. $content = filterContent($content);
  7956. } else {
  7957. $content = getProp($anime, 'content');
  7958. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7959. $need_generate_content = true;
  7960. }
  7961. }
  7962. // 美术风格
  7963. $input_art_style = getProp($data, 'art_style');
  7964. if (!$input_art_style) {
  7965. $mappedArtStyle = getProp($anime, 'art_style');
  7966. }else {
  7967. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7968. }
  7969. // 判断是否需要生成原文内容
  7970. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7971. // 如果需要生成原文内容,添加额外的要求
  7972. $content_generation_requirement = $need_generate_content
  7973. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7974. : "";
  7975. // 美术风格
  7976. if (!$mappedArtStyle) {
  7977. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7978. }else {
  7979. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7980. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7981. }else {
  7982. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7983. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7984. }
  7985. }
  7986. // 构建主体、场景和道具提示词
  7987. $extra_role_prompt = "\n";
  7988. $extra_scene_prompt = "\n";
  7989. $extra_prop_prompt = "\n";
  7990. $extra_roles = [];
  7991. $extra_scenes = [];
  7992. $extra_props = [];
  7993. $ref_products = []; // 参考资产
  7994. if ($extra_products) {
  7995. foreach($extra_products as $item) {
  7996. $product = getProp($item, 'product');
  7997. $product_name = getProp($item, 'product_name');
  7998. if ($product_name == '旁白') continue;
  7999. $ref_products[$product_name] = $item;
  8000. $pic_prompt = getProp($item, 'pic_prompt');
  8001. if ((int)$product === 1) {
  8002. // 拼接角色信息
  8003. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8004. $extra_roles[$product_name] = [
  8005. 'role' => $product_name,
  8006. 'pic_prompt' => $pic_prompt,
  8007. 'url' => getProp($item, 'url', ''),
  8008. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  8009. ];
  8010. } elseif ((int)$product === 2) {
  8011. // 拼接场景信息
  8012. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8013. $extra_scenes[$product_name] = [
  8014. 'scene' => $product_name,
  8015. 'pic_prompt' => $pic_prompt,
  8016. 'url' => getProp($item, 'url', ''),
  8017. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  8018. ];
  8019. } elseif ((int)$product === 3) {
  8020. // 拼接道具信息
  8021. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8022. $extra_props[$product_name] = [
  8023. 'prop' => $product_name,
  8024. 'pic_prompt' => $pic_prompt,
  8025. 'url' => getProp($item, 'url', ''),
  8026. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  8027. ];
  8028. }
  8029. }
  8030. // 优化提示词,融入剧本
  8031. if (!empty(trim($extra_role_prompt))) {
  8032. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  8033. }
  8034. if (!empty(trim($extra_scene_prompt))) {
  8035. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  8036. }
  8037. if (!empty(trim($extra_prop_prompt))) {
  8038. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  8039. }
  8040. }
  8041. if ($anime_script_id && $is_single) {
  8042. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  8043. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  8044. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  8045. }else {
  8046. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8047. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8048. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8049. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8050. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8051. {$extra_role_prompt}";
  8052. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8053. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  8054. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8055. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8056. {$extra_scene_prompt}";
  8057. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8058. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  8059. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8060. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  8061. {$extra_prop_prompt}";
  8062. }
  8063. $systemPrompt = $is_single
  8064. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  8065. 强制要求:
  8066. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8067. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8068. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8069. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8070. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8071. 普通要求:
  8072. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  8073. $role_demo
  8074. $scene_demo
  8075. $prop_demo
  8076. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8077. 5.1片段分割逻辑(优先级从高到低):
  8078. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8079. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8080. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8081. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8082. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8083. - 片段数量格式为: 片段数量:8
  8084. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8085. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8086. 5.3分镜结构:每个分镜包含以下字段:
  8087. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  8088. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8089. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8090. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8091. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8092. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8093. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8094. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8095. - 运镜:场景+画面描述+运镜
  8096. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8097. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8098. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8099. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  8100. 6.《情绪-视听语言映射表》:
  8101. 6.1 场景空间与时间心理学 (Scene & Temporality)
  8102. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8103. -----|---------|------------|----------------
  8104. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  8105. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  8106. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  8107. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  8108. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  8109. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8110. -----|---------|------------|----------------
  8111. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  8112. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  8113. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  8114. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  8115. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  8116. --------|---------|--------------|-------------
  8117. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  8118. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  8119. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  8120. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  8121. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  8122. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  8123. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  8124. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  8125. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  8126. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  8127. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  8128. -----|---------|------------|------------
  8129. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  8130. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  8131. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  8132. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  8133. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  8134. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  8135. --------|---------|--------------|----------
  8136. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  8137. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  8138. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  8139. 6.6 声音设计与潜意识影响 (Soundscape)
  8140. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  8141. -----|---------|------------|------------------
  8142. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  8143. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  8144. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  8145. 理论基石:
  8146. - The Five C's of Cinematography by Joseph V. Mascelli
  8147. - Film Art: An Introduction by David Bordwell
  8148. - Sight, Sound, Motion by Herbert Zettl
  8149. - Notes on the Cinematograph by Robert Bresson
  8150. \n\n
  8151. 7.{$mappedArtStyle_prompt}\n\n
  8152. 示例如下:\n
  8153. ###剧本名:西昆仑
  8154. ###故事梗概
  8155. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8156. ###剧本亮点
  8157. 亮点1:绝境奇药,生死一线
  8158. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8159. 亮点2:结拜兄妹,化解尴尬
  8160. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8161. 亮点3:纤发夺命,情愫暗涌
  8162. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8163. ###人物关系
  8164. 阿雪与梁萧之间存在兄妹之情。
  8165. ###核心矛盾
  8166. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8167. ###主体列表
  8168. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8169. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8170. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8171. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8172. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8173. 全景,正面拍摄,青年女性,亚洲人。
  8174. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8175. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8176. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8177. ###美术风格
  8178. 基础画风风格词:厚涂古风
  8179. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8180. ###场景列表
  8181. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8182. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8183. 无人物。}
  8184. ###分段剧本
  8185. 片段数量:8
  8186. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8187. ##片段1
  8188. 时长:12s
  8189. 分镜1
  8190. 出场角色:刀疤脸
  8191. 场景:边境小镇街道
  8192. 出场道具:酒杯-高脚杯
  8193. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8194. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8195. 配音台词:
  8196. 背景音效:
  8197. 分镜2
  8198. 出场角色:刀疤脸
  8199. 场景:悦来酒馆
  8200. 出场道具:酒杯-高脚杯
  8201. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8202. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8203. 配音台词:
  8204. 背景音效:
  8205. 分镜3
  8206. 出场角色:刀疤脸
  8207. 场景:悦来酒馆
  8208. 出场道具:酒杯-高脚杯
  8209. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8210. 运镜:从中景推向令牌特写。
  8211. 配音台词:
  8212. 背景音效:
  8213. 分镜4
  8214. 出场角色:刀疤脸
  8215. 场景:悦来酒馆
  8216. 出场道具:酒杯-高脚杯
  8217. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8218. 运镜:极速推向酒水溅起的瞬间。
  8219. 配音台词:
  8220. 背景音效:
  8221. 分镜5
  8222. 出场角色:刀疤脸
  8223. 场景:悦来酒馆
  8224. 出场道具:酒杯-高脚杯
  8225. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8226. 运镜:固定机位,利用倾斜构图制造压迫感。
  8227. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8228. 背景音效:
  8229. \n\n"
  8230. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8231. 强制要求:\n
  8232. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8233. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8234. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8235. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8236. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8237. 普通要求:\n
  8238. 1.剧本名(必须生成)必须与文档内容高度相关
  8239. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8240. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8241. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8242. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8243. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8244. {$extra_role_prompt}
  8245. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8246. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  8247. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8248. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8249. {$extra_scene_prompt}
  8250. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8251. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  8252. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8253. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  8254. {$extra_prop_prompt}
  8255. 5.{$mappedArtStyle_prompt}\n\n
  8256. 示例如下:\n
  8257. ###剧本名:西昆仑
  8258. ###故事梗概
  8259. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8260. ###剧本亮点
  8261. 亮点1:绝境奇药,生死一线
  8262. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8263. 亮点2:结拜兄妹,化解尴尬
  8264. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8265. 亮点3:纤发夺命,情愫暗涌
  8266. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8267. ###人物关系
  8268. 阿雪与梁萧之间存在兄妹之情。
  8269. ###核心矛盾
  8270. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8271. ###主体列表
  8272. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8273. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8274. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8275. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8276. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8277. 全景,正面拍摄,青年女性,亚洲人。
  8278. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8279. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8280. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8281. ###美术风格
  8282. 基础画风风格词:厚涂古风
  8283. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8284. ###场景列表
  8285. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8286. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8287. 无人物。}
  8288. ###道具列表
  8289. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  8290. // 构建消息
  8291. $messages = [
  8292. [
  8293. 'role' => 'system',
  8294. 'content' => $systemPrompt
  8295. ],
  8296. [
  8297. 'role' => 'user',
  8298. 'content' => "以下是文档内容:
  8299. {$content}
  8300. 用户问题:
  8301. {$question}"
  8302. ]
  8303. ];
  8304. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8305. $thinkingMode = getProp($data, 'thinking', 'enabled'); // 默认思考模式
  8306. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8307. if ($model === 'deepseek-chat') {
  8308. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8309. $model = 'deepseek-v4-flash';
  8310. $thinkingMode = 'disabled';
  8311. } elseif ($model === 'deepseek-reasoner') {
  8312. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8313. $model = 'deepseek-v4-flash';
  8314. $thinkingMode = 'enabled';
  8315. }
  8316. $post_data = [
  8317. 'model' => $model,
  8318. 'messages' => $messages,
  8319. // 'max_tokens' => 8192,
  8320. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8321. 'frequency_penalty' => 0,
  8322. 'presence_penalty' => 0,
  8323. 'response_format' => ['type' => 'text'],
  8324. 'thinking' => ['type'=>$thinkingMode],
  8325. 'stream' => true // 启用流式输出
  8326. ];
  8327. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8328. // 根据模型类型选择调用方法
  8329. $fullContent = '';
  8330. $fullReasoningContent = '';
  8331. $usage = [];
  8332. try {
  8333. $streamGenerator = $this->dispatchStreamByModel($post_data);
  8334. // 验证返回值类型
  8335. if (!is_iterable($streamGenerator)) {
  8336. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8337. dLog('deepseek')->error('addChat流式生成器无效', [
  8338. 'generator_type' => $errorType,
  8339. 'model' => $model,
  8340. 'anime_id' => $anime_id
  8341. ]);
  8342. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  8343. 'type' => $errorType,
  8344. 'model' => $model
  8345. ]);
  8346. yield [
  8347. 'type' => 'error',
  8348. 'script' => [],
  8349. 'episode' => [],
  8350. 'answer' => '',
  8351. 'reasoning' => '',
  8352. 'usage' => [],
  8353. 'error' => '接口返回数据异常,请重新请求'
  8354. ];
  8355. return;
  8356. }
  8357. // 处理流式输出
  8358. foreach ($streamGenerator as $chunk) {
  8359. if (isset($chunk['type'])) {
  8360. if ($chunk['type'] === 'done') {
  8361. // 最终结果
  8362. $fullContent = $chunk['full_content'];
  8363. $fullReasoningContent = $chunk['full_reasoning'];
  8364. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8365. } else {
  8366. // 逐块yield数据
  8367. yield $chunk;
  8368. }
  8369. }
  8370. }
  8371. } catch (\Exception $e) {
  8372. // 解析上游错误详情(如 content_filter),便于日志定位与前端提示
  8373. $upstream_error = $this->resolveGptUpstreamError($e);
  8374. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  8375. 'model' => $model,
  8376. 'anime_id' => $anime_id,
  8377. 'upstream_status' => $upstream_error['status'],
  8378. 'upstream_code' => $upstream_error['code'],
  8379. 'upstream_body' => $upstream_error['body'],
  8380. 'trace' => $e->getTraceAsString()
  8381. ]);
  8382. logDB('deepseek', 'error', 'addChat流式处理失败', [
  8383. 'error' => $e->getMessage(),
  8384. 'model' => $model,
  8385. 'upstream_status' => $upstream_error['status'],
  8386. 'upstream_code' => $upstream_error['code'],
  8387. 'upstream_body' => $upstream_error['body']
  8388. ]);
  8389. yield [
  8390. 'type' => 'error',
  8391. 'script' => [],
  8392. 'episode' => [],
  8393. 'answer' => '',
  8394. 'reasoning' => '',
  8395. 'usage' => [],
  8396. 'error' => $this->buildChatErrorForUser($e, $upstream_error)
  8397. ];
  8398. return;
  8399. }
  8400. dLog('deepseek')->info('完整内容: '.$fullContent);
  8401. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8402. // 处理完整内容并返回最终结果
  8403. $script_arr = [];
  8404. if ($fullContent) {
  8405. $script_arr = handleScriptContentForAce($fullContent);
  8406. dLog('deepseek')->info('解析内容', $script_arr);
  8407. logDB('deepseek', 'info', '解析内容', $script_arr);
  8408. }
  8409. if (empty($script_arr['roles'])) {
  8410. // 未生成剧本相关内容,保存对话记录并返回提示
  8411. dLog('deepseek')->info('未生成剧本相关的内容');
  8412. try {
  8413. DB::beginTransaction();
  8414. $now = date('Y-m-d H:i:s');
  8415. // 保存对话记录
  8416. $records = [
  8417. [
  8418. 'uid' => $uid,
  8419. 'anime_id' => $anime_id,
  8420. 'sequence' => 0,
  8421. 'role' => 'user',
  8422. 'content' => $prompt,
  8423. 'created_at' => $now,
  8424. 'updated_at' => $now
  8425. ],
  8426. [
  8427. 'uid' => $uid,
  8428. 'anime_id' => $anime_id,
  8429. 'sequence' => 0,
  8430. 'role' => 'assistant',
  8431. // 'content' => $fullContent,
  8432. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  8433. 'created_at' => $now,
  8434. 'updated_at' => $now
  8435. ]
  8436. ];
  8437. DB::table('mp_anime_records')->insert($records);
  8438. DB::commit();
  8439. } catch (\Exception $e) {
  8440. DB::rollBack();
  8441. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8442. }
  8443. yield [
  8444. 'type' => 'done',
  8445. 'script' => [],
  8446. 'episode' => [],
  8447. 'answer' => $fullContent,
  8448. 'reasoning' => $fullReasoningContent,
  8449. 'usage' => $usage,
  8450. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  8451. ];
  8452. return;
  8453. }
  8454. // 如果需要生成原文内容,从script_arr中提取
  8455. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  8456. $content = $script_arr['content'];
  8457. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  8458. if (!$content) {
  8459. yield [
  8460. 'type' => 'done',
  8461. 'script' => [],
  8462. 'episode' => [],
  8463. 'answer' => $fullContent,
  8464. 'reasoning' => $fullReasoningContent,
  8465. 'usage' => $usage,
  8466. 'error' => '未生成剧本内容,请调整提示词再试'
  8467. ];
  8468. return;
  8469. }
  8470. }
  8471. // 替换美术风格
  8472. if ($mappedArtStyle !== '') {
  8473. $script_arr['art_style'] = $mappedArtStyle;
  8474. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8475. }
  8476. // 新建动漫
  8477. if ($user_anime_name == '新剧本策划') {
  8478. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  8479. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  8480. // if (!$anime_name) {
  8481. // // 未识别到剧本名,保存对话记录并返回提示
  8482. // dLog('deepseek')->info('未能识别到剧本名称');
  8483. // try {
  8484. // DB::beginTransaction();
  8485. // $now = date('Y-m-d H:i:s');
  8486. // // 保存对话记录
  8487. // $records = [
  8488. // [
  8489. // 'uid' => $uid,
  8490. // 'anime_id' => $anime_id,
  8491. // 'sequence' => 0,
  8492. // 'role' => 'user',
  8493. // 'content' => $prompt,
  8494. // 'created_at' => $now,
  8495. // 'updated_at' => $now
  8496. // ],
  8497. // [
  8498. // 'uid' => $uid,
  8499. // 'anime_id' => $anime_id,
  8500. // 'sequence' => 0,
  8501. // 'role' => 'assistant',
  8502. // 'content' => '未能生成剧本名称,请重试',
  8503. // 'created_at' => $now,
  8504. // 'updated_at' => $now
  8505. // ]
  8506. // ];
  8507. // DB::table('mp_anime_records')->insert($records);
  8508. // DB::commit();
  8509. // } catch (\Exception $e) {
  8510. // DB::rollBack();
  8511. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8512. // }
  8513. // yield [
  8514. // 'type' => 'done',
  8515. // 'script' => [],
  8516. // 'episode' => [],
  8517. // 'answer' => $fullContent,
  8518. // 'reasoning' => $fullReasoningContent,
  8519. // 'usage' => $usage,
  8520. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  8521. // ];
  8522. // return;
  8523. // }
  8524. // 确认对话名称唯一性
  8525. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  8526. $anime_name = $anime_name . '_' . date('YmdHis');
  8527. }
  8528. }else {
  8529. $anime_name = $user_anime_name;
  8530. }
  8531. // 单剧集模式:按 chatForAce 逻辑校验并重试生成剧集与分段剧本
  8532. if ($is_single) {
  8533. $max_retries = 3;
  8534. $retry_count = 0;
  8535. $validation_failed = false;
  8536. $validation_error_msg = '';
  8537. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8538. // 首次校验
  8539. if ($anime_script_id) {
  8540. if (empty($episode_arr['acts'])) {
  8541. $validation_failed = true;
  8542. $validation_error_msg = '未生成分镜剧本相关的内容';
  8543. } else {
  8544. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8545. $generated_roles = array_filter($generated_roles, function($role) {
  8546. return $role !== '旁白';
  8547. });
  8548. if (empty($generated_roles)) {
  8549. $validation_failed = true;
  8550. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8551. }
  8552. if (!$validation_failed && !empty($extra_roles)) {
  8553. $expected_roles = array_keys($extra_roles);
  8554. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8555. if (!empty($invalid_roles)) {
  8556. $validation_failed = true;
  8557. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8558. }
  8559. }
  8560. if (!$validation_failed && !empty($extra_scenes)) {
  8561. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  8562. $expected_scenes = array_keys($extra_scenes);
  8563. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8564. if (!empty($invalid_scenes)) {
  8565. $validation_failed = true;
  8566. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8567. }
  8568. }
  8569. if (!$validation_failed && !empty($extra_props)) {
  8570. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8571. $expected_props = array_keys($extra_props);
  8572. $invalid_props = array_diff($generated_props, $expected_props);
  8573. if (!empty($invalid_props)) {
  8574. $validation_failed = true;
  8575. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8576. }
  8577. }
  8578. }
  8579. } else {
  8580. if (empty($episode_arr['acts'])) {
  8581. $validation_failed = true;
  8582. $validation_error_msg = '未生成分镜剧本相关的内容';
  8583. } else {
  8584. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8585. $generated_roles = array_filter($generated_roles, function($role) {
  8586. return $role !== '旁白';
  8587. });
  8588. if (empty($generated_roles)) {
  8589. $validation_failed = true;
  8590. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8591. }
  8592. }
  8593. }
  8594. // 重试循环
  8595. while ($validation_failed && $retry_count < $max_retries) {
  8596. $retry_count++;
  8597. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  8598. 'reason' => $validation_error_msg,
  8599. 'anime_id' => $anime_id,
  8600. 'episode_number' => 1
  8601. ]);
  8602. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  8603. 'reason' => $validation_error_msg,
  8604. 'anime_id' => $anime_id
  8605. ]);
  8606. yield [
  8607. 'type' => 'retry',
  8608. 'retry_count' => $retry_count,
  8609. 'reason' => $validation_error_msg
  8610. ];
  8611. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  8612. if ($anime_script_id) {
  8613. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  8614. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  8615. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  8616. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  8617. } else {
  8618. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  8619. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  8620. }
  8621. $messages[] = [
  8622. 'role' => 'assistant',
  8623. 'content' => $fullContent
  8624. ];
  8625. $messages[] = [
  8626. 'role' => 'user',
  8627. 'content' => $retry_prompt
  8628. ];
  8629. $post_data['messages'] = $messages;
  8630. try {
  8631. $streamGenerator = $this->dispatchStreamByModel($post_data);
  8632. $fullContent = '';
  8633. $fullReasoningContent = '';
  8634. foreach ($streamGenerator as $chunk) {
  8635. if (isset($chunk['type'])) {
  8636. if ($chunk['type'] === 'done') {
  8637. $fullContent = $chunk['full_content'];
  8638. $fullReasoningContent = $chunk['full_reasoning'];
  8639. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8640. } else {
  8641. yield $chunk;
  8642. }
  8643. }
  8644. }
  8645. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  8646. // 重试接口未返回有效内容时直接失败,避免空内容被兼容放行后保存
  8647. if ($fullContent === '') {
  8648. dLog('deepseek')->error("第{$retry_count}次重试接口未返回有效内容");
  8649. yield [
  8650. 'type' => 'done',
  8651. 'script' => [],
  8652. 'episode' => [],
  8653. 'answer' => '',
  8654. 'reasoning' => $fullReasoningContent,
  8655. 'usage' => $usage,
  8656. 'error' => '生成接口未返回有效内容,请稍后重试'
  8657. ];
  8658. return;
  8659. }
  8660. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  8661. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  8662. $script_arr = handleScriptContentForAce($fullContent);
  8663. if ($mappedArtStyle !== '') {
  8664. $script_arr['art_style'] = $mappedArtStyle;
  8665. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8666. }
  8667. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8668. $validation_failed = false;
  8669. $validation_error_msg = '';
  8670. if ($anime_script_id) {
  8671. if (empty($episode_arr['acts'])) {
  8672. $validation_failed = true;
  8673. $validation_error_msg = '未生成分镜剧本相关的内容';
  8674. } else {
  8675. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8676. $generated_roles = array_filter($generated_roles, function($role) {
  8677. return $role !== '旁白';
  8678. });
  8679. if (empty($generated_roles)) {
  8680. $validation_failed = true;
  8681. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8682. }
  8683. if (!$validation_failed && !empty($extra_roles)) {
  8684. $expected_roles = array_keys($extra_roles);
  8685. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8686. if (!empty($invalid_roles)) {
  8687. $validation_failed = true;
  8688. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8689. }
  8690. }
  8691. if (!$validation_failed && !empty($extra_scenes)) {
  8692. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  8693. $expected_scenes = array_keys($extra_scenes);
  8694. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8695. if (!empty($invalid_scenes)) {
  8696. $validation_failed = true;
  8697. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8698. }
  8699. }
  8700. if (!$validation_failed && !empty($extra_props)) {
  8701. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8702. $expected_props = array_keys($extra_props);
  8703. $invalid_props = array_diff($generated_props, $expected_props);
  8704. if (!empty($invalid_props)) {
  8705. $validation_failed = true;
  8706. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8707. }
  8708. }
  8709. }
  8710. } else {
  8711. if (empty($episode_arr['acts'])) {
  8712. $validation_failed = true;
  8713. $validation_error_msg = '未生成分镜剧本相关的内容';
  8714. } else {
  8715. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8716. $generated_roles = array_filter($generated_roles, function($role) {
  8717. return $role !== '旁白';
  8718. });
  8719. if (empty($generated_roles)) {
  8720. $validation_failed = true;
  8721. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8722. }
  8723. }
  8724. }
  8725. } catch (\Exception $e) {
  8726. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  8727. 'trace' => $e->getTraceAsString()
  8728. ]);
  8729. break;
  8730. }
  8731. }
  8732. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存
  8733. if ($validation_failed && $retry_count >= $max_retries) {
  8734. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  8735. 'retry_count' => $retry_count,
  8736. 'last_error' => $validation_error_msg
  8737. ]);
  8738. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  8739. 'error' => $validation_error_msg,
  8740. 'anime_id' => $anime_id
  8741. ]);
  8742. $validation_failed = false;
  8743. $validation_error_msg = '';
  8744. }
  8745. // 如果重试后仍然失败
  8746. if ($validation_failed) {
  8747. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  8748. 'retry_count' => $retry_count,
  8749. 'last_error' => $validation_error_msg
  8750. ]);
  8751. try {
  8752. $now = date('Y-m-d H:i:s');
  8753. $records = [
  8754. [
  8755. 'uid' => $uid,
  8756. 'anime_id' => $anime_id,
  8757. 'sequence' => 1,
  8758. 'role' => 'user',
  8759. 'content' => $prompt,
  8760. 'created_at' => $now,
  8761. 'updated_at' => $now
  8762. ],
  8763. [
  8764. 'uid' => $uid,
  8765. 'anime_id' => $anime_id,
  8766. 'sequence' => 1,
  8767. 'role' => 'assistant',
  8768. 'content' => $fullContent,
  8769. 'created_at' => $now,
  8770. 'updated_at' => $now
  8771. ]
  8772. ];
  8773. DB::table('mp_anime_records')->insert($records);
  8774. } catch (\Exception $e) {
  8775. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8776. }
  8777. yield [
  8778. 'type' => 'done',
  8779. 'script' => [],
  8780. 'episode' => [],
  8781. 'answer' => $fullContent,
  8782. 'reasoning' => $fullReasoningContent,
  8783. 'usage' => $usage,
  8784. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  8785. ];
  8786. return;
  8787. }
  8788. // 验证成功,记录日志
  8789. if ($retry_count > 0) {
  8790. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  8791. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  8792. }
  8793. }
  8794. $table_data = [
  8795. 'user_id' => $uid,
  8796. 'anime_name' => $anime_name,
  8797. 'model' => $model,
  8798. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  8799. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  8800. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  8801. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  8802. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  8803. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  8804. 'art_style_type' => $input_art_style,
  8805. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  8806. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  8807. 'status' => '解析完成',
  8808. 'content' => $content,
  8809. 'is_multi' => $is_multi,
  8810. 'ace_mode' => $ace_mode,
  8811. 'generate_status' => '待执行',
  8812. 'updated_at' => date('Y-m-d H:i:s')
  8813. ];
  8814. if ($table_data['content']) {
  8815. $chapters = splitContent($table_data['content']);
  8816. $chapter_count = count($chapters);
  8817. if ($chapter_count > 0) {
  8818. $table_data['start_episode_sequence'] = 1;
  8819. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  8820. }
  8821. }
  8822. if ($extra_products) {
  8823. $table_data['extra_products'] = json_encode($extra_products, 256);
  8824. }
  8825. // 如果有剧本ID则进行绑定
  8826. if ($script_id) {
  8827. $table_data['script_id'] = $script_id;
  8828. }
  8829. $single_episode = [];
  8830. try {
  8831. DB::beginTransaction();
  8832. $now = date('Y-m-d H:i:s');
  8833. // 更新动漫大纲
  8834. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  8835. if (!$boolen) {
  8836. dLog('deepseek')->info('动漫保存失败', $table_data);
  8837. Utils::throwError('20003:动漫保存失败');
  8838. }
  8839. // 保存对话记录
  8840. $records = [
  8841. [
  8842. 'uid' => $uid,
  8843. 'anime_id' => $anime_id,
  8844. 'sequence' => 0,
  8845. 'role' => 'user',
  8846. 'content' => $prompt,
  8847. 'created_at' => date('Y-m-d H:i:s'),
  8848. 'updated_at' => date('Y-m-d H:i:s')
  8849. ],
  8850. [
  8851. 'uid' => $uid,
  8852. 'anime_id' => $anime_id,
  8853. 'sequence' => 0,
  8854. 'role' => 'assistant',
  8855. 'content' => $fullContent,
  8856. 'created_at' => date('Y-m-d H:i:s'),
  8857. 'updated_at' => date('Y-m-d H:i:s')
  8858. ]
  8859. ];
  8860. // 保存对话记录
  8861. $boolen3 = DB::table('mp_anime_records')->insert($records);
  8862. if (!$boolen3) {
  8863. Utils::throwError('20003:对话记录保存失败');
  8864. }
  8865. if ($is_single) {
  8866. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8867. if (empty($episode_arr['acts'])) {
  8868. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  8869. }
  8870. $saveResult = $this->saveEpisodeVersionData(
  8871. $anime_id,
  8872. 1,
  8873. $episode_arr,
  8874. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8875. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8876. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  8877. null,
  8878. null,
  8879. false,
  8880. $content,
  8881. $now,
  8882. $ref_products
  8883. );
  8884. $single_episode = $saveResult['episode'];
  8885. $episode_id = $saveResult['episode_id'];
  8886. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  8887. 'roles' => json_encode($saveResult['merged_roles'], 256),
  8888. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  8889. 'props' => json_encode($saveResult['merged_props'], 256),
  8890. 'updated_at' => $now
  8891. ]);
  8892. if ($boolen5 === false) {
  8893. Utils::throwError('20003:单剧集主表资源同步失败');
  8894. }
  8895. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  8896. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  8897. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  8898. $episode_record_content = '确认分镜大纲';
  8899. if ($content !== '') {
  8900. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  8901. }
  8902. $episode_records = [
  8903. [
  8904. 'uid' => $uid,
  8905. 'anime_id' => $anime_id,
  8906. 'role' => 'user',
  8907. 'content' => $episode_record_content,
  8908. 'sequence' => 1,
  8909. 'episode_id' => $episode_id,
  8910. 'created_at' => $now,
  8911. 'updated_at' => $now
  8912. ],
  8913. [
  8914. 'uid' => $uid,
  8915. 'anime_id' => $anime_id,
  8916. 'role' => 'assistant',
  8917. 'content' => $fullContent,
  8918. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8919. 'sequence' => 1,
  8920. 'episode_id' => $episode_id,
  8921. 'created_at' => $now,
  8922. 'updated_at' => $now
  8923. ]
  8924. ];
  8925. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  8926. if (!$boolen4) {
  8927. Utils::throwError('20003:单剧集分镜记录保存失败');
  8928. }
  8929. }
  8930. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8931. if ($is_single && !empty($single_episode)) {
  8932. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8933. 'anime_id' => $anime_id,
  8934. 'episode_id' => $episode_id ?? 0,
  8935. 'model' => $model,
  8936. 'source' => 'addChatForAce',
  8937. ]);
  8938. }
  8939. }catch (\Exception $e) {
  8940. DB::rollBack();
  8941. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  8942. yield [
  8943. 'type' => 'done',
  8944. 'answer' => $fullContent,
  8945. 'reasoning' => $fullReasoningContent,
  8946. 'usage' => $usage,
  8947. 'error' => $e->getMessage(),
  8948. ];
  8949. return;
  8950. }
  8951. DB::commit();
  8952. dLog('deepseek')->info('保存完毕');
  8953. if ($is_single && !empty($single_episode)) {
  8954. // $this->batchSetGlobalRoleImg([
  8955. // 'anime_id' => $anime_id,
  8956. // ]);
  8957. // $this->batchSetGlobalSceneImg([
  8958. // 'anime_id' => $anime_id,
  8959. // ]);
  8960. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8961. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8962. }
  8963. $table_data['anime_id'] = $anime_id;
  8964. $table_data['roles'] = json_decode($table_data['roles'], true);
  8965. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8966. // $table_data['episodes'] = $script_arr['episodes'];
  8967. unset($table_data['created_at']);
  8968. unset($table_data['updated_at']);
  8969. unset($table_data['status']);
  8970. dLog('deepseek')->info('开始返回');
  8971. yield [
  8972. 'type' => 'done',
  8973. 'script' => $table_data,
  8974. 'episode' => $single_episode,
  8975. 'answer' => $fullContent,
  8976. 'reasoning' => $fullReasoningContent,
  8977. 'usage' => $usage
  8978. ];
  8979. }
  8980. public function reGenerateAnimeForAce($data) {
  8981. $uid = Site::getUid();
  8982. $file = getProp($data, 'file');
  8983. $content = getProp($data, 'content', '');
  8984. $bid = getProp($data, 'bid', 0);
  8985. $script_id = getProp($data, 'script_id', 0);
  8986. $anime_id = getProp($data, 'anime_id');
  8987. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8988. if (!$anime) {
  8989. Utils::throwError('20003:该对话不存在');
  8990. }
  8991. $is_multi = getProp($anime, 'is_multi', 1);
  8992. $is_single = (int)$is_multi !== 1;
  8993. // 积分余额预检(仅单剧集模式收费)
  8994. if ($is_single) {
  8995. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  8996. }
  8997. $extra_products = getProp($data, 'products', []);
  8998. if (!$extra_products) {
  8999. $extra_products = getProp($anime, 'extra_products');
  9000. if ($extra_products) {
  9001. $extra_products = json_decode($extra_products, true);
  9002. }else {
  9003. $extra_products = [];
  9004. }
  9005. }else {
  9006. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  9007. }
  9008. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  9009. $anime_script_id = getProp($anime, 'script_id');
  9010. if ($anime_script_id && $is_single) {
  9011. $cpid = Site::getCpid();
  9012. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  9013. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9014. ->where('mapping.script_id', $anime_script_id)
  9015. ->where('product.cpid', $cpid)
  9016. ->where('product.is_deleted', 0);
  9017. $mappings = $script_products_mappings->select(
  9018. 'mapping.product_id',
  9019. 'mapping.episode_number',
  9020. 'product.product_name',
  9021. 'product.type',
  9022. 'product.product',
  9023. 'product.pic_prompt',
  9024. 'product.url',
  9025. 'product.pic_task_id',
  9026. 'product.pic_task_status',
  9027. 'product.three_view_image_url'
  9028. )
  9029. ->get();
  9030. // 按 product_id 分组,合并 episode_number
  9031. $productMap = [];
  9032. foreach ($mappings as $item) {
  9033. $product_id = $item->product_id;
  9034. $product_name = $item->product_name;
  9035. // 处理product_name两边的符号
  9036. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  9037. if (!isset($productMap[$product_id])) {
  9038. $productMap[$product_id] = [
  9039. 'product_id' => $product_id,
  9040. 'product_name' => $product_name,
  9041. 'type' => (int)$item->type,
  9042. 'product' => (int)$item->product,
  9043. 'pic_prompt' => $item->pic_prompt,
  9044. 'url' => $item->url,
  9045. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9046. 'pic_task_id' => $item->pic_task_id,
  9047. 'pic_task_status' => $item->pic_task_status,
  9048. 'episode_numbers' => [],
  9049. ];
  9050. }
  9051. // 添加 episode_number(去重)
  9052. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  9053. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  9054. }
  9055. }
  9056. // 将查询到的剧本资产合并到extra_products中
  9057. // 先构建extra_products的索引(以product_id为key,用于去重)
  9058. $extraProductsMap = [];
  9059. foreach ($extra_products as $item) {
  9060. $key = getProp($item, 'product_id');
  9061. if ($key) {
  9062. $extraProductsMap[$key] = $item;
  9063. }
  9064. }
  9065. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  9066. foreach ($productMap as $product) {
  9067. $product_id = $product['product_id'];
  9068. // 如果不存在则添加(不带episode_number信息)
  9069. if (!isset($extraProductsMap[$product_id])) {
  9070. $extraProductsMap[$product_id] = [
  9071. 'product_id' => $product['product_id'],
  9072. 'product_name' => $product['product_name'],
  9073. 'type' => $product['type'],
  9074. 'product' => $product['product'],
  9075. 'pic_prompt' => $product['pic_prompt'],
  9076. 'url' => $product['url'],
  9077. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  9078. 'pic_task_id' => $product['pic_task_id'],
  9079. 'pic_task_status' => $product['pic_task_status'],
  9080. ];
  9081. }
  9082. }
  9083. // 重新赋值给extra_products
  9084. $extra_products = array_values($extraProductsMap);
  9085. }
  9086. $user_anime_name = getProp($anime, 'anime_name');
  9087. $prompt = getProp($data, 'prompt');
  9088. // 处理提示词
  9089. if ($prompt && $extra_products) {
  9090. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  9091. foreach($extra_products as $item) {
  9092. $product_name = getProp($item, 'product_name');
  9093. if ($product_name) {
  9094. // 替换 {product_name} 为 product_name
  9095. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  9096. }
  9097. }
  9098. }
  9099. // 处理文本模型
  9100. $model = getProp($data, 'model');
  9101. if (!$model) {
  9102. // 用户没有输入,从anime表获取
  9103. $model = getProp($anime, 'model');
  9104. if (!$model) {
  9105. // anime表也没有,使用默认值
  9106. $model = 'deepseek-v4-pro';
  9107. }
  9108. }
  9109. // 验证模型是否在可用模型表中
  9110. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9111. $model = 'deepseek-v4-pro';
  9112. }
  9113. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  9114. if ($is_single) {
  9115. $episode_exists = DB::table('mp_anime_episodes')
  9116. ->where('anime_id', $anime_id)
  9117. ->where('sequence', 1)
  9118. ->exists();
  9119. if ($episode_exists) {
  9120. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  9121. }
  9122. }
  9123. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  9124. if ($prompt) {
  9125. $question .= "本次修改要求如下:\n{$prompt}";
  9126. }
  9127. // 提取文件内容
  9128. if ($file) {
  9129. $content = $this->extractFileContent($file);
  9130. if (!$content) {
  9131. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  9132. }
  9133. } elseif ($script_id) {
  9134. $content = $this->getContentByScriptId($script_id);
  9135. if (!$content) {
  9136. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  9137. }
  9138. } elseif ($bid) {
  9139. $content = $this->getContentByBid($bid);
  9140. if (!$content) {
  9141. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  9142. }
  9143. } elseif ($content) {
  9144. $content = filterContent($content);
  9145. }else {
  9146. $content = filterContent(getProp($anime, 'content'));
  9147. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  9148. $need_generate_content = true;
  9149. }
  9150. }
  9151. // 判断是否需要生成原文内容
  9152. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  9153. // 如果需要生成原文内容,添加额外的要求
  9154. $content_generation_requirement = $need_generate_content
  9155. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  9156. : "";
  9157. // 美术风格
  9158. $input_art_style = getProp($data, 'art_style');
  9159. if (!$input_art_style) {
  9160. $mappedArtStyle = getProp($anime, 'art_style');
  9161. }else {
  9162. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  9163. }
  9164. if (!$mappedArtStyle) {
  9165. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  9166. }else {
  9167. if (strstr($mappedArtStyle, '基础画风风格词')) {
  9168. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  9169. }else {
  9170. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  9171. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  9172. }
  9173. }
  9174. // 构建主体、场景和道具提示词
  9175. $extra_role_prompt = "\n";
  9176. $extra_scene_prompt = "\n";
  9177. $extra_prop_prompt = "\n";
  9178. $extra_roles = [];
  9179. $extra_scenes = [];
  9180. $extra_props = [];
  9181. $ref_products = []; // 参考资产
  9182. if ($extra_products) {
  9183. foreach($extra_products as $item) {
  9184. $product = getProp($item, 'product');
  9185. $product_name = getProp($item, 'product_name');
  9186. if ($product_name == '旁白') continue;
  9187. $ref_products[$product_name] = $item;
  9188. $pic_prompt = getProp($item, 'pic_prompt');
  9189. if ((int)$product === 1) {
  9190. // 拼接角色信息
  9191. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9192. $extra_roles[$product_name] = [
  9193. 'role' => $product_name,
  9194. 'pic_prompt' => $pic_prompt,
  9195. 'url' => getProp($item, 'url', ''),
  9196. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9197. ];
  9198. } elseif ((int)$product === 2) {
  9199. // 拼接场景信息
  9200. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9201. $extra_scenes[$product_name] = [
  9202. 'scene' => $product_name,
  9203. 'pic_prompt' => $pic_prompt,
  9204. 'url' => getProp($item, 'url', ''),
  9205. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9206. ];
  9207. } elseif ((int)$product === 3) {
  9208. // 拼接道具信息
  9209. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9210. $extra_props[$product_name] = [
  9211. 'prop' => $product_name,
  9212. 'pic_prompt' => $pic_prompt,
  9213. 'url' => getProp($item, 'url', ''),
  9214. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9215. ];
  9216. }
  9217. }
  9218. // 优化提示词,融入剧本
  9219. if (!empty(trim($extra_role_prompt))) {
  9220. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  9221. }
  9222. if (!empty(trim($extra_scene_prompt))) {
  9223. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  9224. }
  9225. if (!empty(trim($extra_prop_prompt))) {
  9226. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  9227. }
  9228. }
  9229. if ($anime_script_id && $is_single) {
  9230. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  9231. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  9232. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  9233. }else {
  9234. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  9235. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9236. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  9237. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9238. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9239. {$extra_role_prompt}";
  9240. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9241. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  9242. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9243. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  9244. {$extra_scene_prompt}";
  9245. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9246. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  9247. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  9248. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  9249. {$extra_prop_prompt}";
  9250. }
  9251. $system_message = ['role'=>'system', 'content'=>$is_single
  9252. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  9253. 强制要求:
  9254. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9255. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9256. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9257. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9258. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9259. 普通要求:
  9260. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  9261. $role_demo
  9262. $scene_demo
  9263. $prop_demo
  9264. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9265. 5.1片段分割逻辑(优先级从高到低):
  9266. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9267. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9268. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9269. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9270. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9271. - 片段数量格式为: 片段数量:8
  9272. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9273. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9274. 5.3分镜结构:每个分镜包含以下字段:
  9275. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  9276. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  9277. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9278. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9279. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9280. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9281. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9282. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9283. - 运镜:场景+画面描述+运镜
  9284. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  9285. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  9286. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9287. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  9288. 6.《情绪-视听语言映射表》:
  9289. 6.1 场景空间与时间心理学 (Scene & Temporality)
  9290. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9291. -----|---------|------------|----------------
  9292. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  9293. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  9294. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  9295. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  9296. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  9297. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9298. -----|---------|------------|----------------
  9299. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  9300. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  9301. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  9302. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  9303. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  9304. --------|---------|--------------|-------------
  9305. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  9306. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  9307. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  9308. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  9309. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  9310. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  9311. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  9312. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  9313. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  9314. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  9315. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  9316. -----|---------|------------|------------
  9317. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  9318. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  9319. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  9320. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  9321. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  9322. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  9323. --------|---------|--------------|----------
  9324. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  9325. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  9326. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  9327. 6.6 声音设计与潜意识影响 (Soundscape)
  9328. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  9329. -----|---------|------------|------------------
  9330. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  9331. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  9332. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  9333. 理论基石:
  9334. - The Five C's of Cinematography by Joseph V. Mascelli
  9335. - Film Art: An Introduction by David Bordwell
  9336. - Sight, Sound, Motion by Herbert Zettl
  9337. - Notes on the Cinematograph by Robert Bresson
  9338. \n\n
  9339. 7.{$mappedArtStyle_prompt}\n\n
  9340. 示例如下:\n
  9341. ###剧本名:西昆仑
  9342. ###故事梗概
  9343. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9344. ###剧本亮点
  9345. 亮点1:绝境奇药,生死一线
  9346. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9347. 亮点2:结拜兄妹,化解尴尬
  9348. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9349. 亮点3:纤发夺命,情愫暗涌
  9350. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9351. ###人物关系
  9352. 阿雪与梁萧之间存在兄妹之情。
  9353. ###核心矛盾
  9354. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9355. ###主体列表
  9356. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9357. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9358. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9359. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9360. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9361. 全景,正面拍摄,青年女性,亚洲人。
  9362. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9363. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9364. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9365. ###美术风格
  9366. 基础画风风格词:厚涂古风
  9367. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9368. ###场景列表
  9369. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9370. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9371. 无人物。}
  9372. ###分段剧本
  9373. 片段数量:8
  9374. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9375. ##片段1
  9376. 时长:12s
  9377. 分镜1
  9378. 出场角色:刀疤脸
  9379. 场景:边境小镇街道
  9380. 出场道具:酒杯-高脚杯
  9381. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9382. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9383. 配音台词:
  9384. 背景音效:
  9385. 分镜2
  9386. 出场角色:刀疤脸
  9387. 场景:悦来酒馆
  9388. 出场道具:酒杯-高脚杯
  9389. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9390. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9391. 配音台词:
  9392. 背景音效:
  9393. 分镜3
  9394. 出场角色:刀疤脸
  9395. 场景:悦来酒馆
  9396. 出场道具:酒杯-高脚杯
  9397. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9398. 运镜:从中景推向令牌特写。
  9399. 配音台词:
  9400. 背景音效:
  9401. 分镜4
  9402. 出场角色:刀疤脸
  9403. 场景:悦来酒馆
  9404. 出场道具:酒杯-高脚杯
  9405. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9406. 运镜:极速推向酒水溅起的瞬间。
  9407. 配音台词:
  9408. 背景音效:
  9409. 分镜5
  9410. 出场角色:刀疤脸
  9411. 场景:悦来酒馆
  9412. 出场道具:酒杯-高脚杯
  9413. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9414. 运镜:固定机位,利用倾斜构图制造压迫感。
  9415. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9416. 背景音效:
  9417. \n\n"
  9418. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  9419. 强制要求:\n
  9420. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9421. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9422. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9423. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9424. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9425. 普通要求:\n
  9426. 1.剧本名(必须生成)必须与文档内容高度相关
  9427. $role_demo
  9428. $scene_demo
  9429. $prop_demo
  9430. 5.{$mappedArtStyle_prompt}\n\n
  9431. 示例如下:\n
  9432. ###剧本名:西昆仑
  9433. ###故事梗概
  9434. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9435. ###剧本亮点
  9436. 亮点1:绝境奇药,生死一线
  9437. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9438. 亮点2:结拜兄妹,化解尴尬
  9439. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9440. 亮点3:纤发夺命,情愫暗涌
  9441. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9442. ###人物关系
  9443. 阿雪与梁萧之间存在兄妹之情。
  9444. ###核心矛盾
  9445. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9446. ###主体列表
  9447. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9448. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9449. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9450. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9451. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9452. 全景,正面拍摄,青年女性,亚洲人。
  9453. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9454. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9455. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9456. ###美术风格
  9457. 基础画风风格词:厚涂古风
  9458. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9459. ###场景列表
  9460. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9461. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9462. 无人物。}
  9463. ###道具列表
  9464. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  9465. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  9466. $episode_count = $this->extractEpisodeNumber($prompt);
  9467. if ((int)getProp($anime, 'is_multi') !== 1) {
  9468. yield [
  9469. 'type' => 'done',
  9470. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  9471. 'reasoning' => '',
  9472. 'usage' => []
  9473. ];
  9474. return;
  9475. }
  9476. if ($episode_count) {
  9477. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  9478. $system_message = [
  9479. 'role' => 'system',
  9480. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  9481. 强制要求:\n
  9482. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9483. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9484. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9485. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9486. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9487. 普通要求:\n
  9488. 1.<故事梗概>控制在200-300字左右
  9489. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  9490. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9491. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  9492. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9493. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9494. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9495. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  9496. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9497. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  9498. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  9499. 示例如下:\n
  9500. ###剧本名:西昆仑
  9501. ###故事梗概
  9502. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9503. ###剧本亮点
  9504. 亮点1:绝境奇药,生死一线
  9505. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9506. 亮点2:结拜兄妹,化解尴尬
  9507. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9508. 亮点3:纤发夺命,情愫暗涌
  9509. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9510. ###人物关系
  9511. 阿雪与梁萧之间存在兄妹之情。
  9512. ###核心矛盾
  9513. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9514. ###主体列表
  9515. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9516. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9517. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9518. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9519. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9520. 全景,正面拍摄,青年女性,亚洲人。
  9521. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9522. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9523. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9524. ###美术风格
  9525. 基础画风风格词:厚涂古风
  9526. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9527. ###场景列表
  9528. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9529. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9530. 无人物。}
  9531. ###分集详细内容
  9532. ##第1章 重生
  9533. 我重生了。
  9534. 源于一个男人偏执的暗恋。
  9535. ##第2章 相救
  9536. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  9537. 我眼睛扫向站在锅炉后的卞大伟。"
  9538. ];
  9539. // 构建消息
  9540. $messages = [
  9541. $system_message,
  9542. [
  9543. 'role' => 'user',
  9544. 'content' => "以下是文档内容:
  9545. {$content}
  9546. 用户问题:
  9547. {$question}"
  9548. ]
  9549. ];
  9550. }else {
  9551. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  9552. // 构建消息
  9553. $messages = [
  9554. $system_message,
  9555. [
  9556. 'role' => 'user',
  9557. 'content' => "以下是文档内容:
  9558. {$content}
  9559. 用户问题:
  9560. {$question}"
  9561. ]
  9562. ];
  9563. }else {
  9564. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  9565. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  9566. return (array)$value;
  9567. })->toArray();
  9568. array_unshift($messages, $system_message);
  9569. $messages[] = [
  9570. 'role' => 'user',
  9571. 'content' => $prompt
  9572. ];
  9573. }
  9574. }
  9575. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  9576. $thinkingMode = getProp($data, 'thinking', 'enabled'); // 默认非思考模式
  9577. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  9578. if ($model === 'deepseek-chat') {
  9579. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  9580. $model = 'deepseek-v4-flash';
  9581. $thinkingMode = 'disabled';
  9582. } elseif ($model === 'deepseek-reasoner') {
  9583. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  9584. $model = 'deepseek-v4-flash';
  9585. $thinkingMode = 'enabled';
  9586. }
  9587. $post_data = [
  9588. 'model' => $model,
  9589. 'messages' => $messages,
  9590. // 'max_tokens' => 8192,
  9591. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9592. 'frequency_penalty' => 0,
  9593. 'presence_penalty' => 0,
  9594. 'response_format' => ['type' => 'text'],
  9595. 'thinking' => ['type' => $thinkingMode],
  9596. 'stream' => true // 启用流式输出
  9597. ];
  9598. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9599. // 根据模型类型选择调用方法
  9600. $fullContent = '';
  9601. $fullReasoningContent = '';
  9602. $usage = [];
  9603. // dd($post_data);
  9604. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  9605. try {
  9606. $streamGenerator = $this->dispatchStreamByModel($post_data);
  9607. // 验证返回值类型
  9608. if (!is_iterable($streamGenerator)) {
  9609. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  9610. dLog('deepseek')->error('方法名流式生成器无效', [
  9611. 'generator_type' => $errorType,
  9612. 'model' => $model,
  9613. // 添加其他上下文信息
  9614. ]);
  9615. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  9616. 'type' => $errorType,
  9617. 'model' => $model
  9618. ]);
  9619. yield [
  9620. 'type' => 'error',
  9621. // 根据方法返回相应的空数据结构
  9622. 'answer' => '',
  9623. 'reasoning' => '',
  9624. 'usage' => [],
  9625. 'error' => '接口返回数据异常,请重新请求'
  9626. ];
  9627. return;
  9628. }
  9629. // 处理流式输出
  9630. foreach ($streamGenerator as $chunk) {
  9631. if (isset($chunk['type'])) {
  9632. if ($chunk['type'] === 'done') {
  9633. $fullContent = $chunk['full_content'];
  9634. $fullReasoningContent = $chunk['full_reasoning'];
  9635. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9636. } else {
  9637. yield $chunk;
  9638. }
  9639. }
  9640. }
  9641. } catch (\Exception $e) {
  9642. // 解析上游错误详情(如 content_filter),便于日志定位与前端提示
  9643. $upstream_error = $this->resolveGptUpstreamError($e);
  9644. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  9645. 'model' => $model,
  9646. 'upstream_status' => $upstream_error['status'],
  9647. 'upstream_code' => $upstream_error['code'],
  9648. 'upstream_body' => $upstream_error['body'],
  9649. 'trace' => $e->getTraceAsString()
  9650. ]);
  9651. logDB('deepseek', 'error', '方法名流式处理失败', [
  9652. 'error' => $e->getMessage(),
  9653. 'model' => $model,
  9654. 'upstream_status' => $upstream_error['status'],
  9655. 'upstream_code' => $upstream_error['code'],
  9656. 'upstream_body' => $upstream_error['body']
  9657. ]);
  9658. yield [
  9659. 'type' => 'error',
  9660. // 根据方法返回相应的空数据结构
  9661. 'answer' => '',
  9662. 'reasoning' => '',
  9663. 'usage' => [],
  9664. 'error' => $this->buildChatErrorForUser($e, $upstream_error)
  9665. ];
  9666. return;
  9667. }
  9668. dLog('deepseek')->info('完整内容: '.$fullContent);
  9669. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  9670. // 处理完整内容并返回最终结果
  9671. $script_arr = [];
  9672. if ($fullContent) {
  9673. $script_arr = handleScriptContentForAce($fullContent);
  9674. dLog('deepseek')->info('解析内容', $script_arr);
  9675. logDB('deepseek', 'info', '解析内容', $script_arr);
  9676. }
  9677. if (empty($script_arr['roles'])) {
  9678. // 未生成剧本相关内容,保存对话记录并返回提示
  9679. dLog('deepseek')->info('未生成剧本相关的内容');
  9680. try {
  9681. $now = date('Y-m-d H:i:s');
  9682. // 保存对话记录
  9683. $records = [
  9684. [
  9685. 'uid' => $uid,
  9686. 'anime_id' => $anime_id,
  9687. 'sequence' => 0,
  9688. 'role' => 'user',
  9689. 'content' => $prompt,
  9690. 'created_at' => $now,
  9691. 'updated_at' => $now
  9692. ],
  9693. [
  9694. 'uid' => $uid,
  9695. 'anime_id' => $anime_id,
  9696. 'sequence' => 0,
  9697. 'role' => 'assistant',
  9698. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  9699. 'created_at' => $now,
  9700. 'updated_at' => $now
  9701. ]
  9702. ];
  9703. DB::table('mp_anime_records')->insert($records);
  9704. } catch (\Exception $e) {
  9705. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9706. }
  9707. yield [
  9708. 'type' => 'done',
  9709. 'script' => [],
  9710. 'episode' => [],
  9711. 'answer' => $fullContent,
  9712. 'reasoning' => $fullReasoningContent,
  9713. 'usage' => $usage,
  9714. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  9715. ];
  9716. return;
  9717. }
  9718. // 替换美术风格
  9719. if ($mappedArtStyle !== '') {
  9720. $script_arr['art_style'] = $mappedArtStyle;
  9721. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  9722. }
  9723. if ($user_anime_name != '新剧本策划') {
  9724. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  9725. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  9726. // 确认对话名称唯一性
  9727. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  9728. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  9729. }
  9730. }else {
  9731. $anime_name = $user_anime_name;
  9732. }
  9733. // 单剧集模式:按 chatForAce 逻辑校验并重试生成剧集与分段剧本
  9734. if ($is_single) {
  9735. $max_retries = 3;
  9736. $retry_count = 0;
  9737. $validation_failed = false;
  9738. $validation_error_msg = '';
  9739. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9740. // 首次校验
  9741. if ($anime_script_id) {
  9742. if (empty($episode_arr['acts'])) {
  9743. $validation_failed = true;
  9744. $validation_error_msg = '未生成分镜剧本相关的内容';
  9745. } else {
  9746. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9747. $generated_roles = array_filter($generated_roles, function($role) {
  9748. return $role !== '旁白';
  9749. });
  9750. if (empty($generated_roles)) {
  9751. $validation_failed = true;
  9752. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9753. }
  9754. if (!$validation_failed && !empty($extra_roles)) {
  9755. $expected_roles = array_keys($extra_roles);
  9756. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9757. if (!empty($invalid_roles)) {
  9758. $validation_failed = true;
  9759. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9760. }
  9761. }
  9762. if (!$validation_failed && !empty($extra_scenes)) {
  9763. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  9764. $expected_scenes = array_keys($extra_scenes);
  9765. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9766. if (!empty($invalid_scenes)) {
  9767. $validation_failed = true;
  9768. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9769. }
  9770. }
  9771. if (!$validation_failed && !empty($extra_props)) {
  9772. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9773. $expected_props = array_keys($extra_props);
  9774. $invalid_props = array_diff($generated_props, $expected_props);
  9775. if (!empty($invalid_props)) {
  9776. $validation_failed = true;
  9777. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9778. }
  9779. }
  9780. }
  9781. } else {
  9782. if (empty($episode_arr['acts'])) {
  9783. $validation_failed = true;
  9784. $validation_error_msg = '未生成分镜剧本相关的内容';
  9785. } else {
  9786. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9787. $generated_roles = array_filter($generated_roles, function($role) {
  9788. return $role !== '旁白';
  9789. });
  9790. if (empty($generated_roles)) {
  9791. $validation_failed = true;
  9792. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9793. }
  9794. }
  9795. }
  9796. // 重试循环
  9797. while ($validation_failed && $retry_count < $max_retries) {
  9798. $retry_count++;
  9799. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  9800. 'reason' => $validation_error_msg,
  9801. 'anime_id' => $anime_id,
  9802. 'episode_number' => 1
  9803. ]);
  9804. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  9805. 'reason' => $validation_error_msg,
  9806. 'anime_id' => $anime_id
  9807. ]);
  9808. yield [
  9809. 'type' => 'retry',
  9810. 'retry_count' => $retry_count,
  9811. 'reason' => $validation_error_msg
  9812. ];
  9813. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  9814. if ($anime_script_id) {
  9815. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  9816. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9817. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  9818. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  9819. } else {
  9820. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9821. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  9822. }
  9823. $messages[] = [
  9824. 'role' => 'assistant',
  9825. 'content' => $fullContent
  9826. ];
  9827. $messages[] = [
  9828. 'role' => 'user',
  9829. 'content' => $retry_prompt
  9830. ];
  9831. $post_data['messages'] = $messages;
  9832. try {
  9833. $streamGenerator = $this->dispatchStreamByModel($post_data);
  9834. $fullContent = '';
  9835. $fullReasoningContent = '';
  9836. foreach ($streamGenerator as $chunk) {
  9837. if (isset($chunk['type'])) {
  9838. if ($chunk['type'] === 'done') {
  9839. $fullContent = $chunk['full_content'];
  9840. $fullReasoningContent = $chunk['full_reasoning'];
  9841. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9842. } else {
  9843. yield $chunk;
  9844. }
  9845. }
  9846. }
  9847. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9848. // 重试接口未返回有效内容时直接失败,避免空内容被兼容放行后保存
  9849. if ($fullContent === '') {
  9850. dLog('deepseek')->error("第{$retry_count}次重试接口未返回有效内容");
  9851. yield [
  9852. 'type' => 'done',
  9853. 'script' => [],
  9854. 'episode' => [],
  9855. 'answer' => '',
  9856. 'reasoning' => $fullReasoningContent,
  9857. 'usage' => $usage,
  9858. 'error' => '生成接口未返回有效内容,请稍后重试'
  9859. ];
  9860. return;
  9861. }
  9862. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  9863. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  9864. $script_arr = handleScriptContentForAce($fullContent);
  9865. if ($mappedArtStyle !== '') {
  9866. $script_arr['art_style'] = $mappedArtStyle;
  9867. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  9868. }
  9869. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9870. $validation_failed = false;
  9871. $validation_error_msg = '';
  9872. if ($anime_script_id) {
  9873. if (empty($episode_arr['acts'])) {
  9874. $validation_failed = true;
  9875. $validation_error_msg = '未生成分镜剧本相关的内容';
  9876. } else {
  9877. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9878. $generated_roles = array_filter($generated_roles, function($role) {
  9879. return $role !== '旁白';
  9880. });
  9881. if (empty($generated_roles)) {
  9882. $validation_failed = true;
  9883. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9884. }
  9885. if (!$validation_failed && !empty($extra_roles)) {
  9886. $expected_roles = array_keys($extra_roles);
  9887. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9888. if (!empty($invalid_roles)) {
  9889. $validation_failed = true;
  9890. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9891. }
  9892. }
  9893. if (!$validation_failed && !empty($extra_scenes)) {
  9894. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  9895. $expected_scenes = array_keys($extra_scenes);
  9896. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9897. if (!empty($invalid_scenes)) {
  9898. $validation_failed = true;
  9899. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9900. }
  9901. }
  9902. if (!$validation_failed && !empty($extra_props)) {
  9903. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9904. $expected_props = array_keys($extra_props);
  9905. $invalid_props = array_diff($generated_props, $expected_props);
  9906. if (!empty($invalid_props)) {
  9907. $validation_failed = true;
  9908. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9909. }
  9910. }
  9911. }
  9912. } else {
  9913. if (empty($episode_arr['acts'])) {
  9914. $validation_failed = true;
  9915. $validation_error_msg = '未生成分镜剧本相关的内容';
  9916. } else {
  9917. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9918. $generated_roles = array_filter($generated_roles, function($role) {
  9919. return $role !== '旁白';
  9920. });
  9921. if (empty($generated_roles)) {
  9922. $validation_failed = true;
  9923. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9924. }
  9925. }
  9926. }
  9927. } catch (\Exception $e) {
  9928. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  9929. 'trace' => $e->getTraceAsString()
  9930. ]);
  9931. break;
  9932. }
  9933. }
  9934. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存
  9935. if ($validation_failed && $retry_count >= $max_retries) {
  9936. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  9937. 'retry_count' => $retry_count,
  9938. 'last_error' => $validation_error_msg
  9939. ]);
  9940. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  9941. 'error' => $validation_error_msg,
  9942. 'anime_id' => $anime_id
  9943. ]);
  9944. $validation_failed = false;
  9945. $validation_error_msg = '';
  9946. }
  9947. // 如果重试后仍然失败
  9948. if ($validation_failed) {
  9949. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  9950. 'retry_count' => $retry_count,
  9951. 'last_error' => $validation_error_msg
  9952. ]);
  9953. try {
  9954. $now = date('Y-m-d H:i:s');
  9955. $records = [
  9956. [
  9957. 'uid' => $uid,
  9958. 'anime_id' => $anime_id,
  9959. 'sequence' => 1,
  9960. 'role' => 'user',
  9961. 'content' => $prompt,
  9962. 'created_at' => $now,
  9963. 'updated_at' => $now
  9964. ],
  9965. [
  9966. 'uid' => $uid,
  9967. 'anime_id' => $anime_id,
  9968. 'sequence' => 1,
  9969. 'role' => 'assistant',
  9970. 'content' => $fullContent,
  9971. 'created_at' => $now,
  9972. 'updated_at' => $now
  9973. ]
  9974. ];
  9975. DB::table('mp_anime_records')->insert($records);
  9976. } catch (\Exception $e) {
  9977. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9978. }
  9979. yield [
  9980. 'type' => 'done',
  9981. 'script' => [],
  9982. 'episode' => [],
  9983. 'answer' => $fullContent,
  9984. 'reasoning' => $fullReasoningContent,
  9985. 'usage' => $usage,
  9986. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  9987. ];
  9988. return;
  9989. }
  9990. // 验证成功,记录日志
  9991. if ($retry_count > 0) {
  9992. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  9993. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  9994. }
  9995. }
  9996. $table_data = [
  9997. 'user_id' => $uid,
  9998. 'model' => $model,
  9999. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  10000. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  10001. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  10002. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  10003. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  10004. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  10005. 'art_style_type' => $input_art_style,
  10006. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  10007. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  10008. 'status' => '解析完成',
  10009. 'generate_status' => '待执行',
  10010. 'updated_at' => date('Y-m-d H:i:s')
  10011. ];
  10012. if ($anime_name) $table_data['anime_name'] = $anime_name;
  10013. // 如果是修改集数,则将content内容更新(会改变原文)
  10014. if (isset($episode_count) && $episode_count > 0) {
  10015. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  10016. $table_data['start_episode_sequence'] = 1;
  10017. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  10018. }else {
  10019. // 如果需要生成原文内容,从script_arr中提取
  10020. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  10021. $table_data['content'] = $script_arr['content'];
  10022. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  10023. if (!$table_data['content']) {
  10024. yield [
  10025. 'type' => 'done',
  10026. 'script' => [],
  10027. 'episode' => [],
  10028. 'answer' => $fullContent,
  10029. 'reasoning' => $fullReasoningContent,
  10030. 'usage' => $usage,
  10031. 'error' => '未生成剧本内容,请调整提示词再试'
  10032. ];
  10033. return;
  10034. }
  10035. }
  10036. if (isset($table_data['content']) && $table_data['content']) {
  10037. $chapters = splitContent($table_data['content']);
  10038. $chapter_count = count($chapters);
  10039. if ($chapter_count > 0) {
  10040. $table_data['start_episode_sequence'] = 1;
  10041. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  10042. }
  10043. }
  10044. }
  10045. if ($extra_products) {
  10046. $table_data['extra_products'] = json_encode($extra_products, 256);
  10047. }
  10048. $single_episode = [];
  10049. try {
  10050. DB::beginTransaction();
  10051. $now = date('Y-m-d H:i:s');
  10052. // 更新动漫大纲
  10053. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  10054. if (!$boolen) {
  10055. dLog('deepseek')->info('对话修改失败', $table_data);
  10056. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  10057. Utils::throwError('20003:对话修改失败');
  10058. }
  10059. // 保存对话记录
  10060. $records = [
  10061. [
  10062. 'uid' => $uid,
  10063. 'anime_id' => $anime_id,
  10064. 'sequence' => 0,
  10065. 'role' => 'user',
  10066. 'content' => $prompt,
  10067. 'created_at' => $now,
  10068. 'updated_at' => $now
  10069. ],
  10070. [
  10071. 'uid' => $uid,
  10072. 'anime_id' => $anime_id,
  10073. 'sequence' => 0,
  10074. 'role' => 'assistant',
  10075. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  10076. 'content' => $fullContent,
  10077. 'created_at' => $now,
  10078. 'updated_at' => $now
  10079. ]
  10080. ];
  10081. // 保存对话记录
  10082. $boolen3 = DB::table('mp_anime_records')->insert($records);
  10083. if (!$boolen3) {
  10084. Utils::throwError('20003:对话记录保存失败');
  10085. }
  10086. // 单剧集模式:生成并保存剧集信息
  10087. if ($is_single) {
  10088. $anime_name = getProp($anime, 'anime_name', '未命名');
  10089. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  10090. if (empty($episode_arr['acts'])) {
  10091. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  10092. }
  10093. $saveResult = $this->saveEpisodeVersionData(
  10094. $anime_id,
  10095. 1,
  10096. $episode_arr,
  10097. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  10098. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  10099. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  10100. null,
  10101. null,
  10102. false,
  10103. $content,
  10104. $now,
  10105. $ref_products
  10106. );
  10107. $single_episode = $saveResult['episode'];
  10108. $episode_id = $saveResult['episode_id'];
  10109. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  10110. 'roles' => json_encode($saveResult['merged_roles'], 256),
  10111. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  10112. 'props' => json_encode($saveResult['merged_props'], 256),
  10113. 'updated_at' => $now
  10114. ]);
  10115. if ($boolen5 === false) {
  10116. Utils::throwError('20003:单剧集主表资源同步失败');
  10117. }
  10118. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  10119. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  10120. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  10121. $episode_record_content = '确认分镜大纲';
  10122. if ($content !== '') {
  10123. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  10124. }
  10125. $episode_records = [
  10126. [
  10127. 'uid' => $uid,
  10128. 'anime_id' => $anime_id,
  10129. 'role' => 'user',
  10130. 'content' => $episode_record_content,
  10131. 'sequence' => 1,
  10132. 'episode_id' => $episode_id,
  10133. 'created_at' => $now,
  10134. 'updated_at' => $now
  10135. ],
  10136. [
  10137. 'uid' => $uid,
  10138. 'anime_id' => $anime_id,
  10139. 'role' => 'assistant',
  10140. 'content' => $fullContent,
  10141. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  10142. 'sequence' => 1,
  10143. 'episode_id' => $episode_id,
  10144. 'created_at' => $now,
  10145. 'updated_at' => $now
  10146. ]
  10147. ];
  10148. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  10149. if (!$boolen4) {
  10150. Utils::throwError('20003:单剧集分镜记录保存失败');
  10151. }
  10152. }
  10153. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  10154. if ($is_single && !empty($single_episode)) {
  10155. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  10156. 'anime_id' => $anime_id,
  10157. 'episode_id' => $episode_id ?? 0,
  10158. 'model' => $model,
  10159. 'source' => 'reGenerateAnimeForAce',
  10160. ]);
  10161. }
  10162. }catch (\Exception $e) {
  10163. DB::rollBack();
  10164. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  10165. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  10166. yield [
  10167. 'type' => 'done',
  10168. 'answer' => $fullContent,
  10169. 'reasoning' => $fullReasoningContent,
  10170. 'usage' => $usage,
  10171. 'error' => $e->getMessage(),
  10172. ];
  10173. return;
  10174. }
  10175. DB::commit();
  10176. dLog('deepseek')->info('保存完毕');
  10177. if ($is_single && !empty($single_episode)) {
  10178. // $this->batchSetGlobalRoleImg([
  10179. // 'anime_id' => $anime_id,
  10180. // ]);
  10181. // $this->batchSetGlobalSceneImg([
  10182. // 'anime_id' => $anime_id,
  10183. // ]);
  10184. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  10185. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  10186. }
  10187. $table_data['anime_id'] = $anime_id;
  10188. $table_data['roles'] = json_decode($table_data['roles'], true);
  10189. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  10190. $table_data['props'] = json_decode($table_data['props'], true);
  10191. unset($table_data['updated_at']);
  10192. unset($table_data['status']);
  10193. yield [
  10194. 'type' => 'done',
  10195. 'script' => $table_data,
  10196. 'episode' => $single_episode,
  10197. 'answer' => $fullContent,
  10198. 'reasoning' => $fullReasoningContent,
  10199. 'usage' => $usage
  10200. ];
  10201. }
  10202. public function chatForAce($data) {
  10203. $uid = Site::getUid();
  10204. // 积分余额预检(不足直接报错)
  10205. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  10206. $anime_id = getProp($data, 'anime_id');
  10207. $file = getProp($data, 'file');
  10208. $content = getProp($data, 'content', '');
  10209. $bid = getProp($data, 'bid', 0);
  10210. $script_id = getProp($data, 'script_id', 0);
  10211. $episode_number = getProp($data, 'episode_number', 1);
  10212. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10213. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10214. if (!$anime) Utils::throwError('20003:该对话不存在!');
  10215. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  10216. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  10217. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  10218. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  10219. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  10220. $roles = is_array($roles) ? $roles : [];
  10221. $scenes = is_array($scenes) ? $scenes : [];
  10222. $extra_products = getProp($data, 'products', []);
  10223. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  10224. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  10225. $anime_script_id = getProp($anime, 'script_id');
  10226. if ($anime_script_id) {
  10227. $cpid = Site::getCpid();
  10228. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  10229. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  10230. ->where('mapping.script_id', $anime_script_id)
  10231. ->where('product.cpid', $cpid)
  10232. ->where('product.is_deleted', 0);
  10233. // 如果提供了 episode_number,则过滤指定集数
  10234. if ($episode_number !== null && $episode_number !== '') {
  10235. $script_products_mappings->where('mapping.episode_number', $episode_number);
  10236. }
  10237. $mappings = $script_products_mappings->select(
  10238. 'mapping.product_id',
  10239. 'mapping.episode_number',
  10240. 'product.product_name',
  10241. 'product.type',
  10242. 'product.product',
  10243. 'product.pic_prompt',
  10244. 'product.url',
  10245. 'product.pic_task_id',
  10246. 'product.pic_task_status',
  10247. 'product.three_view_image_url'
  10248. )
  10249. ->get();
  10250. // 按 product_id 分组,合并 episode_number
  10251. $productMap = [];
  10252. foreach ($mappings as $item) {
  10253. $product_id = $item->product_id;
  10254. $product_name = $item->product_name;
  10255. // 处理product_name两边的符号
  10256. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  10257. if (!isset($productMap[$product_id])) {
  10258. $productMap[$product_id] = [
  10259. 'product_id' => $product_id,
  10260. 'product_name' => $product_name,
  10261. 'type' => (int)$item->type,
  10262. 'product' => (int)$item->product,
  10263. 'pic_prompt' => $item->pic_prompt,
  10264. 'url' => $item->url,
  10265. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  10266. 'pic_task_id' => $item->pic_task_id,
  10267. 'pic_task_status' => $item->pic_task_status,
  10268. 'episode_numbers' => [],
  10269. ];
  10270. }
  10271. // 添加 episode_number(去重)
  10272. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  10273. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  10274. }
  10275. }
  10276. // 将查询到的剧本资产合并到extra_products中
  10277. // 先构建extra_products的索引(以product_id+episode_number为key)
  10278. $extraProductsMap = [];
  10279. foreach ($extra_products as $item) {
  10280. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  10281. $extraProductsMap[$key] = $item;
  10282. }
  10283. // 合并剧本资产(去重:product_id+episode_number)
  10284. foreach ($productMap as $product) {
  10285. foreach ($product['episode_numbers'] as $ep_num) {
  10286. $key = $product['product_id'] . '_' . $ep_num;
  10287. // 如果不存在则添加
  10288. if (!isset($extraProductsMap[$key])) {
  10289. $extraProductsMap[$key] = [
  10290. 'product_id' => $product['product_id'],
  10291. 'product_name' => $product['product_name'],
  10292. 'type' => $product['type'],
  10293. 'product' => $product['product'],
  10294. 'pic_prompt' => $product['pic_prompt'],
  10295. 'url' => $product['url'],
  10296. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  10297. 'pic_task_id' => $product['pic_task_id'],
  10298. 'pic_task_status' => $product['pic_task_status'],
  10299. 'episode_number' => $ep_num,
  10300. ];
  10301. }
  10302. }
  10303. }
  10304. // 重新赋值给extra_products
  10305. $extra_products = array_values($extraProductsMap);
  10306. }
  10307. // 处理提示词
  10308. if ($prompt && $extra_products) {
  10309. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  10310. foreach($extra_products as $item) {
  10311. $product_name = getProp($item, 'product_name');
  10312. if ($product_name) {
  10313. // 替换 {product_name} 为 product_name
  10314. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  10315. }
  10316. }
  10317. }
  10318. // 获取最后一集序号
  10319. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  10320. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  10321. // 转换主体列表和场景列表的格式
  10322. // 获取参考主体或场景
  10323. if ((int)$episode_number === 1) {
  10324. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  10325. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  10326. }else {
  10327. $prev_episode_number = $episode_number - 1;
  10328. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  10329. }
  10330. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  10331. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  10332. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  10333. // 合并anime_products和extra_products(extra_products优先,去重)
  10334. $anime_products = getProp($anime, 'extra_products');
  10335. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  10336. $ref_products = [];
  10337. foreach($anime_products as $item) {
  10338. $product_name = getProp($item, 'product_name');
  10339. $ref_products[$product_name] = $item;
  10340. }
  10341. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  10342. $extra_roles = []; // 从extra_products中提取的角色
  10343. $extra_scenes = []; // 从extra_products中提取的场景
  10344. $extra_props = []; // 从extra_products中提取的道具
  10345. if ($extra_products && is_array($extra_products)) {
  10346. foreach($extra_products as $item) {
  10347. $product = (int)getProp($item, 'product');
  10348. $product_name = getProp($item, 'product_name');
  10349. if ($product_name == '旁白') continue;
  10350. $pic_prompt = getProp($item, 'pic_prompt');
  10351. $ref_products[$product_name] = $item;
  10352. if ($product === 1) {
  10353. // 角色
  10354. $extra_roles[$product_name] = [
  10355. 'role' => $product_name,
  10356. 'pic_prompt' => $pic_prompt,
  10357. 'url' => getProp($item, 'url', ''),
  10358. ];
  10359. } elseif ($product === 2) {
  10360. // 场景
  10361. $extra_scenes[$product_name] = [
  10362. 'scene' => $product_name,
  10363. 'pic_prompt' => $pic_prompt,
  10364. 'url' => getProp($item, 'url', ''),
  10365. ];
  10366. } elseif ($product === 3) {
  10367. // 道具
  10368. $extra_props[$product_name] = [
  10369. 'prop' => $product_name,
  10370. 'pic_prompt' => $pic_prompt,
  10371. 'url' => getProp($item, 'url', ''),
  10372. ];
  10373. }
  10374. }
  10375. }
  10376. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  10377. $merged_roles = [];
  10378. foreach($ref_roles as $role) {
  10379. $role_name = getProp($role, 'role');
  10380. if (!isset($extra_roles[$role_name])) {
  10381. $merged_roles[$role_name] = $role;
  10382. }
  10383. }
  10384. // 添加extra_roles
  10385. foreach($extra_roles as $role_name => $role) {
  10386. $merged_roles[$role_name] = $role;
  10387. }
  10388. $ref_roles = array_values($merged_roles);
  10389. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  10390. $merged_scenes = [];
  10391. foreach($ref_scenes as $scene) {
  10392. $scene_name = getProp($scene, 'scene');
  10393. if (!isset($extra_scenes[$scene_name])) {
  10394. $merged_scenes[$scene_name] = $scene;
  10395. }
  10396. }
  10397. // 添加extra_scenes
  10398. foreach($extra_scenes as $scene_name => $scene) {
  10399. $merged_scenes[$scene_name] = $scene;
  10400. }
  10401. $ref_scenes = array_values($merged_scenes);
  10402. // 合并ref_props和extra_props(extra_props优先,去重)
  10403. $merged_props = [];
  10404. foreach($ref_props as $prop) {
  10405. $prop_name = getProp($prop, 'prop');
  10406. if (!isset($extra_props[$prop_name])) {
  10407. $merged_props[$prop_name] = $prop;
  10408. }
  10409. }
  10410. // 添加extra_props
  10411. foreach($extra_props as $prop_name => $prop) {
  10412. $merged_props[$prop_name] = $prop;
  10413. }
  10414. $ref_props = array_values($merged_props);
  10415. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  10416. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  10417. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  10418. // 构建强制主体、场景和道具提示词
  10419. $forced_roles_prompt = "";
  10420. $forced_scenes_prompt = "";
  10421. $forced_props_prompt = "";
  10422. if (!empty($extra_roles)) {
  10423. $forced_roles_list = "";
  10424. foreach($extra_roles as $role_name => $role) {
  10425. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  10426. }
  10427. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  10428. }
  10429. if (!empty($extra_scenes)) {
  10430. $forced_scenes_list = "";
  10431. foreach($extra_scenes as $scene_name => $scene) {
  10432. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  10433. }
  10434. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  10435. }
  10436. if (!empty($extra_props)) {
  10437. $forced_props_list = "";
  10438. foreach($extra_props as $prop_name => $prop) {
  10439. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  10440. }
  10441. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  10442. }
  10443. if ($anime_script_id) {
  10444. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  10445. }else if ($roles_content) {
  10446. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  10447. 主体范围:\n {$roles_content}\n
  10448. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  10449. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  10450. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  10451. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  10452. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  10453. }else {
  10454. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  10455. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  10456. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  10457. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  10458. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  10459. }
  10460. if ($anime_script_id) {
  10461. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  10462. }else if ($scenes_content) {
  10463. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  10464. 场景范围:\n {$scenes_content}\n
  10465. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  10466. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  10467. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  10468. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  10469. }else {
  10470. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  10471. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  10472. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  10473. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  10474. }
  10475. if ($anime_script_id) {
  10476. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  10477. }else if ($props_content) {
  10478. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  10479. 道具范围:\n {$props_content}\n
  10480. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  10481. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  10482. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  10483. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  10484. }else {
  10485. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  10486. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  10487. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  10488. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  10489. }
  10490. // 提取文件内容
  10491. if ($file) {
  10492. $uploaded_content = $this->extractFileContent($file);
  10493. if (!$uploaded_content) {
  10494. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  10495. }
  10496. } elseif ($script_id) {
  10497. $uploaded_content = $this->getContentByScriptId($script_id);
  10498. if (!$uploaded_content) {
  10499. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  10500. }
  10501. } elseif ($bid) {
  10502. $uploaded_content = $this->getContentByBid($bid);
  10503. if (!$uploaded_content) {
  10504. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  10505. }
  10506. } elseif ($content) {
  10507. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  10508. }
  10509. // elseif ($prompt) {
  10510. // $uploaded_content = filterContent($prompt);
  10511. // }
  10512. else {
  10513. $uploaded_content = '';
  10514. }
  10515. // 美术风格
  10516. $input_art_style = getProp($data, 'art_style');
  10517. if (!$input_art_style) {
  10518. $mappedArtStyle = getProp($anime, 'art_style');
  10519. }else {
  10520. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  10521. }
  10522. if (!$mappedArtStyle) {
  10523. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  10524. }else {
  10525. if (strstr($mappedArtStyle, '基础画风风格词')) {
  10526. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  10527. }else {
  10528. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  10529. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  10530. }
  10531. }
  10532. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10533. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  10534. // 强制要求:
  10535. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  10536. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  10537. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  10538. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  10539. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  10540. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  10541. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  10542. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  10543. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  10544. // 10.分镜要和场景列表、人物主体保持一致\n
  10545. // 普通要求:
  10546. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  10547. // {$role_demo}
  10548. // {$scene_demo}
  10549. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10550. // 4.1片段分割逻辑(优先级从高到低):
  10551. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10552. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10553. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10554. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10555. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10556. // - 片段数量格式为: 片段数量:8
  10557. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10558. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10559. // 4.3分镜结构:每个分镜包含以下字段:
  10560. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  10561. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  10562. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10563. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  10564. // - 运镜:场景+画面描述+运镜
  10565. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  10566. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10567. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10568. // 5.$mappedArtStyle_prompt\n\n
  10569. // 示例格式:\n
  10570. // 第1集:隐形的守护者
  10571. // ###故事梗概
  10572. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10573. // ###美术风格
  10574. // 基础画风风格词:胡金铨武侠
  10575. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10576. // ###主体列表
  10577. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10578. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10579. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10580. // ###场景列表
  10581. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10582. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10583. // ###分段剧本
  10584. // 片段数量:8
  10585. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10586. // ##片段1
  10587. // 时长:12s
  10588. // 分镜1
  10589. // 场景:边境小镇街道
  10590. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10591. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10592. // 配音台词:
  10593. // 背景音效:
  10594. // 分镜2
  10595. // 场景:悦来酒馆
  10596. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10597. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10598. // 配音台词:
  10599. // 背景音效:
  10600. // 分镜3
  10601. // 场景:悦来酒馆
  10602. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10603. // 运镜:从中景推向令牌特写。
  10604. // 配音台词:
  10605. // 背景音效:
  10606. // 分镜4
  10607. // 场景:悦来酒馆
  10608. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10609. // 运镜:极速推向酒水溅起的瞬间。
  10610. // 配音台词:
  10611. // 背景音效:
  10612. // 分镜5
  10613. // 镜头描述
  10614. // 场景:悦来酒馆
  10615. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10616. // 运镜:固定机位,利用倾斜构图制造压迫感。
  10617. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10618. // 背景音效:
  10619. // \n\n";
  10620. /*
  10621. // ====== 旧版 $demo(缓存优化前版本,动态数据内嵌在规则中间) ======
  10622. // 如需换回:删除下方新版 $demo,并把本块恢复为活动代码(去掉首尾注释标记)
  10623. // ===================================================================
  10624. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  10625. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  10626. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  10627. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  10628. 强制要求:
  10629. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  10630. 普通要求:
  10631. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  10632. {$role_demo}
  10633. {$scene_demo}
  10634. {$prop_demo}
  10635. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10636. 5.1片段分割逻辑(优先级从高到低):
  10637. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10638. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10639. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10640. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10641. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10642. - 片段数量格式为: 片段数量:8
  10643. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10644. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10645. 5.3分镜结构:每个分镜包含以下字段:
  10646. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  10647. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10648. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10649. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10650. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10651. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10652. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10653. - 运镜:场景+画面描述+运镜
  10654. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  10655. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  10656. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10657. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10658. 6.《情绪-视听语言映射表》:
  10659. 6.1 场景空间与时间心理学 (Scene & Temporality)
  10660. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10661. -----|---------|------------|----------------
  10662. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  10663. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  10664. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  10665. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  10666. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  10667. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10668. -----|---------|------------|----------------
  10669. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  10670. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  10671. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  10672. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  10673. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  10674. --------|---------|--------------|-------------
  10675. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  10676. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  10677. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  10678. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  10679. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  10680. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  10681. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  10682. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  10683. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  10684. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  10685. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  10686. -----|---------|------------|------------
  10687. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  10688. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  10689. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  10690. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  10691. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  10692. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  10693. --------|---------|--------------|----------
  10694. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  10695. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  10696. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  10697. 6.6 声音设计与潜意识影响 (Soundscape)
  10698. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  10699. -----|---------|------------|------------------
  10700. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  10701. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  10702. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  10703. 理论基石:
  10704. - The Five C's of Cinematography by Joseph V. Mascelli
  10705. - Film Art: An Introduction by David Bordwell
  10706. - Sight, Sound, Motion by Herbert Zettl
  10707. - Notes on the Cinematograph by Robert Bresson
  10708. \n\n
  10709. 7.{$mappedArtStyle_prompt}
  10710. 示例格式:\n
  10711. 第1集:隐形的守护者
  10712. ###故事梗概
  10713. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10714. ###美术风格
  10715. 基础画风风格词:胡金铨武侠
  10716. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10717. ###主体列表
  10718. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10719. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10720. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10721. ###场景列表
  10722. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10723. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10724. ###道具列表
  10725. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  10726. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  10727. ###分段剧本
  10728. 片段数量:8
  10729. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10730. ##片段1
  10731. 时长:12s
  10732. 分镜1
  10733. 出场角色:刀疤脸
  10734. 场景:边境小镇街道
  10735. 出场道具:酒杯-高脚杯
  10736. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10737. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10738. 配音台词:
  10739. 背景音效:
  10740. 分镜2
  10741. 出场角色:刀疤脸
  10742. 场景:悦来酒馆
  10743. 出场道具:酒杯-高脚杯
  10744. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10745. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10746. 配音台词:
  10747. 背景音效:
  10748. 分镜3
  10749. 出场角色:刀疤脸
  10750. 场景:悦来酒馆
  10751. 出场道具:酒杯-高脚杯
  10752. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10753. 运镜:从中景推向令牌特写。
  10754. 配音台词:
  10755. 背景音效:
  10756. 分镜4
  10757. 出场角色:刀疤脸
  10758. 场景:悦来酒馆
  10759. 出场道具:酒杯-高脚杯
  10760. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10761. 运镜:极速推向酒水溅起的瞬间。
  10762. 配音台词:
  10763. 背景音效:
  10764. 分镜5
  10765. 出场角色:刀疤脸
  10766. 场景:悦来酒馆
  10767. 出场道具:酒杯-高脚杯
  10768. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10769. 运镜:固定机位,利用倾斜构图制造压迫感。
  10770. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10771. 背景音效:
  10772. \n\n";
  10773. */
  10774. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  10775. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  10776. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  10777. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  10778. 强制要求:
  10779. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  10780. 普通要求:
  10781. 1.剧集标题必须与文档内容高度相关,剧集序号见文末【本次剧集信息】。
  10782. 2.<主体列表>的详细规则和可选范围见文末【本次生成数据-主体列表】。
  10783. 3.<场景列表>的详细规则和可选范围见文末【本次生成数据-场景列表】。
  10784. 4.<道具列表>的详细规则和可选范围见文末【本次生成数据-道具列表】。
  10785. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10786. 5.1片段分割逻辑(优先级从高到低):
  10787. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10788. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10789. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10790. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10791. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10792. - 片段数量格式为: 片段数量:8
  10793. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10794. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10795. 5.3分镜结构:每个分镜包含以下字段:
  10796. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  10797. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  10798. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10799. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10800. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10801. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10802. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10803. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10804. - 运镜:场景+画面描述+运镜
  10805. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  10806. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  10807. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10808. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10809. 6.《情绪-视听语言映射表》:
  10810. 6.1 场景空间与时间心理学 (Scene & Temporality)
  10811. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10812. -----|---------|------------|----------------
  10813. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  10814. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  10815. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  10816. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  10817. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  10818. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10819. -----|---------|------------|----------------
  10820. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  10821. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  10822. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  10823. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  10824. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  10825. --------|---------|--------------|-------------
  10826. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  10827. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  10828. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  10829. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  10830. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  10831. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  10832. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  10833. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  10834. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  10835. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  10836. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  10837. -----|---------|------------|------------
  10838. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  10839. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  10840. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  10841. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  10842. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  10843. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  10844. --------|---------|--------------|----------
  10845. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  10846. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  10847. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  10848. 6.6 声音设计与潜意识影响 (Soundscape)
  10849. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  10850. -----|---------|------------|------------------
  10851. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  10852. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  10853. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  10854. 理论基石:
  10855. - The Five C's of Cinematography by Joseph V. Mascelli
  10856. - Film Art: An Introduction by David Bordwell
  10857. - Sight, Sound, Motion by Herbert Zettl
  10858. - Notes on the Cinematograph by Robert Bresson
  10859. \n\n
  10860. 7.美术风格要求见文末【本次生成数据-美术风格】。
  10861. 示例格式:\n
  10862. 第1集:隐形的守护者
  10863. ###故事梗概
  10864. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10865. ###美术风格
  10866. 基础画风风格词:胡金铨武侠
  10867. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10868. ###主体列表
  10869. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10870. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10871. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10872. ###场景列表
  10873. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10874. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10875. ###道具列表
  10876. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  10877. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  10878. ###分段剧本
  10879. 片段数量:8
  10880. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10881. ##片段1
  10882. 时长:12s
  10883. 分镜1
  10884. 出场角色:刀疤脸
  10885. 场景:边境小镇街道
  10886. 出场道具:酒杯-高脚杯
  10887. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10888. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10889. 配音台词:
  10890. 背景音效:
  10891. 分镜2
  10892. 出场角色:刀疤脸
  10893. 场景:悦来酒馆
  10894. 出场道具:酒杯-高脚杯
  10895. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10896. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10897. 配音台词:
  10898. 背景音效:
  10899. 分镜3
  10900. 出场角色:刀疤脸
  10901. 场景:悦来酒馆
  10902. 出场道具:酒杯-高脚杯
  10903. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10904. 运镜:从中景推向令牌特写。
  10905. 配音台词:
  10906. 背景音效:
  10907. 分镜4
  10908. 出场角色:刀疤脸
  10909. 场景:悦来酒馆
  10910. 出场道具:酒杯-高脚杯
  10911. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10912. 运镜:极速推向酒水溅起的瞬间。
  10913. 配音台词:
  10914. 背景音效:
  10915. 分镜5
  10916. 出场角色:刀疤脸
  10917. 场景:悦来酒馆
  10918. 出场道具:酒杯-高脚杯
  10919. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10920. 运镜:固定机位,利用倾斜构图制造压迫感。
  10921. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10922. 背景音效:
  10923. \n\n本次生成数据(以上规则的动态数据均在此处,优先级等同对应编号规则):
  10924. 【本次剧集信息】剧集序号是{$episode_number}。
  10925. 【本次生成数据-主体列表】{$role_demo}
  10926. 【本次生成数据-场景列表】{$scene_demo}
  10927. 【本次生成数据-道具列表】{$prop_demo}
  10928. 【本次生成数据-美术风格】{$mappedArtStyle_prompt}
  10929. \n\n";
  10930. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10931. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  10932. // $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  10933. $is_regenerate_version = true;
  10934. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  10935. $prompt = $origin_prompt;
  10936. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  10937. // 获取章节内容
  10938. $full_content = getProp($anime, 'content');
  10939. if ($uploaded_content) {
  10940. $full_content = $uploaded_content;
  10941. }
  10942. // 根据章节内容拆分章节
  10943. $chapters = splitContent($full_content);
  10944. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  10945. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  10946. $messages = [];
  10947. if ($prompt == '确认分镜大纲') {
  10948. // 暂时保留
  10949. $content = $chapter_content;
  10950. if ($is_single) $content = $full_content; // 单剧集使用全文
  10951. if (!$content) {
  10952. Utils::throwError('20003:章节内容无法获取,请确认');
  10953. }
  10954. $question = $is_single
  10955. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  10956. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  10957. // 构建消息
  10958. $messages[] =
  10959. [
  10960. 'role' => 'user',
  10961. 'content' => $question
  10962. ];
  10963. }else if ($prompt == '继续策划下一集') {
  10964. if ($is_single) {
  10965. Utils::throwError('20003:单剧集不支持继续策划下一集');
  10966. }
  10967. $content = $chapter_content;
  10968. if (!$content) {
  10969. Utils::throwError('20003:章节内容无法获取,请确认');
  10970. }
  10971. // 获取上一集最后记录
  10972. $prev_sequence = $episode_number - 1;
  10973. $messages = array_merge(
  10974. [
  10975. [
  10976. 'role' => 'system',
  10977. 'content' => $demo
  10978. ]
  10979. ],
  10980. $this->getEpisodeChatContent($anime_id, $prev_sequence, $content)
  10981. );
  10982. // 构建消息
  10983. $messages[] =
  10984. [
  10985. 'role' => 'user',
  10986. 'content' => "请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)"
  10987. ];
  10988. /*
  10989. // 旧版逻辑
  10990. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  10991. // 构建消息
  10992. $messages[] =
  10993. [
  10994. 'role' => 'user',
  10995. 'content' => $question
  10996. ];
  10997. */
  10998. // dd($messages);
  10999. }else {
  11000. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  11001. if (!$content) {
  11002. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  11003. }
  11004. if (!$content) {
  11005. Utils::throwError('20003:章节内容无法获取,请确认');
  11006. }
  11007. $messages = array_merge(
  11008. [
  11009. [
  11010. 'role' => 'system',
  11011. 'content' => $demo
  11012. ]
  11013. ],
  11014. $this->getEpisodeChatMessages($anime_id, $episode_number)
  11015. );
  11016. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  11017. $question = "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  11018. if ($origin_prompt) {
  11019. $question .= "本次修改要求如下:\n{$origin_prompt}";
  11020. }
  11021. // 将本集原文加入消息,供模型逐字摘录原文台词(修复重新生成时配音台词全部为"无"的问题)
  11022. $messages[] = [
  11023. 'role' => 'user',
  11024. 'content' => "本集剧情内容:\n\n{$content}\n"
  11025. ];
  11026. $messages[] =
  11027. [
  11028. 'role' => 'user',
  11029. 'content' => $question
  11030. ];
  11031. }
  11032. // 处理文本模型
  11033. $model = getProp($data, 'model');
  11034. if (!$model) {
  11035. // 用户没有输入,从anime表获取
  11036. $model = getProp($anime, 'model');
  11037. if (!$model) {
  11038. // anime表也没有,使用默认值
  11039. $model = 'deepseek-v4-pro';
  11040. }
  11041. }
  11042. // 验证模型是否在可用模型表中
  11043. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  11044. $model = 'deepseek-v4-pro';
  11045. }
  11046. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  11047. $thinkingMode = getProp($data, 'thinking', 'enabled'); // 默认非思考模式
  11048. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  11049. if ($model === 'deepseek-chat') {
  11050. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  11051. $model = 'deepseek-v4-flash';
  11052. $thinkingMode = 'disabled';
  11053. } elseif ($model === 'deepseek-reasoner') {
  11054. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  11055. $model = 'deepseek-v4-flash';
  11056. $thinkingMode = 'enabled';
  11057. }
  11058. $post_data = [
  11059. 'model' => $model,
  11060. 'messages' => $messages,
  11061. // 'max_tokens' => 8192,
  11062. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  11063. 'frequency_penalty' => 0,
  11064. 'presence_penalty' => 0,
  11065. 'response_format' => ['type' => 'text'],
  11066. 'thinking' => ['type' => $thinkingMode],
  11067. 'stream' => true // 启用流式输出
  11068. ];
  11069. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  11070. // 根据模型类型选择调用方法
  11071. $fullContent = '';
  11072. $fullReasoningContent = '';
  11073. $usage = [];
  11074. try {
  11075. $streamGenerator = $this->dispatchStreamByModel($post_data);
  11076. // 验证返回值类型
  11077. if (!is_iterable($streamGenerator)) {
  11078. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  11079. dLog('deepseek')->error('chat流式生成器无效', [
  11080. 'generator_type' => $errorType,
  11081. 'model' => $model,
  11082. 'anime_id' => $anime_id,
  11083. 'episode_number' => $episode_number
  11084. ]);
  11085. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  11086. 'type' => $errorType,
  11087. 'model' => $model
  11088. ]);
  11089. yield [
  11090. 'type' => 'error',
  11091. 'episode' => [],
  11092. 'answer' => '',
  11093. 'reasoning' => '',
  11094. 'usage' => [],
  11095. 'error' => '接口返回数据异常,请重新请求'
  11096. ];
  11097. return;
  11098. }
  11099. // 处理流式输出
  11100. foreach ($streamGenerator as $chunk) {
  11101. if (isset($chunk['type'])) {
  11102. if ($chunk['type'] === 'done') {
  11103. // 最终结果
  11104. $fullContent = $chunk['full_content'];
  11105. $fullReasoningContent = $chunk['full_reasoning'];
  11106. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  11107. } else {
  11108. // 逐块yield数据
  11109. yield $chunk;
  11110. }
  11111. }
  11112. }
  11113. } catch (\Exception $e) {
  11114. // 解析上游错误详情(如 content_filter),便于日志定位与前端提示
  11115. $upstream_error = $this->resolveGptUpstreamError($e);
  11116. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  11117. 'model' => $model,
  11118. 'anime_id' => $anime_id,
  11119. 'episode_number' => $episode_number,
  11120. 'upstream_status' => $upstream_error['status'],
  11121. 'upstream_code' => $upstream_error['code'],
  11122. 'upstream_body' => $upstream_error['body'],
  11123. 'trace' => $e->getTraceAsString()
  11124. ]);
  11125. logDB('deepseek', 'error', 'chat流式处理失败', [
  11126. 'error' => $e->getMessage(),
  11127. 'model' => $model,
  11128. 'upstream_status' => $upstream_error['status'],
  11129. 'upstream_code' => $upstream_error['code'],
  11130. 'upstream_body' => $upstream_error['body']
  11131. ]);
  11132. yield [
  11133. 'type' => 'error',
  11134. 'episode' => [],
  11135. 'answer' => '',
  11136. 'reasoning' => '',
  11137. 'usage' => [],
  11138. 'error' => $this->buildChatErrorForUser($e, $upstream_error)
  11139. ];
  11140. return;
  11141. }
  11142. // 兼容模型偶发将整段正文包裹成 JSON 字符串返回
  11143. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  11144. dLog('deepseek')->info('完整内容: '.$fullContent);
  11145. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  11146. // 处理完整内容并返回最终结果
  11147. $episode_arr = handleEpisodeContentForAce($fullContent);
  11148. dLog('deepseek')->info('解析内容: ', $episode_arr);
  11149. logDB('deepseek', 'info', '解析内容', $episode_arr);
  11150. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  11151. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  11152. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  11153. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  11154. // }
  11155. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  11156. $max_retries = 3;
  11157. $retry_count = 0;
  11158. $validation_failed = false;
  11159. $validation_error_msg = '';
  11160. // 验证生成的内容
  11161. if ($anime_script_id) {
  11162. // 检查是否有acts数据
  11163. if (empty($episode_arr['acts'])) {
  11164. $validation_failed = true;
  11165. $validation_error_msg = '未生成分镜剧本相关的内容';
  11166. } else {
  11167. // 校验主体列表:不能为空主体(旁白不算)
  11168. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11169. // 过滤掉"旁白"角色
  11170. $generated_roles = array_filter($generated_roles, function($role) {
  11171. return $role !== '旁白';
  11172. });
  11173. if (empty($generated_roles)) {
  11174. $validation_failed = true;
  11175. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11176. }
  11177. // 仅当存在强制主体设定时校验主体列表
  11178. if (!$validation_failed && !empty($extra_roles)) {
  11179. $expected_roles = array_keys($extra_roles);
  11180. // 找出生成的主体中不在预期列表中的主体
  11181. $invalid_roles = array_diff($generated_roles, $expected_roles);
  11182. if (!empty($invalid_roles)) {
  11183. $validation_failed = true;
  11184. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  11185. }
  11186. }
  11187. // 仅当存在强制场景设定时校验场景列表
  11188. if (!$validation_failed && !empty($extra_scenes)) {
  11189. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  11190. $expected_scenes = array_keys($extra_scenes);
  11191. // 找出生成的场景中不在预期列表中的场景
  11192. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  11193. if (!empty($invalid_scenes)) {
  11194. $validation_failed = true;
  11195. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  11196. }
  11197. }
  11198. // 仅当存在强制道具设定时校验道具列表
  11199. if (!$validation_failed && !empty($extra_props)) {
  11200. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  11201. $expected_props = array_keys($extra_props);
  11202. // 找出生成的道具中不在预期列表中的道具
  11203. $invalid_props = array_diff($generated_props, $expected_props);
  11204. if (!empty($invalid_props)) {
  11205. $validation_failed = true;
  11206. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  11207. }
  11208. }
  11209. }
  11210. } else {
  11211. // 如果没有anime_script_id,只检查是否有acts数据
  11212. if (empty($episode_arr['acts'])) {
  11213. $validation_failed = true;
  11214. $validation_error_msg = '未生成分镜剧本相关的内容';
  11215. } else {
  11216. // 校验主体列表:不能为空主体(旁白不算)
  11217. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11218. // 过滤掉"旁白"角色
  11219. $generated_roles = array_filter($generated_roles, function($role) {
  11220. return $role !== '旁白';
  11221. });
  11222. if (empty($generated_roles)) {
  11223. $validation_failed = true;
  11224. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11225. }
  11226. }
  11227. }
  11228. // 重试逻辑
  11229. while ($validation_failed && $retry_count < $max_retries) {
  11230. $retry_count++;
  11231. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  11232. 'reason' => $validation_error_msg,
  11233. 'anime_id' => $anime_id,
  11234. 'episode_number' => $episode_number
  11235. ]);
  11236. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  11237. 'reason' => $validation_error_msg,
  11238. 'anime_id' => $anime_id
  11239. ]);
  11240. // 发送流式重试提示
  11241. yield [
  11242. 'type' => 'retry',
  11243. 'retry_count' => $retry_count,
  11244. 'reason' => $validation_error_msg
  11245. ];
  11246. // 构建重试提示词
  11247. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  11248. if ($anime_script_id) {
  11249. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  11250. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  11251. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  11252. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  11253. } else {
  11254. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  11255. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  11256. }
  11257. // 添加重试消息到messages
  11258. $messages[] = [
  11259. 'role' => 'assistant',
  11260. 'content' => $fullContent
  11261. ];
  11262. $messages[] = [
  11263. 'role' => 'user',
  11264. 'content' => $retry_prompt
  11265. ];
  11266. // 更新post_data的messages
  11267. $post_data['messages'] = $messages;
  11268. // 重新调用API
  11269. try {
  11270. $streamGenerator = $this->dispatchStreamByModel($post_data);
  11271. // 处理流式输出
  11272. $fullContent = '';
  11273. $fullReasoningContent = '';
  11274. foreach ($streamGenerator as $chunk) {
  11275. if (isset($chunk['type'])) {
  11276. if ($chunk['type'] === 'done') {
  11277. $fullContent = $chunk['full_content'];
  11278. $fullReasoningContent = $chunk['full_reasoning'];
  11279. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  11280. } else {
  11281. yield $chunk;
  11282. }
  11283. }
  11284. }
  11285. // 重新解析内容
  11286. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  11287. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  11288. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  11289. $episode_arr = handleEpisodeContentForAce($fullContent);
  11290. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  11291. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  11292. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  11293. // }
  11294. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  11295. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  11296. // 重新验证
  11297. $validation_failed = false;
  11298. $validation_error_msg = '';
  11299. if ($anime_script_id) {
  11300. if (empty($episode_arr['acts'])) {
  11301. $validation_failed = true;
  11302. $validation_error_msg = '未生成分镜剧本相关的内容';
  11303. } else {
  11304. // 校验主体列表:不能为空主体(旁白不算)
  11305. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11306. // 过滤掉"旁白"角色
  11307. $generated_roles = array_filter($generated_roles, function($role) {
  11308. return $role !== '旁白';
  11309. });
  11310. if (empty($generated_roles)) {
  11311. $validation_failed = true;
  11312. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11313. }
  11314. // 仅当存在强制主体设定时校验主体列表
  11315. if (!$validation_failed && !empty($extra_roles)) {
  11316. $expected_roles = array_keys($extra_roles);
  11317. $invalid_roles = array_diff($generated_roles, $expected_roles);
  11318. if (!empty($invalid_roles)) {
  11319. $validation_failed = true;
  11320. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  11321. }
  11322. }
  11323. // 仅当存在强制场景设定时校验场景列表
  11324. if (!$validation_failed && !empty($extra_scenes)) {
  11325. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  11326. $expected_scenes = array_keys($extra_scenes);
  11327. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  11328. if (!empty($invalid_scenes)) {
  11329. $validation_failed = true;
  11330. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  11331. }
  11332. }
  11333. // 仅当存在强制道具设定时校验道具列表
  11334. if (!$validation_failed && !empty($extra_props)) {
  11335. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  11336. $expected_props = array_keys($extra_props);
  11337. $invalid_props = array_diff($generated_props, $expected_props);
  11338. if (!empty($invalid_props)) {
  11339. $validation_failed = true;
  11340. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  11341. }
  11342. }
  11343. }
  11344. } else {
  11345. if (empty($episode_arr['acts'])) {
  11346. $validation_failed = true;
  11347. $validation_error_msg = '未生成分镜剧本相关的内容';
  11348. } else {
  11349. // 校验主体列表:不能为空主体(旁白不算)
  11350. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11351. // 过滤掉"旁白"角色
  11352. $generated_roles = array_filter($generated_roles, function($role) {
  11353. return $role !== '旁白';
  11354. });
  11355. if (empty($generated_roles)) {
  11356. $validation_failed = true;
  11357. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11358. }
  11359. }
  11360. }
  11361. } catch (\Exception $e) {
  11362. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  11363. 'trace' => $e->getTraceAsString()
  11364. ]);
  11365. break;
  11366. }
  11367. }
  11368. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  11369. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  11370. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  11371. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  11372. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  11373. if ($validation_failed && $retry_count >= $max_retries) {
  11374. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  11375. 'retry_count' => $retry_count,
  11376. 'last_error' => $validation_error_msg
  11377. ]);
  11378. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  11379. 'error' => $validation_error_msg,
  11380. 'anime_id' => $anime_id
  11381. ]);
  11382. $validation_failed = false;
  11383. $validation_error_msg = '';
  11384. }
  11385. // 如果重试后仍然失败
  11386. if ($validation_failed) {
  11387. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  11388. 'retry_count' => $retry_count,
  11389. 'last_error' => $validation_error_msg
  11390. ]);
  11391. try {
  11392. $now = date('Y-m-d H:i:s');
  11393. $records = [
  11394. [
  11395. 'uid' => $uid,
  11396. 'anime_id' => $anime_id,
  11397. 'sequence' => $episode_number,
  11398. 'role' => 'user',
  11399. 'content' => $prompt,
  11400. 'created_at' => $now,
  11401. 'updated_at' => $now
  11402. ],
  11403. [
  11404. 'uid' => $uid,
  11405. 'anime_id' => $anime_id,
  11406. 'sequence' => $episode_number,
  11407. 'role' => 'assistant',
  11408. 'content' => $fullContent,
  11409. 'created_at' => $now,
  11410. 'updated_at' => $now
  11411. ]
  11412. ];
  11413. DB::table('mp_anime_records')->insert($records);
  11414. } catch (\Exception $e) {
  11415. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  11416. }
  11417. yield [
  11418. 'type' => 'done',
  11419. 'episode' => [],
  11420. 'answer' => $fullContent,
  11421. 'reasoning' => $fullReasoningContent,
  11422. 'usage' => $usage,
  11423. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  11424. ];
  11425. return;
  11426. }
  11427. // 验证成功,记录日志
  11428. if ($retry_count > 0) {
  11429. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  11430. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  11431. }
  11432. // 老逻辑
  11433. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  11434. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  11435. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  11436. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  11437. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  11438. $existing_props = is_array($existing_props) ? $existing_props : [];
  11439. $now = date('Y-m-d H:i:s');
  11440. try {
  11441. DB::beginTransaction();
  11442. $saveResult = $this->saveEpisodeVersionData(
  11443. $anime_id,
  11444. $episode_number,
  11445. $episode_arr,
  11446. $existing_roles,
  11447. $existing_scenes,
  11448. $existing_props,
  11449. $current_episode,
  11450. $base_episode,
  11451. $is_regenerate_version,
  11452. $content,
  11453. $now,
  11454. $ref_products
  11455. );
  11456. $episode = $saveResult['episode'];
  11457. $episode_id = $saveResult['episode_id'];
  11458. $merged_roles = $saveResult['merged_roles'];
  11459. $merged_scenes = $saveResult['merged_scenes'];
  11460. $merged_props = $saveResult['merged_props'];
  11461. $record_content = $origin_prompt;
  11462. if ($uploaded_content !== '') {
  11463. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  11464. }
  11465. $records = [
  11466. [
  11467. 'uid' => $uid,
  11468. 'anime_id' => $anime_id,
  11469. 'role' => 'user',
  11470. 'content' => $record_content,
  11471. 'sequence' => $episode_number,
  11472. 'episode_id' => $episode_id,
  11473. 'created_at' => $now,
  11474. 'updated_at' => $now
  11475. ],
  11476. [
  11477. 'uid' => $uid,
  11478. 'anime_id' => $anime_id,
  11479. 'role' => 'assistant',
  11480. 'content' => $fullContent,
  11481. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  11482. 'sequence' => $episode_number,
  11483. 'episode_id' => $episode_id,
  11484. 'created_at' => $now,
  11485. 'updated_at' => $now
  11486. ]
  11487. ];
  11488. $boolen4 = DB::table('mp_anime_records')->insert($records);
  11489. if (!$boolen4) {
  11490. Utils::throwError('20003:对话记录保存失败');
  11491. }
  11492. // 保存模型到anime表
  11493. $update_anime_data = [
  11494. 'model' => $model,
  11495. 'updated_at' => $now
  11496. ];
  11497. if ($uploaded_content) {
  11498. $update_anime_data['content'] = $uploaded_content;
  11499. }
  11500. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  11501. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  11502. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  11503. 'anime_id' => $anime_id,
  11504. 'episode_number' => $episode_number,
  11505. 'model' => $model,
  11506. 'source' => 'chatForAce',
  11507. ]);
  11508. }catch (\Exception $e) {
  11509. DB::rollBack();
  11510. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  11511. yield [
  11512. 'type' => 'done',
  11513. 'answer' => $fullContent,
  11514. 'reasoning' => $fullReasoningContent,
  11515. 'usage' => $usage,
  11516. 'error' => $e->getMessage(),
  11517. ];
  11518. return;
  11519. }
  11520. DB::commit();
  11521. if ($is_global_generate_pics) {
  11522. // // 批量生成全局角色图片
  11523. // $this->batchSetGlobalRoleImg([
  11524. // 'anime_id' => $anime_id,
  11525. // ], true);
  11526. // // 批量生成全局场景图片
  11527. // $this->batchSetGlobalSceneImg([
  11528. // 'anime_id' => $anime_id,
  11529. // ], true);
  11530. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  11531. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  11532. }
  11533. $episode['episode_id'] = $episode_id;
  11534. $episode['roles'] = $merged_roles;
  11535. $episode['scenes'] = $merged_scenes;
  11536. $episode['props'] = $merged_props;
  11537. $episode['end_episode_sequence'] = $end_episode_sequence;
  11538. // 获取mp_animes表中的视频参数
  11539. $episode['video_params'] = [
  11540. 'video_model' => getProp($anime, 'video_model'),
  11541. 'video_resolution' => getProp($anime, 'video_resolution'),
  11542. 'ratio' => getProp($anime, 'video_ratio'),
  11543. ];
  11544. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  11545. yield [
  11546. 'type' => 'done',
  11547. 'episode' => $episode,
  11548. 'answer' => $fullContent,
  11549. 'reasoning' => $fullReasoningContent,
  11550. 'usage' => $usage
  11551. ];
  11552. }
  11553. /**
  11554. * chatForAce的非流式版本 - 用于定时任务
  11555. * 只获取最终 type=done 的数据,并验证必要字段
  11556. *
  11557. * @param array $data 请求数据
  11558. * @return array 生成结果
  11559. */
  11560. public function chatForAceNonStream($data) {
  11561. $finalResult = null;
  11562. // 调用流式方法,只保存 type=done 的数据
  11563. foreach ($this->chatForAce($data) as $chunk) {
  11564. // 只关注最终结果
  11565. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  11566. $finalResult = $chunk;
  11567. break; // 找到 done 就退出循环
  11568. }
  11569. // 出错时直接带上原因返回(如上游内容安全策略拦截),避免被吞成"未获取到最终结果"
  11570. if (isset($chunk['type']) && $chunk['type'] === 'error' && !empty($chunk['error'])) {
  11571. return ['error' => $chunk['error']];
  11572. }
  11573. }
  11574. // 验证最终结果
  11575. if (!$finalResult) {
  11576. return ['error' => '生成失败:未获取到最终结果'];
  11577. }
  11578. // 检查是否有错误
  11579. if (isset($finalResult['error']) && $finalResult['error']) {
  11580. return $finalResult;
  11581. }
  11582. // 验证必要字段
  11583. $episode = $finalResult['episode'] ?? [];
  11584. // 验证 roles(旁白不算主体,过滤后不能为空)
  11585. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  11586. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  11587. }
  11588. $nonNarratorRoles = array_filter(array_column($episode['roles'], 'role'), function($role) {
  11589. return $role !== '旁白';
  11590. });
  11591. if (empty($nonNarratorRoles)) {
  11592. return ['error' => '生成失败:主体列表(roles)为空或格式错误(旁白不算)'];
  11593. }
  11594. // 验证 scenes
  11595. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  11596. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  11597. }
  11598. // 验证 props(道具可以为空,但必须存在且为数组)
  11599. if (!isset($episode['props']) || !is_array($episode['props'])) {
  11600. $episode['props'] = [];
  11601. }
  11602. // 验证 acts(分镜剧本)
  11603. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  11604. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  11605. }
  11606. // 更新验证后的 episode 数据
  11607. $finalResult['episode'] = $episode;
  11608. // 记录验证成功日志
  11609. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  11610. 'roles_count' => count($episode['roles']),
  11611. 'scenes_count' => count($episode['scenes']),
  11612. 'props_count' => count($episode['props']),
  11613. 'acts_count' => count($episode['acts'])
  11614. ]);
  11615. return $finalResult;
  11616. }
  11617. /**
  11618. * 批量生成多个分集
  11619. *
  11620. * @param array $data 请求数据
  11621. * @return array 任务信息
  11622. */
  11623. public function batchGenerateEpisodes($data) {
  11624. $uid = Site::getUid();
  11625. $cpid = Site::getCpid();
  11626. $anime_id = getProp($data, 'anime_id');
  11627. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  11628. $start_episode_number = getProp($data, 'start_episode_number');
  11629. $end_episode_number = getProp($data, 'end_episode_number');
  11630. if (!$anime_id) {
  11631. Utils::throwError('20003:anime_id参数缺失');
  11632. }
  11633. if ($generate_episode_number < 1) {
  11634. Utils::throwError('20003:生成集数必须大于0');
  11635. }
  11636. // 获取动漫信息
  11637. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  11638. if (!$anime) {
  11639. Utils::throwError('20003:该剧集不存在');
  11640. }
  11641. // 检查是否是全能模式
  11642. if ((int)getProp($anime, 'ace_mode') !== 1) {
  11643. Utils::throwError('20003:只有全能模式才支持批量生成');
  11644. }
  11645. // 检查是否是多剧集模式
  11646. if ((int)getProp($anime, 'is_multi') !== 1) {
  11647. Utils::throwError('20003:单剧集不支持批量生成');
  11648. }
  11649. // 指定起始/结束剧集序号时的校验
  11650. $hasSpecifiedRange = ($start_episode_number !== null && $start_episode_number !== '')
  11651. || ($end_episode_number !== null && $end_episode_number !== '');
  11652. if ($hasSpecifiedRange) {
  11653. if ($start_episode_number === null || $start_episode_number === ''
  11654. || $end_episode_number === null || $end_episode_number === '') {
  11655. Utils::throwError('20003:起始剧集序号和结束剧集序号必须同时提供');
  11656. }
  11657. $start_episode_number = (int)$start_episode_number;
  11658. $end_episode_number = (int)$end_episode_number;
  11659. if ($start_episode_number < 1 || $end_episode_number < $start_episode_number) {
  11660. Utils::throwError('20003:剧集序号范围错误,结束剧集序号不能小于起始剧集序号');
  11661. }
  11662. // 起始序号必须是已有剧集(is_default=1)的下一个序号,不允许跨序号创建
  11663. $currentMaxEpisode = DB::table('mp_anime_episodes')
  11664. ->where('anime_id', $anime_id)
  11665. ->where('is_default', 1)
  11666. ->max('episode_number');
  11667. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  11668. $nextEpisodeNumber = $currentMaxEpisode + 1;
  11669. if ($start_episode_number !== $nextEpisodeNumber) {
  11670. Utils::throwError('20003:起始剧集序号必须是已有剧集的下一个序号(第' . $nextEpisodeNumber . '集),不允许跨序号创建');
  11671. }
  11672. $startEpisodeNumber = $start_episode_number;
  11673. $endEpisodeNumber = $end_episode_number;
  11674. } else {
  11675. // 未指定范围时,以 generate_episode_number 判断要生成的集数,从当前已生成的最大集数的下一集开始
  11676. $currentMaxEpisode = DB::table('mp_anime_episodes')
  11677. ->where('anime_id', $anime_id)
  11678. ->where('is_default', 1)
  11679. ->max('episode_number');
  11680. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  11681. // 确定起始集数
  11682. $startEpisodeNumber = $currentMaxEpisode + 1;
  11683. // 计算结束集数
  11684. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  11685. }
  11686. // 本次实际生成的集数
  11687. $totalEpisodeCount = $endEpisodeNumber - $startEpisodeNumber + 1;
  11688. // 检查是否超过总集数限制
  11689. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  11690. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  11691. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  11692. }
  11693. // 创建任务前验重:批量任务表与剧集表中是否已存在范围内的剧集序号
  11694. $duplicatedBatchEpisodes = DB::table('mp_batch_episode_generation_details')
  11695. ->where('anime_id', $anime_id)
  11696. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11697. ->pluck('episode_number')
  11698. ->unique()
  11699. ->sort()
  11700. ->values()
  11701. ->toArray();
  11702. $duplicatedAnimeEpisodes = DB::table('mp_anime_episodes')
  11703. ->where('anime_id', $anime_id)
  11704. ->where('is_default', 1)
  11705. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11706. ->pluck('episode_number')
  11707. ->unique()
  11708. ->sort()
  11709. ->values()
  11710. ->toArray();
  11711. if (!empty($duplicatedBatchEpisodes) || !empty($duplicatedAnimeEpisodes)) {
  11712. $duplicateMessages = [];
  11713. if (!empty($duplicatedBatchEpisodes)) {
  11714. $duplicateMessages[] = '批量生成任务中已存在第' . implode('、', $duplicatedBatchEpisodes) . '集';
  11715. }
  11716. if (!empty($duplicatedAnimeEpisodes)) {
  11717. $duplicateMessages[] = '剧集中已存在第' . implode('、', $duplicatedAnimeEpisodes) . '集';
  11718. }
  11719. Utils::throwError('20003:' . implode(';', $duplicateMessages) . ',请勿重复创建');
  11720. }
  11721. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  11722. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  11723. ->where('anime_id', $anime_id)
  11724. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11725. ->whereIn('status', ['pending', 'processing', 'completed'])
  11726. ->count();
  11727. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  11728. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  11729. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  11730. if ($needEpisodeCount > 0) {
  11731. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints() * $needEpisodeCount, $uid);
  11732. }
  11733. $now = date('Y-m-d H:i:s');
  11734. $createdTasks = [];
  11735. $skippedTasks = [];
  11736. // 为每一集创建详情记录
  11737. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  11738. // 检查是否已有该集的任务记录
  11739. $existingTask = DB::table('mp_batch_episode_generation_details')
  11740. ->where('anime_id', $anime_id)
  11741. ->where('episode_number', $episodeNumber)
  11742. ->first();
  11743. if ($existingTask) {
  11744. // 如果已存在且未完成,跳过
  11745. if (in_array($existingTask->status, ['pending', 'processing'])) {
  11746. $skippedTasks[] = $episodeNumber;
  11747. continue;
  11748. }
  11749. // 如果是失败状态,可以重新创建(删除旧记录)
  11750. if ($existingTask->status === 'failed') {
  11751. DB::table('mp_batch_episode_generation_details')
  11752. ->where('id', $existingTask->id)
  11753. ->delete();
  11754. }
  11755. // 如果是已完成状态,也跳过
  11756. if ($existingTask->status === 'completed') {
  11757. $skippedTasks[] = $episodeNumber;
  11758. continue;
  11759. }
  11760. }
  11761. // 准备任务数据
  11762. $taskData = [
  11763. 'anime_id' => $anime_id,
  11764. 'uid' => $uid,
  11765. 'cpid' => $cpid,
  11766. 'episode_number' => $episodeNumber,
  11767. 'status' => 'pending',
  11768. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  11769. 'retry_count' => 0,
  11770. 'created_at' => $now,
  11771. 'updated_at' => $now
  11772. ];
  11773. // 创建任务记录
  11774. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  11775. if ($taskId) {
  11776. $createdTasks[] = $episodeNumber;
  11777. }
  11778. }
  11779. if (empty($createdTasks)) {
  11780. if (!empty($skippedTasks)) {
  11781. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  11782. } else {
  11783. Utils::throwError('20003:创建批量生成任务失败');
  11784. }
  11785. }
  11786. // 创建/复用任务中心记录(按入参+type验重,避免重复任务)
  11787. $taskCenterId = $this->createBatchGenerateEpisodesTaskCenter(
  11788. $uid,
  11789. $cpid,
  11790. $anime_id,
  11791. $generate_episode_number,
  11792. $startEpisodeNumber,
  11793. $endEpisodeNumber
  11794. );
  11795. return [
  11796. 'anime_id' => $anime_id,
  11797. 'start_episode' => $startEpisodeNumber,
  11798. 'end_episode' => $endEpisodeNumber,
  11799. 'total_episodes' => $totalEpisodeCount,
  11800. 'created_episodes' => $createdTasks,
  11801. 'skipped_episodes' => $skippedTasks,
  11802. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$totalEpisodeCount}集。" .
  11803. "已创建: " . implode(',', $createdTasks) .
  11804. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : ""),
  11805. 'task_center_id' => $taskCenterId
  11806. ];
  11807. }
  11808. /**
  11809. * 根据入参创建或复用批量生成分集的任务中心记录
  11810. *
  11811. * 以入参(anime_id、generate_episode_number)计算 md5 存入 params_md5 字段用于验重:
  11812. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  11813. * 避免生成重复任务;唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复。
  11814. *
  11815. * @param int|string $uid
  11816. * @param int|string $cpid
  11817. * @param int|string $anime_id
  11818. * @param int $generate_episode_number
  11819. * @param int $startEpisodeNumber
  11820. * @param int $endEpisodeNumber
  11821. * @return int 任务中心ID
  11822. */
  11823. private function createBatchGenerateEpisodesTaskCenter($uid, $cpid, $anime_id, $generate_episode_number, $startEpisodeNumber, $endEpisodeNumber) {
  11824. $params = [
  11825. 'anime_id' => (int)$anime_id,
  11826. 'generate_episode_number' => (int)$generate_episode_number,
  11827. 'start_episode' => (int)$startEpisodeNumber,
  11828. 'end_episode' => (int)$endEpisodeNumber,
  11829. ];
  11830. // 验重键:入参 + 生成范围(anime_id + generate_episode_number + start/end)+ task_type
  11831. $paramsMd5 = md5(json_encode([
  11832. 'anime_id' => (int)$anime_id,
  11833. 'generate_episode_number' => (int)$generate_episode_number,
  11834. 'start_episode' => (int)$startEpisodeNumber,
  11835. 'end_episode' => (int)$endEpisodeNumber,
  11836. ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  11837. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  11838. $existing = DB::table('mp_task_center')
  11839. ->where('uid', (int)$uid)
  11840. ->where('cpid', (int)$cpid)
  11841. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11842. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  11843. ->where('params_md5', $paramsMd5)
  11844. ->orderBy('id', 'desc')
  11845. ->first();
  11846. if ($existing) {
  11847. dLog('deepseek')->info('复用批量生成分集任务中心记录,避免重复任务', [
  11848. 'anime_id' => $anime_id,
  11849. 'task_center_id' => $existing->id,
  11850. 'params_md5' => $paramsMd5,
  11851. ]);
  11852. return (int)$existing->id;
  11853. }
  11854. $now = date('Y-m-d H:i:s');
  11855. DB::table('mp_task_center')->insertOrIgnore([
  11856. 'uid' => (int)$uid,
  11857. 'cpid' => (int)$cpid,
  11858. 'task_type' => MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES,
  11859. 'title' => '批量生成分集',
  11860. 'ref_task_id' => 0,
  11861. 'status' => MpTaskCenter::STATUS_PROCESSING,
  11862. 'result' => null,
  11863. 'error_message' => null,
  11864. 'prompt' => null,
  11865. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  11866. 'params_md5' => $paramsMd5,
  11867. 'created_at' => $now,
  11868. 'updated_at' => $now,
  11869. ]);
  11870. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  11871. $taskId = (int)DB::table('mp_task_center')
  11872. ->where('uid', (int)$uid)
  11873. ->where('cpid', (int)$cpid)
  11874. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11875. ->where('params_md5', $paramsMd5)
  11876. ->orderBy('id', 'desc')
  11877. ->value('id');
  11878. dLog('deepseek')->info('创建批量生成分集任务中心记录', [
  11879. 'anime_id' => $anime_id,
  11880. 'task_center_id' => $taskId,
  11881. 'params_md5' => $paramsMd5,
  11882. ]);
  11883. return $taskId;
  11884. }
  11885. /**
  11886. * 批量生成分集全部结束后,更新任务中心记录的状态和结果
  11887. *
  11888. * 由批量生成 worker 子进程在退出前调用。分集详情任务的状态会在多处更新
  11889. * (completed/failed/pending/processing),这里只在所有详情任务均已结束时
  11890. * 统一汇总更新,避免在每个更新点重复处理。
  11891. *
  11892. * @param int|string $animeId
  11893. * @return int 更新的任务中心记录数
  11894. */
  11895. public function finishBatchGenerateEpisodesTaskCenters($animeId) {
  11896. $animeId = (int)$animeId;
  11897. $updated = 0;
  11898. // 该 anime 是否还有未结束的详情任务
  11899. $hasUnfinished = DB::table('mp_batch_episode_generation_details')
  11900. ->where('anime_id', $animeId)
  11901. ->whereIn('status', ['pending', 'processing'])
  11902. ->exists();
  11903. // 扫描该 anime 相关的未完成任务中心记录
  11904. $tasks = DB::table('mp_task_center')
  11905. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11906. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  11907. ->orderBy('id', 'desc')
  11908. ->limit(500)
  11909. ->get();
  11910. if ($hasUnfinished && !$tasks) {
  11911. return 0;
  11912. }
  11913. foreach ($tasks as $task) {
  11914. try {
  11915. $taskParams = json_decode((string)$task->params, true);
  11916. if (!is_array($taskParams) || (int)($taskParams['anime_id'] ?? 0) !== $animeId) {
  11917. continue;
  11918. }
  11919. $startEpisode = (int)($taskParams['start_episode'] ?? 0);
  11920. $endEpisode = (int)($taskParams['end_episode'] ?? 0);
  11921. if ($startEpisode < 1 || $endEpisode < $startEpisode) {
  11922. continue;
  11923. }
  11924. $details = DB::table('mp_batch_episode_generation_details')
  11925. ->where('anime_id', $animeId)
  11926. ->whereBetween('episode_number', [$startEpisode, $endEpisode])
  11927. ->get();
  11928. // 该批次范围内存在缺失记录,等待下一次检查
  11929. if ($details->isEmpty() || $details->count() < ($endEpisode - $startEpisode + 1)) {
  11930. continue;
  11931. }
  11932. $completedEpisodes = [];
  11933. $failedEpisodes = [];
  11934. $allFinished = true;
  11935. foreach ($details as $detail) {
  11936. if ($detail->status === 'completed') {
  11937. $completedEpisodes[] = $detail->episode_number;
  11938. } elseif ($detail->status === 'failed') {
  11939. $failedEpisodes[] = [
  11940. 'episode_number' => $detail->episode_number,
  11941. 'error_message' => $detail->error_message ?? '',
  11942. ];
  11943. } else {
  11944. // pending/processing(防御处理,正常不会走到)
  11945. $allFinished = false;
  11946. break;
  11947. }
  11948. }
  11949. if (!$allFinished) {
  11950. continue;
  11951. }
  11952. $result = json_encode([
  11953. 'anime_id' => $animeId,
  11954. 'start_episode' => $startEpisode,
  11955. 'end_episode' => $endEpisode,
  11956. 'total_episodes' => count($details),
  11957. 'completed_count' => count($completedEpisodes),
  11958. 'failed_count' => count($failedEpisodes),
  11959. 'completed_episodes' => $completedEpisodes,
  11960. 'failed_episodes' => $failedEpisodes,
  11961. ], JSON_UNESCAPED_UNICODE);
  11962. DB::table('mp_task_center')
  11963. ->where('id', $task->id)
  11964. ->update([
  11965. 'status' => !empty($failedEpisodes) ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  11966. 'result' => $result,
  11967. 'error_message' => !empty($failedEpisodes) ? ('有 ' . count($failedEpisodes) . ' 集生成失败') : null,
  11968. 'updated_at' => date('Y-m-d H:i:s'),
  11969. ]);
  11970. $updated++;
  11971. dLog('command')->info('批量生成分集任务已完成,更新任务中心', [
  11972. 'task_center_id' => $task->id,
  11973. 'anime_id' => $animeId,
  11974. 'start_episode' => $startEpisode,
  11975. 'end_episode' => $endEpisode,
  11976. ]);
  11977. } catch (\Exception $e) {
  11978. dLog('command')->error('更新批量生成分集任务中心异常', [
  11979. 'task_center_id' => $task->id,
  11980. 'anime_id' => $animeId,
  11981. 'error' => $e->getMessage(),
  11982. ]);
  11983. }
  11984. }
  11985. return $updated;
  11986. }
  11987. /**
  11988. * 获取批量生成任务状态
  11989. *
  11990. * @param array $data 请求数据
  11991. * @return array 任务状态信息
  11992. */
  11993. public function getBatchGenerationTaskStatus($data) {
  11994. $anime_id = getProp($data, 'anime_id');
  11995. if (!$anime_id) {
  11996. Utils::throwError('20003:anime_id参数缺失');
  11997. }
  11998. // 获取该anime的所有任务
  11999. $tasks = DB::table('mp_batch_episode_generation_details')
  12000. ->where('anime_id', $anime_id)
  12001. ->orderBy('episode_number')
  12002. ->get()
  12003. ->map(function($item) {
  12004. return [
  12005. 'id' => $item->id,
  12006. 'episode_number' => $item->episode_number,
  12007. 'status' => $item->status,
  12008. 'error_message' => $item->error_message,
  12009. 'retry_count' => $item->retry_count,
  12010. 'created_at' => $item->created_at,
  12011. 'updated_at' => $item->updated_at,
  12012. 'completed_at' => $item->completed_at
  12013. ];
  12014. })
  12015. ->toArray();
  12016. if (empty($tasks)) {
  12017. Utils::throwError('20003:该剧集没有批量生成任务');
  12018. }
  12019. // 统计各状态数量
  12020. $totalCount = count($tasks);
  12021. $pendingCount = 0;
  12022. $processingCount = 0;
  12023. $completedCount = 0;
  12024. $failedCount = 0;
  12025. $failed_episodes = [];
  12026. foreach ($tasks as $task) {
  12027. switch ($task['status']) {
  12028. case 'pending':
  12029. $pendingCount++;
  12030. break;
  12031. case 'processing':
  12032. $processingCount++;
  12033. break;
  12034. case 'completed':
  12035. $completedCount++;
  12036. break;
  12037. case 'failed':
  12038. $failedCount++;
  12039. // 组装失败分集对象(新对象):分集序号、错误原因
  12040. $failed_episodes[] = [
  12041. 'episode_number' => $task['episode_number'],
  12042. 'error_message' => $task['error_message'] ?? ''
  12043. ];
  12044. break;
  12045. }
  12046. }
  12047. // 计算进度百分比
  12048. $progress = 0;
  12049. if ($totalCount > 0) {
  12050. $progress = round(($completedCount / $totalCount) * 100, 2);
  12051. }
  12052. // 判断整体状态
  12053. $overallStatus = 'processing';
  12054. if ($completedCount === $totalCount) {
  12055. $overallStatus = 'completed';
  12056. } elseif ($pendingCount === $totalCount) {
  12057. $overallStatus = 'pending';
  12058. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  12059. $overallStatus = 'failed';
  12060. }
  12061. return [
  12062. 'anime_id' => $anime_id,
  12063. 'total_episodes' => $totalCount,
  12064. 'pending_count' => $pendingCount,
  12065. 'processing_count' => $processingCount,
  12066. 'completed_count' => $completedCount,
  12067. 'failed_count' => $failedCount,
  12068. 'progress' => $progress,
  12069. 'overall_status' => $overallStatus,
  12070. 'failed_episodes' => $failed_episodes,
  12071. 'tasks' => $tasks
  12072. ];
  12073. }
  12074. /**
  12075. * 将生成内容中不在强制列表中的资源合并进强制列表
  12076. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  12077. *
  12078. * @param array $generated 生成内容中的资源列表
  12079. * @param array $forced 强制资源列表(key为资源名称)
  12080. * @param string $type 资源类型:role、scene、prop
  12081. * @return array
  12082. */
  12083. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  12084. {
  12085. foreach ($generated as $item) {
  12086. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  12087. if ($name === null || $name === '') {
  12088. continue;
  12089. }
  12090. if ($name === '旁白') {
  12091. continue;
  12092. }
  12093. if (!isset($forced[$name])) {
  12094. $forced[$name] = $item;
  12095. }
  12096. }
  12097. return $forced;
  12098. }
  12099. /**
  12100. * 智能匹配并替换主体和场景名称
  12101. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  12102. *
  12103. * @param array $episode_arr 解析后的剧集数据
  12104. * @param array $extra_roles 强制主体设定(key为主体名称)
  12105. * @param array $extra_scenes 强制场景设定(key为场景名称)
  12106. * @return array 替换后的剧集数据
  12107. */
  12108. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  12109. $replaced_count = 0;
  12110. // 1. 处理主体列表
  12111. if (!empty($episode_arr['roles'])) {
  12112. foreach ($episode_arr['roles'] as &$role) {
  12113. $generated_role_name = $role['role'] ?? '';
  12114. // 跳过旁白
  12115. if ($generated_role_name === '旁白') {
  12116. continue;
  12117. }
  12118. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  12119. if (!isset($extra_roles[$generated_role_name])) {
  12120. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  12121. if ($matched_role) {
  12122. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  12123. $role['role'] = $matched_role;
  12124. $replaced_count++;
  12125. }
  12126. }
  12127. }
  12128. }
  12129. // 2. 处理场景列表
  12130. if (!empty($episode_arr['scenes'])) {
  12131. foreach ($episode_arr['scenes'] as &$scene) {
  12132. $generated_scene_name = $scene['scene'] ?? '';
  12133. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  12134. if (!isset($extra_scenes[$generated_scene_name])) {
  12135. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  12136. if ($matched_scene) {
  12137. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  12138. $scene['scene'] = $matched_scene;
  12139. $replaced_count++;
  12140. }
  12141. }
  12142. }
  12143. }
  12144. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  12145. if (!empty($episode_arr['acts'])) {
  12146. foreach ($episode_arr['acts'] as &$act) {
  12147. if (!empty($act['segments'])) {
  12148. foreach ($act['segments'] as &$segment) {
  12149. if (!empty($segment['segment_content'])) {
  12150. $original_content = $segment['segment_content'];
  12151. $replaced_content = $original_content;
  12152. // 替换场景名 - 在文本中查找并替换
  12153. foreach (array_keys($extra_scenes) as $full_scene_name) {
  12154. // 尝试找到可能的短名称
  12155. $potential_short_names = [];
  12156. // 提取场景名的主要部分(冒号之前)
  12157. if (mb_strpos($full_scene_name, ':') !== false) {
  12158. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  12159. $potential_short_names[] = $short_name;
  12160. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  12161. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  12162. $potential_short_names[] = $short_name;
  12163. }
  12164. // 替换场景字段中的短名称
  12165. foreach ($potential_short_names as $short_name) {
  12166. if ($short_name !== $full_scene_name) {
  12167. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  12168. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  12169. if ($new_content !== $replaced_content) {
  12170. $replaced_content = $new_content;
  12171. $replaced_count++;
  12172. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  12173. }
  12174. }
  12175. }
  12176. }
  12177. // 替换配音角色名(跳过旁白)
  12178. foreach (array_keys($extra_roles) as $full_role_name) {
  12179. if ($full_role_name === '旁白') {
  12180. continue;
  12181. }
  12182. // 尝试找到可能的短名称
  12183. $potential_short_names = [];
  12184. // 提取角色名的主要部分(短横线之前)
  12185. if (mb_strpos($full_role_name, '-') !== false) {
  12186. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  12187. $potential_short_names[] = $short_name;
  12188. }
  12189. // 替换配音台词中的短名称
  12190. foreach ($potential_short_names as $short_name) {
  12191. if ($short_name !== $full_role_name) {
  12192. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  12193. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  12194. if ($new_content !== $replaced_content) {
  12195. $replaced_content = $new_content;
  12196. $replaced_count++;
  12197. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  12198. }
  12199. }
  12200. }
  12201. }
  12202. // 如果有替换,更新segment_content
  12203. if ($replaced_content !== $original_content) {
  12204. $segment['segment_content'] = $replaced_content;
  12205. }
  12206. }
  12207. }
  12208. }
  12209. }
  12210. }
  12211. if ($replaced_count > 0) {
  12212. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  12213. 'replaced_count' => $replaced_count
  12214. ]);
  12215. }
  12216. return $episode_arr;
  12217. }
  12218. /**
  12219. * 查找匹配的名称
  12220. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  12221. *
  12222. * @param string $generated_name 生成的名称
  12223. * @param array $expected_names 预期的名称列表
  12224. * @return string|null 匹配到的名称,如果没有匹配则返回null
  12225. */
  12226. private function findMatchingName($generated_name, $expected_names) {
  12227. if (empty($generated_name)) {
  12228. return null;
  12229. }
  12230. // 尝试精确匹配
  12231. if (in_array($generated_name, $expected_names)) {
  12232. return $generated_name;
  12233. }
  12234. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  12235. foreach ($expected_names as $expected_name) {
  12236. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  12237. if (mb_strpos($expected_name, $generated_name) === 0) {
  12238. return $expected_name;
  12239. }
  12240. }
  12241. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  12242. // 这样可以处理一些变体,但优先级较低
  12243. foreach ($expected_names as $expected_name) {
  12244. if (mb_strpos($expected_name, $generated_name) !== false) {
  12245. return $expected_name;
  12246. }
  12247. }
  12248. return null;
  12249. }
  12250. /**
  12251. * 重新生成分段剧本
  12252. * @param array $data 包含以下字段:
  12253. * - prompt: string|null 用户修改要求(可选)
  12254. * - template_id: int|null 提示词模板ID(可选)
  12255. * - act_id: int|null 单个片段ID(与episode_id二选一)
  12256. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  12257. * @return array 返回生成结果
  12258. */
  12259. public function regenerateSegmentScript($data) {
  12260. $uid = Site::getUid();
  12261. $prompt = trim((string)getProp($data, 'prompt', ''));
  12262. $template_id = getProp($data, 'template_id', 0);
  12263. $act_id = getProp($data, 'act_id', 0);
  12264. $episode_id = getProp($data, 'episode_id', 0);
  12265. $check_mode = (int)getProp($data, 'check_mode', 0); // 1=预览确认模式(仅 act_id 模式生效,不落库,返回 editAct 入参)
  12266. // 单片段模式:act_id 可以是数据库真实ID(数字)或预览生成的虚拟ID(字符串),非空即单片段模式
  12267. $isActIdMode = !empty($act_id);
  12268. // 验证:prompt和template_id至少提供一个
  12269. if (empty($prompt) && empty($template_id)) {
  12270. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  12271. }
  12272. // 验证:act_id和episode_id二选一
  12273. if (empty($act_id) && empty($episode_id)) {
  12274. Utils::throwError('20003:请提供片段ID或剧集ID');
  12275. }
  12276. if (!empty($act_id) && !empty($episode_id)) {
  12277. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  12278. }
  12279. // 积分余额预检:act_id 单片段模式按 normal 档,episode_id 剧集模式按 special 档
  12280. $chargeType = $isActIdMode ? 'normal' : 'special';
  12281. if ($isActIdMode) {
  12282. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', $chargeType), $uid);
  12283. } else {
  12284. $is_generated = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('is_generated');
  12285. if ($is_generated) Utils::throwError('20003:该分集已不支持重新生成片段,请创建副本后重试!');
  12286. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', $chargeType), $uid);
  12287. }
  12288. // 如果提供了template_id,获取模板提示词
  12289. $template_prompt = '';
  12290. if ($template_id > 0) {
  12291. $template = DB::table('mp_prompt_templates')
  12292. ->where('id', $template_id)
  12293. ->where('is_deleted', 0)
  12294. ->first();
  12295. if (!$template) {
  12296. Utils::throwError('20003:提示词模板不存在或已删除');
  12297. }
  12298. $template_prompt = $template->template_prompt ?? '';
  12299. }
  12300. // 合并用户提示词和模板提示词(模板提示词与用户输入基本一致时只保留一个,避免重复提示词)
  12301. $final_prompt = '';
  12302. if (!empty($template_prompt)) {
  12303. $trimmedPrompt = trim((string)$prompt);
  12304. if ($trimmedPrompt !== '' && mb_strtolower($trimmedPrompt) === mb_strtolower(trim($template_prompt))) {
  12305. $final_prompt = $template_prompt;
  12306. } elseif (!empty($prompt)) {
  12307. $final_prompt = $template_prompt . "\n\n补充要求:" . $prompt;
  12308. } else {
  12309. $final_prompt = $template_prompt;
  12310. }
  12311. } else {
  12312. $final_prompt = $prompt;
  12313. }
  12314. // 获取需要重新生成的内容参考
  12315. $reference_content = '';
  12316. $target_episode_id = 0;
  12317. $target_anime_id = 0;
  12318. $target_episode_number = 0;
  12319. if ($isActIdMode) {
  12320. // 单个片段模式:获取该片段的内容
  12321. $segment = DB::table('mp_episode_segments')
  12322. ->where('id', $act_id)
  12323. ->first();
  12324. // 数据库不存在时,尝试从预览虚拟 act_id 保存的 redis 数据中恢复
  12325. if (!$segment) {
  12326. $previewData = Redis::get($this->buildActPreviewKey($act_id));
  12327. if ($previewData) {
  12328. $previewData = json_decode($previewData, true);
  12329. $segment = (object)[
  12330. 'anime_id' => getProp($previewData, 'anime_id'),
  12331. 'episode_id' => getProp($previewData, 'episode_id'),
  12332. 'episode_number' => getProp($previewData, 'episode_number'),
  12333. 'act_number' => getProp($previewData, 'act_number'),
  12334. 'act_duration' => getProp($previewData, 'act_duration'),
  12335. 'act_content' => getProp($previewData, 'act_content'),
  12336. ];
  12337. }
  12338. }
  12339. if (!$segment) {
  12340. Utils::throwError('20003:片段不存在');
  12341. }
  12342. $target_episode_id = $segment->episode_id;
  12343. $target_anime_id = $segment->anime_id;
  12344. $target_episode_number = $segment->episode_number;
  12345. $reference_content = $segment->act_content ?? '';
  12346. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  12347. } else {
  12348. // 整个剧集模式:获取所有片段的内容
  12349. $segments = DB::table('mp_episode_segments')
  12350. ->where('episode_id', $episode_id)
  12351. ->orderBy('act_number')
  12352. ->get();
  12353. if ($segments->isEmpty()) {
  12354. Utils::throwError('20003:该剧集没有片段数据');
  12355. }
  12356. $target_episode_id = $episode_id;
  12357. $target_anime_id = $segments[0]->anime_id;
  12358. $target_episode_number = $segments[0]->episode_number;
  12359. // 拼接所有片段内容,保留格式用于AI理解
  12360. $act_contents = [];
  12361. foreach ($segments as $seg) {
  12362. $act_number = $seg->act_number;
  12363. $act_content = $seg->act_content ?? '';
  12364. if (!empty($act_content)) {
  12365. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  12366. }
  12367. }
  12368. $reference_content = implode("\n\n", $act_contents);
  12369. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  12370. if ($episode_content) {
  12371. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【原分段剧本内容】\n{$reference_content}";
  12372. //$reference_content = "\n\n【本集原始内容】\n{$episode_content}";
  12373. }else {
  12374. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  12375. }
  12376. }
  12377. if (empty($reference_content)) {
  12378. Utils::throwError('20003:没有可参考的片段内容');
  12379. }
  12380. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  12381. $episode = DB::table('mp_anime_episodes')
  12382. ->where('id', $target_episode_id)
  12383. ->first();
  12384. if (!$episode) {
  12385. Utils::throwError('20003:剧集不存在');
  12386. }
  12387. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  12388. $anime_script_id = getProp($anime, 'script_id');
  12389. $intro = $episode->intro ?? '';
  12390. $art_style = $episode->art_style ?? '';
  12391. $roles = json_decode($episode->roles ?? '[]', true);
  12392. $scenes = json_decode($episode->scenes ?? '[]', true);
  12393. $props = json_decode($episode->props ?? '[]', true);
  12394. // 构建提示词中的主体列表和场景列表参考
  12395. $roles_ref = '';
  12396. if (!empty($roles) && is_array($roles)) {
  12397. $roles_list = [];
  12398. foreach ($roles as $role) {
  12399. $role_name = getProp($role, 'role', '');
  12400. $role_desc = getProp($role, 'description', '');
  12401. $pic_prompt = getProp($role, 'pic_prompt', '');
  12402. $voice_prompt = getProp($role, 'voice_prompt', '');
  12403. if (!empty($role_name)) {
  12404. $role_line = $role_name;
  12405. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  12406. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  12407. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  12408. $roles_list[] = $role_line;
  12409. }
  12410. }
  12411. if (!empty($roles_list)) {
  12412. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  12413. }
  12414. }
  12415. $scenes_ref = '';
  12416. if (!empty($scenes) && is_array($scenes)) {
  12417. $scenes_list = [];
  12418. foreach ($scenes as $scene) {
  12419. $scene_name = getProp($scene, 'scene', '');
  12420. $scene_desc = getProp($scene, 'description', '');
  12421. $pic_prompt = getProp($scene, 'pic_prompt', '');
  12422. if (!empty($scene_name)) {
  12423. $scene_line = $scene_name;
  12424. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  12425. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  12426. $scenes_list[] = $scene_line;
  12427. }
  12428. }
  12429. if (!empty($scenes_list)) {
  12430. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  12431. }
  12432. }
  12433. $props_ref = '';
  12434. if (!empty($props) && is_array($props)) {
  12435. $props_list = [];
  12436. foreach ($props as $prop) {
  12437. $prop_name = getProp($prop, 'prop', '');
  12438. $prop_desc = getProp($prop, 'description', '');
  12439. $pic_prompt = getProp($prop, 'pic_prompt', '');
  12440. if (!empty($prop_name)) {
  12441. $prop_line = $prop_name;
  12442. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  12443. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  12444. $props_list[] = $prop_line;
  12445. }
  12446. }
  12447. if (!empty($props_list)) {
  12448. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  12449. }
  12450. }
  12451. // 构建美术风格参考
  12452. $art_style_ref = '';
  12453. if (!empty($art_style)) {
  12454. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  12455. }
  12456. // 构建内容简介参考
  12457. $intro_ref = '';
  12458. if (!empty($intro)) {
  12459. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  12460. }
  12461. // 构建完整的AI提示词
  12462. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  12463. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  12464. $user_prompt .= $intro_ref;
  12465. $user_prompt .= $art_style_ref;
  12466. $user_prompt .= $reference_content;
  12467. $user_prompt .= "\n\n【生成要求】\n- 请以【原分段剧本内容】为蓝本,保留剧情脉络、角色、场景与分段结构,但必须围绕【用户要求】对相关片段进行实质性修改;若【用户要求】未指定具体修改点,也需对画面、运镜、台词等描述进行改写,禁止整段原样复制。\n";
  12468. // $user_prompt .= $roles_ref;
  12469. // $user_prompt .= $scenes_ref;
  12470. // 输出格式铁律(用户消息侧再次强制,避免模型自由发挥)
  12471. $user_prompt .= "\n\n【输出格式铁律-必须严格遵守】\n";
  12472. if ($isActIdMode) {
  12473. $user_prompt .= "- 请直接以“##片段1”开头,紧跟“时长:X s”行,然后输出本片段的完整分镜内容(分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效),分镜从1开始连续编号。\n";
  12474. $user_prompt .= "- 只允许根据【原分段剧本内容】生成一个片段(即“##片段1”),禁止生成多个片段。\n";
  12475. } else {
  12476. $user_prompt .= "- 请以“###分段剧本”开头,依次输出“片段数量:N”、“旁白音色:...”,然后按“##片段N”逐段输出,每段必须紧跟“时长:X s”行,再输出该片段的完整分镜内容(分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效),分镜从1开始连续编号。\n";
  12477. }
  12478. $user_prompt .= "- 缺少“##片段N”标题或“时长:”行即为格式错误;输出前必须检查格式,不得输出其他任何内容。\n";
  12479. $user_prompt .= "- 片段时长必须在4秒到15秒之间(4s≤时长≤15s),超过15秒必须拆分为多个片段,不得输出低于4秒或超过15秒的片段。\n";
  12480. // 整集模式:强制生成与原来一致的片段数量
  12481. if ($episode_id > 0 && isset($segments)) {
  12482. $originSegmentCount = count($segments);
  12483. $user_prompt .= "- 本集原有{$originSegmentCount}个片段,必须严格生成{$originSegmentCount}个片段(##片段1 到 ##片段{$originSegmentCount}),不得多不得少。\n";
  12484. }
  12485. $system_prompt = "\n\n【输出格式铁律-最高优先级】\n";
  12486. if ($isActIdMode) {
  12487. $system_prompt .= "- 直接以“##片段1”开头,紧跟“时长:X s”行,然后输出本片段分镜内容\n";
  12488. $system_prompt .= "- 只允许根据【原分段剧本内容】生成一个片段(即“##片段1”),禁止生成多个片段。\n";
  12489. } else {
  12490. $system_prompt .= "- 以“###分段剧本”开头,输出“片段数量:N”、“旁白音色:...”\n";
  12491. $system_prompt .= "- 然后按“##片段N”逐段输出,每段紧跟“时长:X s”行\n";
  12492. }
  12493. $system_prompt .= "- 每个片段必须严格以“##片段N”开头(N从1开始连续),并且必须包含“时长:X s”行,缺少即为格式错误\n";
  12494. $system_prompt .= "- 片段时长必须在4~15秒之间(4s≤时长≤15s),超过15秒必须拆分为多个片段,禁止输出低于4秒或超过15秒的片段\n";
  12495. $system_prompt .= "- 输出前检查:若缺少##片段N标题或时长行,视为输出无效,必须修正后输出\n\n";
  12496. $system_prompt .= "【强制要求】\n";
  12497. // $system_prompt .= "- 请严格参考【本集原始内容】或【原分段剧本内容】进行本次生成,注意新生成的分段剧本内容一定不要跟【原分段剧本内容】一致,要进行一定程度调整\n";
  12498. $system_prompt .= "- 【重要】必须参考【本集原始内容】与【原分段剧本内容】中的剧情脉络、角色、场景、道具和分段结构,但严禁原样复制或几乎照抄原文;必须围绕【用户要求】对相关内容进行实质性修改,若生成结果与【原分段剧本内容】完全一致或未体现用户要求,视为生成失败\n";
  12499. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:\n";
  12500. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)\n";
  12501. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  12502. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  12503. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  12504. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  12505. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  12506. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  12507. $system_prompt .= "- 【重要】每个片段必须以“##片段N”开头(N为序号),并且必须包含“时长:X s”行,缺少片段标题或时长视为格式错误\n";
  12508. // 按模式构造强制输出格式:只传 act_id(单片段)时不需要 ###分段剧本/片段数量/旁白音色;传 episode_id(整集)时需要完整格式
  12509. $segmentHeader = '';
  12510. if ($episode_id > 0) {
  12511. $segmentHeader = "###分段剧本\n片段数量:8\n旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。\n\n";
  12512. }
  12513. $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背景音效:";
  12514. // 获取模型配置
  12515. $model = getProp($data, 'model');
  12516. if (!$model) {
  12517. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  12518. }
  12519. // 验证模型是否在可用模型表中
  12520. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  12521. $model = 'deepseek-v4-pro';
  12522. }
  12523. // 模型兼容性处理
  12524. $thinkingMode = 'disabled';
  12525. $reasoningEffort = 'high';
  12526. if ($model === 'deepseek-chat') {
  12527. $model = 'deepseek-v4-flash';
  12528. $thinkingMode = 'disabled';
  12529. } elseif ($model === 'deepseek-reasoner') {
  12530. $model = 'deepseek-v4-flash';
  12531. $thinkingMode = 'enabled';
  12532. }
  12533. // 构建消息
  12534. $messages = [
  12535. [
  12536. 'role' => 'system',
  12537. 'content' => $system_prompt
  12538. ],
  12539. [
  12540. 'role' => 'user',
  12541. 'content' => $user_prompt
  12542. ]
  12543. ];
  12544. // dd($messages);
  12545. // 构建请求参数
  12546. $post_data = [
  12547. 'model' => $model,
  12548. 'messages' => $messages,
  12549. 'temperature' => 1.4,
  12550. 'frequency_penalty' => 0.3,
  12551. 'presence_penalty' => 0,
  12552. 'response_format' => ['type' => 'text'],
  12553. 'thinking' => ['type' => $thinkingMode],
  12554. 'stream' => false // 非流式输出
  12555. ];
  12556. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  12557. // 调用AI生成新的分段剧本
  12558. try {
  12559. $fullContent = '';
  12560. $usage = [];
  12561. // 根据模型类型选择调用方法
  12562. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  12563. if (is_array($chatResult)) {
  12564. $fullContent = $chatResult['fullContent'] ?? '';
  12565. $usage = $chatResult['usage'] ?? [];
  12566. }
  12567. $generated_content = $fullContent;
  12568. // 归一化"场景:"标签换行格式:场景:\n场景名\n => 场景:场景名\n,保证场景字段为一行
  12569. $generated_content = preg_replace('/场景[::]\s*\n\s*([^\n]+)/u', '场景:$1', $generated_content);
  12570. if (empty($generated_content)) {
  12571. Utils::throwError('20003:AI生成内容为空,请重试');
  12572. }
  12573. dLog('deepseek')->info('regenerateSegmentScript AI生成内容', [
  12574. 'act_id' => $act_id,
  12575. 'episode_id' => $episode_id,
  12576. 'content_length' => mb_strlen($generated_content),
  12577. 'content_head' => mb_substr($generated_content, 0, 500),
  12578. 'content_tail' => mb_substr($generated_content, -200),
  12579. ]);
  12580. // 解析生成的内容 - 按片段分割
  12581. $parsed_segments = [];
  12582. // 先在开头添加换行符,确保第1片段也能被正确分割
  12583. $normalizedText = "\n" . $generated_content;
  12584. $parts = preg_split('/\n\s*##/', $normalizedText);
  12585. foreach ($parts as $part) {
  12586. $part = trim($part);
  12587. if (empty($part)) continue;
  12588. // 匹配"片段X"格式
  12589. if (!preg_match('/^片段\d+/', $part)) {
  12590. continue;
  12591. }
  12592. // 分离标题和内容
  12593. $lines = explode("\n", $part, 2);
  12594. $actTitle = trim($lines[0]);
  12595. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  12596. // 解析标题,提取序号
  12597. $actNumber = 0;
  12598. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  12599. $actNumber = intval($segmentTitleMatch[1]);
  12600. } else {
  12601. $actNumber = count($parsed_segments) + 1;
  12602. }
  12603. // 提取时长(仅保留数字)
  12604. $actDuration = 0;
  12605. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  12606. $actDurationStr = trim($actDurationMatch[1]);
  12607. // 提取数字部分(支持整数和小数)
  12608. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  12609. $actDuration = (float)$numMatch[1];
  12610. }
  12611. }
  12612. // 时长范围约束:4~15秒,超限兜底修正(0=未知按最低4秒)
  12613. if ($actDuration > 15) {
  12614. $actDuration = 15;
  12615. }
  12616. if ($actDuration < 4) {
  12617. $actDuration = 4;
  12618. }
  12619. // 清理act_content:去除时长、旁白音色等非分镜内容行,只保留分镜内容
  12620. $cleaned_content = $this->cleanSegmentContent($actContent);
  12621. $parsed_segments[] = [
  12622. 'act_number' => $actNumber,
  12623. 'act_title' => $actTitle,
  12624. 'act_duration' => $actDuration,
  12625. 'act_content' => $cleaned_content,
  12626. ];
  12627. }
  12628. // 兜底:模型未输出 ##片段N 标题时(如直接输出分镜正文),将整个生成内容作为单个片段解析(act_id 单片段场景)
  12629. if (empty($parsed_segments)) {
  12630. $fallbackContent = $this->cleanSegmentContent($generated_content);
  12631. if ($fallbackContent !== '') {
  12632. $fallbackDuration = 0;
  12633. if (preg_match('/时长[::]\s*([^\n]+)/u', $generated_content, $durationMatch)) {
  12634. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $durationMatch[1], $numMatch)) {
  12635. $fallbackDuration = (float)$numMatch[1];
  12636. }
  12637. }
  12638. // 内容未带时长时,单片段模式沿用原片段的时长
  12639. if ($fallbackDuration <= 0 && $isActIdMode && !empty($segment->act_duration)) {
  12640. $fallbackDuration = (float)$segment->act_duration;
  12641. }
  12642. // 时长范围约束:4~15秒,超限兜底修正(0=未知按最低4秒)
  12643. if ($fallbackDuration > 15) {
  12644. $fallbackDuration = 15;
  12645. }
  12646. if ($fallbackDuration < 4) {
  12647. $fallbackDuration = 4;
  12648. }
  12649. $parsed_segments[] = [
  12650. 'act_number' => 1,
  12651. 'act_title' => '片段1',
  12652. 'act_duration' => $fallbackDuration,
  12653. 'act_content' => $fallbackContent,
  12654. ];
  12655. }
  12656. }
  12657. // act_id 单片段模式:只允许一个片段,多余片段丢弃,仅保留第一个
  12658. if ($isActIdMode && count($parsed_segments) > 1) {
  12659. dLog('deepseek')->info('regenerateSegmentScript act_id 模式仅保留第一个片段', [
  12660. 'act_id' => $act_id,
  12661. 'original_count' => count($parsed_segments),
  12662. ]);
  12663. $parsed_segments = array_slice($parsed_segments, 0, 1);
  12664. }
  12665. dLog('deepseek')->info('regenerateSegmentScript 解析结果', [
  12666. 'act_id' => $act_id,
  12667. 'episode_id' => $episode_id,
  12668. 'segment_count' => count($parsed_segments),
  12669. 'segments' => array_map(function ($seg) {
  12670. return [
  12671. 'act_number' => $seg['act_number'],
  12672. 'act_duration' => $seg['act_duration'],
  12673. 'content_length' => mb_strlen($seg['act_content']),
  12674. ];
  12675. }, $parsed_segments),
  12676. ]);
  12677. if (empty($parsed_segments)) {
  12678. dLog('deepseek')->error('regenerateSegmentScript 无法解析生成的分段剧本', [
  12679. 'act_id' => $act_id,
  12680. 'episode_id' => $episode_id,
  12681. 'content_length' => mb_strlen($generated_content),
  12682. 'content_head' => mb_substr($generated_content, 0, 1000),
  12683. 'content_tail' => mb_substr($generated_content, -300),
  12684. ]);
  12685. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  12686. }
  12687. // 收集所有资产名称(角色、场景、道具)
  12688. $product_names = [];
  12689. // 收集角色名称
  12690. if (!empty($roles) && is_array($roles)) {
  12691. foreach ($roles as $role) {
  12692. $role_name = getProp($role, 'role', '');
  12693. if (!empty($role_name)) {
  12694. $product_names[] = $role_name;
  12695. }
  12696. }
  12697. }
  12698. // 收集场景名称
  12699. if (!empty($scenes) && is_array($scenes)) {
  12700. foreach ($scenes as $scene) {
  12701. $scene_name = getProp($scene, 'scene', '');
  12702. if (!empty($scene_name)) {
  12703. $product_names[] = $scene_name;
  12704. }
  12705. }
  12706. }
  12707. // 收集道具名称
  12708. if (!empty($props) && is_array($props)) {
  12709. foreach ($props as $prop) {
  12710. $prop_name = getProp($prop, 'prop', '');
  12711. if (!empty($prop_name)) {
  12712. $product_names[] = $prop_name;
  12713. }
  12714. }
  12715. }
  12716. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  12717. $product_names = array_unique($product_names);
  12718. usort($product_names, function($a, $b) {
  12719. return mb_strlen($b) - mb_strlen($a);
  12720. });
  12721. // 处理每个片段的 act_show_content
  12722. foreach ($parsed_segments as &$segment) {
  12723. $act_content = getProp($segment, 'act_content', '');
  12724. if (empty($act_content)) {
  12725. $segment['act_show_content'] = '';
  12726. continue;
  12727. }
  12728. $processed_content = $act_content;
  12729. // 统一替换所有资产名称为 {资产名} 格式
  12730. // 使用占位符避免嵌套替换问题
  12731. $placeholder_map = [];
  12732. $placeholder_index = 0;
  12733. foreach ($product_names as $product_name) {
  12734. // 转义特殊字符
  12735. $escaped_product = preg_quote($product_name, '/');
  12736. // 检查是否匹配且未被 {} 包裹
  12737. $processed_content = preg_replace_callback(
  12738. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  12739. function($matches) use (&$placeholder_map, &$placeholder_index) {
  12740. // 使用唯一占位符
  12741. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  12742. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  12743. $placeholder_index++;
  12744. return $placeholder;
  12745. },
  12746. $processed_content
  12747. );
  12748. }
  12749. // 将所有占位符替换回实际内容
  12750. foreach ($placeholder_map as $placeholder => $replacement) {
  12751. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  12752. }
  12753. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  12754. $shot_counter = 0;
  12755. $processed_content = preg_replace_callback(
  12756. // 兼容“【镜头 1】”“【分镜 1】”等分镜/镜头与数字间带空格的情况
  12757. '/【(?:镜头|分镜)\s*(\d+)】/u',
  12758. function($matches) use (&$shot_counter) {
  12759. $shot_counter++;
  12760. return '【镜头' . $shot_counter . '】';
  12761. },
  12762. $processed_content
  12763. );
  12764. $segment['act_show_content'] = $processed_content;
  12765. }
  12766. unset($segment); // 解除引用
  12767. // 保存到数据库
  12768. $now = date('Y-m-d H:i:s');
  12769. $saved_acts = []; // 用于记录保存后的片段信息
  12770. if ($isActIdMode) {
  12771. // 单个片段模式:更新单条记录
  12772. if (count($parsed_segments) > 0) {
  12773. $new_segment = $parsed_segments[0];
  12774. // 预览确认模式(check_mode=1):不落库,组装 editAct 入参返回,由前端确认后调用 editAct 更新
  12775. if ($check_mode === 1) {
  12776. // 单片段预览生成即按 normal 档扣费
  12777. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12778. 'anime_id' => $target_anime_id,
  12779. 'episode_id' => $target_episode_id,
  12780. 'model' => $model,
  12781. 'source' => 'regenerateSegmentScript',
  12782. ], 'normal');
  12783. return [
  12784. 'check_mode' => 1,
  12785. 'act_id' => $act_id,
  12786. 'act_title' => getProp($new_segment, 'act_title', ''),
  12787. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  12788. 'act_content' => getProp($new_segment, 'act_show_content', ''),
  12789. ];
  12790. }
  12791. // 虚拟 act_id 仅用于预览/参考,不允许直接保存到数据库
  12792. if (!is_numeric($act_id)) {
  12793. Utils::throwError('20003:该片段不可直接保存');
  12794. }
  12795. $update_data = [
  12796. 'act_content' => getProp($new_segment, 'act_content', ''),
  12797. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  12798. 'act_title' => getProp($new_segment, 'act_title', ''),
  12799. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  12800. 'updated_at' => $now,
  12801. ];
  12802. DB::table('mp_episode_segments')
  12803. ->where('id', $act_id)
  12804. ->update($update_data);
  12805. // 获取更新后的记录
  12806. $updated_act = DB::table('mp_episode_segments')
  12807. ->where('id', $act_id)
  12808. ->first();
  12809. if ($updated_act) {
  12810. $saved_acts[] = [
  12811. 'act_id' => $updated_act->id,
  12812. 'act_number' => $updated_act->act_number,
  12813. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  12814. 'act_content' => $updated_act->act_content,
  12815. 'act_show_content' => $updated_act->act_show_content,
  12816. 'video_url' => $updated_act->video_url ?? '',
  12817. 'video_duration' => $updated_act->video_duration ?? 0,
  12818. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  12819. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  12820. ];
  12821. }
  12822. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  12823. // 单片段模式成功扣费(normal 档)
  12824. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12825. 'anime_id' => $target_anime_id,
  12826. 'episode_id' => $target_episode_id,
  12827. 'model' => $model,
  12828. 'source' => 'regenerateSegmentScript',
  12829. ], 'normal');
  12830. }
  12831. } else {
  12832. // 预览确认模式(check_mode=1):不落库,返回展示参数供前端确认后调用 saveEpisodeActs 保存
  12833. if ($check_mode === 1) {
  12834. // 剧集模式预览生成即扣除积分并记录 token 明细(special 档)
  12835. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12836. 'anime_id' => $target_anime_id,
  12837. 'episode_id' => $target_episode_id,
  12838. 'model' => $model,
  12839. 'source' => 'regenerateSegmentScript',
  12840. ], 'special');
  12841. // 为每个片段生成虚拟 act_id 并写入 redis(1天有效),供后续按虚拟 act_id 恢复片段数据
  12842. $previewActs = [];
  12843. foreach ($parsed_segments as $seg) {
  12844. $virtualActId = 'preview_' . time() . '_' . uniqid();
  12845. Redis::setex($this->buildActPreviewKey($virtualActId), 86400, json_encode([
  12846. 'anime_id' => $target_anime_id,
  12847. 'episode_id' => $target_episode_id,
  12848. 'episode_number' => $target_episode_number,
  12849. 'act_number' => $seg['act_number'],
  12850. 'act_title' => $seg['act_title'],
  12851. 'act_duration' => $seg['act_duration'],
  12852. 'act_content' => $seg['act_content'],
  12853. 'act_show_content'=> $seg['act_show_content'],
  12854. ], JSON_UNESCAPED_UNICODE));
  12855. $previewActs[] = [
  12856. 'act_id' => $virtualActId,
  12857. 'act_number' => $seg['act_number'],
  12858. 'act_title' => $seg['act_title'],
  12859. 'act_duration' => $seg['act_duration'],
  12860. 'act_content' => $seg['act_content'],
  12861. 'act_show_content' => $seg['act_show_content'],
  12862. 'video_url' => '',
  12863. 'video_duration' => 0,
  12864. 'video_time_point_start' => 0,
  12865. 'video_time_point_end' => 0,
  12866. 'last_frame_url' => '',
  12867. 'current_type' => 0,
  12868. ];
  12869. }
  12870. return [
  12871. 'check_mode' => 1,
  12872. 'anime_id' => $target_anime_id,
  12873. 'episode_id' => $target_episode_id,
  12874. 'title' => getProp($episode, 'title', ''),
  12875. 'episode_number' => $target_episode_number,
  12876. 'is_generated' => getProp($episode, 'is_generated', 0),
  12877. 'acts' => $previewActs,
  12878. ];
  12879. }
  12880. // 整个剧集模式:删除原有记录并批量保存新记录
  12881. DB::beginTransaction();
  12882. try {
  12883. // 删除原有的所有片段记录
  12884. DB::table('mp_episode_segments')
  12885. ->where('episode_id', $target_episode_id)
  12886. ->delete();
  12887. // 批量插入新的片段记录
  12888. $segments_to_insert = [];
  12889. foreach ($parsed_segments as $index => $segment) {
  12890. $act_number = $index + 1;
  12891. $segments_to_insert[] = [
  12892. 'anime_id' => $target_anime_id,
  12893. 'episode_id' => $target_episode_id,
  12894. 'episode_number' => $target_episode_number,
  12895. 'act_number' => $act_number,
  12896. 'act_title' => getProp($segment, 'act_title', ''),
  12897. 'act_duration' => getProp($segment, 'act_duration', 0),
  12898. 'act_content' => getProp($segment, 'act_content', ''),
  12899. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  12900. 'created_at' => $now,
  12901. 'updated_at' => $now,
  12902. ];
  12903. }
  12904. if (!empty($segments_to_insert)) {
  12905. DB::table('mp_episode_segments')->insert($segments_to_insert);
  12906. }
  12907. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(special 档,与保存同事务)
  12908. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12909. 'anime_id' => $target_anime_id,
  12910. 'episode_id' => $target_episode_id,
  12911. 'model' => $model,
  12912. 'source' => 'regenerateSegmentScript',
  12913. ], 'special');
  12914. DB::commit();
  12915. // 查询保存后的所有片段记录
  12916. $saved_segments = DB::table('mp_episode_segments')
  12917. ->where('episode_id', $target_episode_id)
  12918. ->orderBy('act_number')
  12919. ->get();
  12920. foreach ($saved_segments as $saved_segment) {
  12921. $saved_acts[] = [
  12922. 'act_id' => $saved_segment->id,
  12923. 'act_number' => $saved_segment->act_number,
  12924. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  12925. 'act_content' => $saved_segment->act_content,
  12926. 'act_show_content' => $saved_segment->act_show_content,
  12927. 'video_url' => $saved_segment->video_url ?? '',
  12928. 'video_duration' => $saved_segment->video_duration ?? 0,
  12929. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  12930. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  12931. ];
  12932. }
  12933. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  12934. 'episode_id' => $target_episode_id,
  12935. 'segments_count' => count($segments_to_insert)
  12936. ]);
  12937. } catch (\Exception $e) {
  12938. DB::rollBack();
  12939. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  12940. Utils::throwError('20003:保存失败,请重试');
  12941. }
  12942. }
  12943. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  12944. return [
  12945. 'anime_id' => $target_anime_id,
  12946. 'episode_id' => $target_episode_id,
  12947. 'title' => getProp($episode, 'title', ''),
  12948. 'episode_number' => $target_episode_number,
  12949. 'is_generated' => getProp($episode, 'is_generated', 0),
  12950. 'acts' => $saved_acts,
  12951. ];
  12952. } catch (\Exception $e) {
  12953. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  12954. throw $e;
  12955. }
  12956. }
  12957. /**
  12958. * 保存剧集片段(预览确认模式使用):删除旧数据并批量保存新数据到 mp_episode_segments
  12959. *
  12960. * 逻辑与 regenerateSegmentScript 的 episode_id + check_mode=0 保存保持一致。
  12961. *
  12962. * @param array $data 请求参数:episode_id 必填,acts 必填(预览返回的片段数组)
  12963. * @return array
  12964. */
  12965. public function saveEpisodeActs($data) {
  12966. $uid = Site::getUid();
  12967. $episode_id = (int)getProp($data, 'episode_id', 0);
  12968. $acts = getProp($data, 'acts', []);
  12969. if (!$episode_id) {
  12970. Utils::throwError('20003:请提供剧集ID');
  12971. }
  12972. if (!is_array($acts) || empty($acts)) {
  12973. Utils::throwError('20003:请提供片段数据');
  12974. }
  12975. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  12976. if (!$episode) {
  12977. Utils::throwError('20003:剧集不存在');
  12978. }
  12979. // 用户校验:只能调整自己的剧集
  12980. $anime = DB::table('mp_animes')->where('id', $episode->anime_id)->first();
  12981. if (!$anime || (int)$anime->user_id !== (int)$uid) {
  12982. Utils::throwError('20003:没有权限操作该剧集');
  12983. }
  12984. $anime_id = (int)$episode->anime_id;
  12985. $episode_number = (int)$episode->episode_number;
  12986. $now = date('Y-m-d H:i:s');
  12987. try {
  12988. DB::beginTransaction();
  12989. // 删除原有的所有片段记录
  12990. DB::table('mp_episode_segments')
  12991. ->where('episode_id', $episode_id)
  12992. ->delete();
  12993. // 批量插入新的片段记录
  12994. $segments_to_insert = [];
  12995. $index = 0;
  12996. foreach ($acts as $act) {
  12997. if (!is_array($act)) {
  12998. continue;
  12999. }
  13000. $index++;
  13001. $segments_to_insert[] = [
  13002. 'anime_id' => $anime_id,
  13003. 'episode_id' => $episode_id,
  13004. 'episode_number' => $episode_number,
  13005. 'act_number' => (int)getProp($act, 'act_number', $index),
  13006. 'act_title' => (string)getProp($act, 'act_title', ''),
  13007. 'act_duration' => (float)getProp($act, 'act_duration', 0),
  13008. 'act_content' => (string)getProp($act, 'act_content', ''),
  13009. // 'act_show_content' => (string)getProp($act, 'act_show_content', ''),
  13010. 'created_at' => $now,
  13011. 'updated_at' => $now,
  13012. ];
  13013. }
  13014. if (empty($segments_to_insert)) {
  13015. DB::rollBack();
  13016. Utils::throwError('20003:没有有效的片段数据');
  13017. }
  13018. DB::table('mp_episode_segments')->insert($segments_to_insert);
  13019. DB::commit();
  13020. } catch (\Exception $e) {
  13021. DB::rollBack();
  13022. dLog('deepseek')->error('保存剧集片段失败: ' . $e->getMessage(), [
  13023. 'episode_id' => $episode_id,
  13024. ]);
  13025. Utils::throwError('20003:保存失败,请重试');
  13026. }
  13027. // 查询保存后的所有片段记录(数组化,与 episodeInfoForAce 处理一致)
  13028. $saved_segments = DB::table('mp_episode_segments')
  13029. ->where('episode_id', $episode_id)
  13030. ->orderBy('act_number')
  13031. ->get()
  13032. ->map(function ($value) {
  13033. return (array)$value;
  13034. })
  13035. ->toArray();
  13036. // 构造与 episodeInfoForAce 一致的 acts 与 total_duration
  13037. $acts = [];
  13038. $totalDuration = 0;
  13039. foreach ($saved_segments as $segment) {
  13040. $videoDuration = getProp($segment, 'video_duration');
  13041. $actDuration = getProp($segment, 'act_duration');
  13042. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  13043. $totalDuration += floatval($videoDuration);
  13044. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  13045. $totalDuration += floatval($actDuration);
  13046. } else {
  13047. $totalDuration += 5;
  13048. }
  13049. $acts[] = [
  13050. 'act_id' => getProp($segment, 'id'),
  13051. 'act_number' => getProp($segment, 'act_number'),
  13052. 'act_title' => getProp($segment, 'act_title'),
  13053. 'act_duration' => getProp($segment, 'act_duration'),
  13054. 'act_content' => getProp($segment, 'act_content'),
  13055. 'video_url' => getProp($segment, 'video_url'),
  13056. 'video_duration' => getProp($segment, 'video_duration', 0),
  13057. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  13058. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  13059. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  13060. 'current_type' => getProp($segment, 'current_type'),
  13061. ];
  13062. }
  13063. // 顶层与 episodeInfoForAce 一致
  13064. $result = [
  13065. 'episode_id' => $episode_id,
  13066. 'anime_id' => $anime_id,
  13067. 'episode_number' => $episode_number,
  13068. 'title' => getProp($episode, 'title'),
  13069. 'intro' => getProp($episode, 'intro'),
  13070. 'art_style' => getProp($episode, 'art_style'),
  13071. 'roles' => json_decode(getProp($episode, 'roles', '[]'), true),
  13072. 'scenes' => json_decode(getProp($episode, 'scenes', '[]'), true),
  13073. 'props' => getProp($episode, 'props') ? json_decode(getProp($episode, 'props'), true) : [],
  13074. 'is_generated' => getProp($episode, 'is_generated'),
  13075. 'acts' => array_values($acts),
  13076. 'total_duration' => intval(round($totalDuration)),
  13077. ];
  13078. // video_params(从 mp_animes 取,与 episodeInfoForAce 一致)
  13079. $animeRow = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  13080. $result['video_params'] = [
  13081. 'video_model' => getProp($animeRow, 'video_model'),
  13082. 'video_resolution' => getProp($animeRow, 'video_resolution'),
  13083. 'ratio' => getProp($animeRow, 'video_ratio'),
  13084. ];
  13085. return $result;
  13086. }
  13087. /**
  13088. * 预览虚拟 act_id 在 redis 中的键
  13089. *
  13090. * @param mixed $actId
  13091. * @return string
  13092. */
  13093. private function buildActPreviewKey($actId): string
  13094. {
  13095. return 'anime_act_preview:' . $actId;
  13096. }
  13097. /**
  13098. * 清理分镜内容:去除时长、旁白音色等非分镜行,只保留完整分镜内容(分镜标记统一为【分镜N】/【镜头N】)
  13099. *
  13100. * @param string $actContent
  13101. * @return string
  13102. */
  13103. private function cleanSegmentContent(string $actContent): string
  13104. {
  13105. $cleaned_content = '';
  13106. $content_lines = explode("\n", $actContent);
  13107. $is_capturing = false; // 标记是否开始捕获分镜内容
  13108. $count = 0;
  13109. foreach ($content_lines as $line) {
  13110. $trimmed_line = trim($line);
  13111. // 跳过时长、旁白音色等非分镜行
  13112. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  13113. continue;
  13114. }
  13115. // 检测分镜开始(支持【分镜X】【镜头X】、分镜X、镜头X,以及分镜/镜头与数字间带空格的情况)
  13116. if (preg_match('/^(?:【)?(分镜|镜头)\s*(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  13117. $count++;
  13118. $is_capturing = true;
  13119. // 统一归一化为【分镜N】/【镜头N】(兼容“镜头 1”“【镜头 1】”等写法)
  13120. $trimmed_line = preg_replace('/^(?:【)?(分镜|镜头)\s*(\d+)(?:】)?/u', '【$1$2】', $trimmed_line);
  13121. if ($count > 1) {
  13122. $trimmed_line = "\n" . $trimmed_line;
  13123. }
  13124. }
  13125. if ($is_capturing && !empty($trimmed_line)) {
  13126. $cleaned_content .= $trimmed_line . "\n";
  13127. }
  13128. }
  13129. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  13130. return $cleaned_content;
  13131. }
  13132. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  13133. {
  13134. $episode_arr = [
  13135. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  13136. 'intro' => getProp($script_arr, 'intro'),
  13137. 'art_style' => getProp($script_arr, 'art_style'),
  13138. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  13139. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  13140. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  13141. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  13142. ];
  13143. if (empty($episode_arr['acts'])) {
  13144. $fallback_episode_arr = handleEpisodeContent($fullContent);
  13145. if (!empty($fallback_episode_arr['acts'])) {
  13146. $episode_arr = array_merge($fallback_episode_arr, [
  13147. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  13148. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  13149. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  13150. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  13151. ]);
  13152. }
  13153. }
  13154. // if (!getProp($episode_arr, 'episode_title')) {
  13155. // $episode_title = '';
  13156. // $episodes = getProp($script_arr, 'episodes', []);
  13157. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  13158. // $episode_title = '第1集:' . $episodes[0]['title'];
  13159. // }
  13160. // if (!$episode_title) {
  13161. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  13162. // }
  13163. // $episode_arr['episode_title'] = $episode_title;
  13164. // }
  13165. return $episode_arr;
  13166. }
  13167. private function saveEpisodeVersionData(
  13168. int $anime_id,
  13169. int $episode_number,
  13170. array $episode_arr,
  13171. array $existing_roles,
  13172. array $existing_scenes,
  13173. array $existing_props,
  13174. $current_episode,
  13175. $base_episode,
  13176. bool $is_regenerate_version,
  13177. string $content,
  13178. string $now,
  13179. array $ref_products = []
  13180. ): array {
  13181. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  13182. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  13183. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  13184. // 过滤掉关键字段为空的条目
  13185. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  13186. return !empty($item['role'] ?? null);
  13187. }));
  13188. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  13189. return !empty($item['scene'] ?? null);
  13190. }));
  13191. $merged_props = array_values(array_filter($generated_props, function ($item) {
  13192. return !empty($item['prop'] ?? null);
  13193. }));
  13194. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  13195. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  13196. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  13197. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  13198. $ace_mode = getProp($anime, 'ace_mode');
  13199. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  13200. $global_roles = json_decode(getProp($anime, 'roles'), true);
  13201. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  13202. $global_roles = is_array($global_roles) ? $global_roles : [];
  13203. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  13204. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  13205. $art_style_type = getProp($anime, 'art_style_type');
  13206. // 检查并创建 roles 的图片生成任务
  13207. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  13208. // 检查并创建 scenes 的图片生成任务
  13209. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  13210. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  13211. if ($arr && is_array($arr)) {
  13212. $merged_roles = $arr['roles'];
  13213. $merged_scenes = $arr['scenes'];
  13214. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  13215. }
  13216. // 确保数据是数组类型
  13217. if (!is_array($merged_roles)) {
  13218. dLog('deepseek')->error('merged_roles不是数组类型', [
  13219. 'type' => gettype($merged_roles),
  13220. 'value' => $merged_roles
  13221. ]);
  13222. $merged_roles = [];
  13223. }
  13224. if (!is_array($merged_scenes)) {
  13225. dLog('deepseek')->error('merged_scenes不是数组类型', [
  13226. 'type' => gettype($merged_scenes),
  13227. 'value' => $merged_scenes
  13228. ]);
  13229. $merged_scenes = [];
  13230. }
  13231. if (!is_array($merged_props)) {
  13232. dLog('deepseek')->error('merged_props不是数组类型', [
  13233. 'type' => gettype($merged_props),
  13234. 'value' => $merged_props
  13235. ]);
  13236. $merged_props = [];
  13237. }
  13238. // 同步新出现的主体和场景到全局
  13239. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  13240. $role_arr = [];
  13241. foreach ($merged_roles as $item) {
  13242. $role_arr[$item['role']] = $item;
  13243. }
  13244. $version_count = DB::table('mp_anime_episodes')
  13245. ->where('anime_id', $anime_id)
  13246. ->where('episode_number', $episode_number)
  13247. ->count('id');
  13248. $episode = [
  13249. 'anime_id' => $anime_id,
  13250. 'episode_number' => $episode_number,
  13251. 'title' => getProp($episode_arr, 'episode_title'),
  13252. 'content' => $content,
  13253. 'intro' => getProp($episode_arr, 'intro'),
  13254. 'art_style' => getProp($episode_arr, 'art_style'),
  13255. 'roles' => json_encode($merged_roles, 256),
  13256. 'scenes' => json_encode($merged_scenes, 256),
  13257. 'props' => json_encode($merged_props, 256),
  13258. 'generate_status' => '待执行',
  13259. 'generate_at' => $now,
  13260. 'is_default' => 1,
  13261. 'updated_at' => $now,
  13262. ];
  13263. $del_flag = false;
  13264. if ($is_regenerate_version) {
  13265. DB::table('mp_anime_episodes')
  13266. ->where('anime_id', $anime_id)
  13267. ->where('episode_number', $episode_number)
  13268. ->update(['is_default' => 0, 'updated_at' => $now]);
  13269. $episode['sequence'] = $version_count + 1;
  13270. $episode['created_at'] = $now;
  13271. $episode['cpid'] = Site::getCpid();
  13272. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  13273. if (!$episode_id) {
  13274. Utils::throwError('20003:创建剧集版本失败');
  13275. }
  13276. } else {
  13277. $target_episode = $current_episode ?: $base_episode;
  13278. if ($target_episode) {
  13279. $episode_id = getProp($target_episode, 'id');
  13280. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  13281. DB::table('mp_anime_episodes')
  13282. ->where('anime_id', $anime_id)
  13283. ->where('episode_number', $episode_number)
  13284. ->where('id', '<>', $episode_id)
  13285. ->update(['is_default' => 0, 'updated_at' => $now]);
  13286. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  13287. if ($boolen === false) {
  13288. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  13289. Utils::throwError('20003:分集内容保存失败');
  13290. }
  13291. $del_flag = true;
  13292. } else {
  13293. DB::table('mp_anime_episodes')
  13294. ->where('anime_id', $anime_id)
  13295. ->where('episode_number', $episode_number)
  13296. ->update(['is_default' => 0, 'updated_at' => $now]);
  13297. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  13298. $episode['created_at'] = $now;
  13299. $episode['cpid'] = Site::getCpid();
  13300. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  13301. if (!$episode_id) {
  13302. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  13303. Utils::throwError('20003:分集内容保存失败');
  13304. }
  13305. }
  13306. }
  13307. $segments = [];
  13308. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  13309. // 如果是第2集及以后,获取上一集的主体音色数据
  13310. $previous_roles_voice = [];
  13311. if ($episode_number >= 2) {
  13312. $previous_episode = DB::table('mp_anime_episodes')
  13313. ->where('anime_id', $anime_id)
  13314. ->where('episode_number', $episode_number - 1)
  13315. ->where('is_default', 1)
  13316. ->first();
  13317. if ($previous_episode) {
  13318. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  13319. if (is_array($previous_roles)) {
  13320. foreach ($previous_roles as $prev_role) {
  13321. $role_name = getProp($prev_role, 'role');
  13322. if ($role_name) {
  13323. $previous_roles_voice[$role_name] = [
  13324. 'voice_name' => getProp($prev_role, 'voice_name'),
  13325. 'voice_type' => getProp($prev_role, 'voice_type'),
  13326. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  13327. ];
  13328. $voice_prompt = getProp($prev_role, 'voice_prompt');
  13329. if ($voice_prompt) {
  13330. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  13331. }
  13332. }
  13333. }
  13334. }
  13335. }
  13336. }
  13337. // 将继承的音色数据同步到当前集的主体列表
  13338. if (!empty($previous_roles_voice)) {
  13339. foreach ($merged_roles as &$role) {
  13340. $role_name = getProp($role, 'role');
  13341. if ($role_name && isset($previous_roles_voice[$role_name])) {
  13342. // 强制继承上一集的音色数据
  13343. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  13344. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  13345. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  13346. // 如果上一集有 voice_prompt 则继承,否则跳过
  13347. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  13348. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  13349. }
  13350. }
  13351. }
  13352. unset($role); // 解除引用
  13353. // 更新 role_arr 以便后续使用
  13354. $role_arr = [];
  13355. foreach ($merged_roles as $item) {
  13356. $role_arr[$item['role']] = $item;
  13357. }
  13358. }
  13359. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  13360. $emotion_list = array_flip($emotion_list);
  13361. foreach ($acts as $act) {
  13362. $act_segments = getProp($act, 'segments', []);
  13363. if (!is_array($act_segments)) {
  13364. continue;
  13365. }
  13366. if ((int)$ace_mode === 1) {
  13367. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  13368. $merged_parts = [];
  13369. foreach ($act_segments as $seg) {
  13370. $seg_num = getProp($seg, 'segment_number');
  13371. $seg_content = getProp($seg, 'segment_content');
  13372. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  13373. }
  13374. $act_content = implode("\n", $merged_parts);
  13375. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  13376. $segments[] = [
  13377. 'anime_id' => $anime_id,
  13378. 'episode_id' => $episode_id,
  13379. 'episode_number' => $episode_number,
  13380. 'act_number' => getProp($act, 'act_number'),
  13381. 'act_title' => getProp($act, 'act_title'),
  13382. 'act_duration' => getProp($act, 'act_duration'),
  13383. 'act_content' => $act_content,
  13384. 'created_at' => $now,
  13385. 'updated_at' => $now
  13386. ];
  13387. } else {
  13388. foreach ($act_segments as $segment) {
  13389. $voice_actor = getProp($segment, 'voice_actor');
  13390. // 优先从上一集继承音色数据
  13391. $timbre_info = [];
  13392. if (isset($previous_roles_voice[$voice_actor])) {
  13393. // 从上一集继承音色数据
  13394. $timbre_info = $previous_roles_voice[$voice_actor];
  13395. } elseif (isset($role_arr[$voice_actor])) {
  13396. // 使用当前集的主体音色数据
  13397. $timbre_info = $role_arr[$voice_actor];
  13398. }
  13399. $voice_type = getProp($timbre_info, 'voice_type');
  13400. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  13401. if ($timbre_emotion) {
  13402. $timbre_emotion = explode(',', $timbre_emotion);
  13403. } else {
  13404. $timbre_emotion = [];
  13405. }
  13406. $emotion = getProp($segment, 'emotion', '中性');
  13407. if (!in_array($emotion, $timbre_emotion)) {
  13408. $emotion = '中性';
  13409. }
  13410. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  13411. $segments[] = [
  13412. 'anime_id' => $anime_id,
  13413. 'episode_id' => $episode_id,
  13414. 'episode_number' => $episode_number,
  13415. 'act_number' => getProp($act, 'act_number'),
  13416. 'act_title' => getProp($act, 'act_title'),
  13417. 'act_duration' => getProp($act, 'act_duration'),
  13418. 'segment_id' => getProp($segment, 'segment_id'),
  13419. 'segment_number' => getProp($segment, 'segment_number'),
  13420. 'segment_content' => getProp($segment, 'segment_content'),
  13421. 'description' => getProp($segment, 'description'),
  13422. 'composition' => getProp($segment, 'composition'),
  13423. 'camera_movement' => getProp($segment, 'camera_movement'),
  13424. 'voice_actor' => $voice_actor,
  13425. 'dialogue' => getProp($segment, 'dialogue'),
  13426. 'frame_type' => getProp($segment, 'frame_type'),
  13427. 'scene' => getProp($segment, 'scene'),
  13428. 'characters' => getProp($segment, 'characters'),
  13429. 'tail_frame' => getProp($segment, 'tail_frame'),
  13430. 'voice_name' => getProp($timbre_info, 'voice_name'),
  13431. 'voice_type' => $voice_type,
  13432. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  13433. 'emotion' => $emotion,
  13434. 'emotion_type' => $emotion_type,
  13435. 'gender' => getProp($segment, 'gender', '0'),
  13436. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  13437. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  13438. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  13439. 'pitch' => getProp($segment, 'pitch', 0),
  13440. 'created_at' => $now,
  13441. 'updated_at' => $now
  13442. ];
  13443. }
  13444. }
  13445. }
  13446. if ($segments) {
  13447. if ($del_flag) {
  13448. DB::table('mp_episode_segments')
  13449. ->where('anime_id', $anime_id)
  13450. ->where('episode_id', $episode_id)
  13451. ->delete();
  13452. }
  13453. $boolen = DB::table('mp_episode_segments')->insert($segments);
  13454. if (!$boolen) {
  13455. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  13456. Utils::throwError('20003:分镜内容保存失败');
  13457. }
  13458. }
  13459. dLog('deepseek')->info('segments', $segments);
  13460. // ace_mode=1: acts 返回值按合并格式调整
  13461. if ((int)$ace_mode === 1) {
  13462. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  13463. $act_map = [];
  13464. foreach ($table_act_data as $item) {
  13465. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  13466. }
  13467. $restructured_acts = [];
  13468. foreach ($acts as $act) {
  13469. $act_segments = getProp($act, 'segments', []);
  13470. if (!is_array($act_segments)) {
  13471. continue;
  13472. }
  13473. $merged_parts = [];
  13474. foreach ($act_segments as $seg) {
  13475. $seg_num = getProp($seg, 'segment_number');
  13476. $seg_content = getProp($seg, 'segment_content');
  13477. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  13478. }
  13479. $act_content = implode("\n", $merged_parts);
  13480. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  13481. $restructured_acts[] = [
  13482. 'anime_id' => $anime_id,
  13483. 'episode_id' => $episode_id,
  13484. 'episode_number' => $episode_number,
  13485. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  13486. 'act_number' => getProp($act, 'act_number'),
  13487. 'act_title' => getProp($act, 'act_title'),
  13488. 'act_duration' => getProp($act, 'act_duration'),
  13489. 'act_content' => $act_content,
  13490. 'created_at' => $now,
  13491. 'updated_at' => $now,
  13492. ];
  13493. }
  13494. $acts = $restructured_acts;
  13495. }
  13496. $episode['episode_id'] = $episode_id;
  13497. $episode['roles'] = $merged_roles;
  13498. $episode['scenes'] = $merged_scenes;
  13499. $episode['props'] = $merged_props;
  13500. $episode['acts'] = $acts;
  13501. return [
  13502. 'episode' => $episode,
  13503. 'episode_id' => $episode_id,
  13504. 'merged_roles' => $merged_roles,
  13505. 'merged_scenes' => $merged_scenes,
  13506. 'merged_props' => $merged_props,
  13507. ];
  13508. }
  13509. private function buildEpisodeItemContent(array $items, string $nameKey): string
  13510. {
  13511. $content = '';
  13512. foreach ($items as $item) {
  13513. $name = trim((string)getProp($item, $nameKey));
  13514. if ($name === '' || $name === '旁白') {
  13515. continue;
  13516. }
  13517. $description = trim((string)getProp($item, 'description'));
  13518. $content .= $name . ': ' . $description;
  13519. if ($nameKey == 'role') {
  13520. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  13521. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13522. $voice_name = trim(getProp($item, 'voice_name'));
  13523. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  13524. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  13525. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  13526. }else {
  13527. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  13528. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13529. }
  13530. $content .= "\n";
  13531. }
  13532. return trim($content);
  13533. }
  13534. private function getEpisodeChatContent($animeId, $sequence, $content) {
  13535. if ((int)$sequence <= 0) {
  13536. return [];
  13537. }
  13538. $origin_content = '';
  13539. if ($content) {
  13540. $origin_content = '本集剧情内容:'.$content;
  13541. }else {
  13542. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  13543. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  13544. }
  13545. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  13546. // 获取分集信息
  13547. $episode = DB::table('mp_anime_episodes')
  13548. ->where('anime_id', $animeId)
  13549. ->where('episode_number', $sequence)
  13550. ->where('is_default', 1)
  13551. ->first();
  13552. if (!$episode) {
  13553. return [];
  13554. }
  13555. $episode_id = getProp($episode, 'id');
  13556. $episode_number = getProp($episode, 'episode_number');
  13557. $title = getProp($episode, 'title');
  13558. $intro = getProp($episode, 'intro');
  13559. $art_style = getProp($episode, 'art_style');
  13560. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  13561. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  13562. // 组装纯文本内容
  13563. $content = '';
  13564. // 添加分集标题和梗概
  13565. $content .= "###第{$episode_number}集:{$title}\n\n";
  13566. $content .= "###故事梗概\n";
  13567. $content .= trim($intro) . "\n\n";
  13568. // 添加美术风格
  13569. $content .= "###美术风格\n";
  13570. $content .= trim($art_style) . "\n\n";
  13571. // 添加主体列表
  13572. $content .= "###主体列表\n";
  13573. $pangbai_voice_prompt = "";
  13574. foreach ($roles as $role) {
  13575. $name = getProp($role, 'role');
  13576. $description = getProp($role, 'description');
  13577. $pic_prompt = getProp($role, 'pic_prompt');
  13578. $voice_prompt = getProp($role, 'voice_prompt');
  13579. $voice_name = getProp($role, 'voice_name');
  13580. $content .= "{$name}: {$description}";
  13581. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13582. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  13583. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  13584. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  13585. $content .= "\n";
  13586. }
  13587. $content .= "\n";
  13588. // 添加场景列表
  13589. $content .= "###场景列表\n";
  13590. foreach ($scenes as $scene) {
  13591. $name = getProp($scene, 'scene');
  13592. $description = getProp($scene, 'description');
  13593. $pic_prompt = getProp($scene, 'pic_prompt');
  13594. $content .= "{$name}: {$description}";
  13595. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13596. $content .= "\n";
  13597. }
  13598. $content .= "\n";
  13599. // 获取分镜信息
  13600. $segments = DB::table('mp_episode_segments')
  13601. ->where('anime_id', $animeId)
  13602. ->where('episode_id', $episode_id)
  13603. ->orderBy('segment_number')
  13604. ->get();
  13605. if ($segments && count($segments) > 0) {
  13606. if ((int)$ace_mode === 1) {
  13607. $content .= "###分段剧本\n";
  13608. // 获取片段数量
  13609. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  13610. $content .= "片段数量:{$act_count}\n";
  13611. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  13612. $content .= "\n";
  13613. }else {
  13614. $content .= "###分镜剧本\n";
  13615. }
  13616. // 按幕分组
  13617. $currentAct = null;
  13618. foreach ($segments as $segment) {
  13619. $act_number = getProp($segment, 'act_number');
  13620. $act_title = getProp($segment, 'act_title');
  13621. $act_duration = getProp($segment, 'act_duration');
  13622. $segment_number = getProp($segment, 'segment_number');
  13623. $segment_content = getProp($segment, 'segment_content');
  13624. $scene_description = getProp($segment, 'scene_description');
  13625. $scene_name = getProp($segment, 'scene_name');
  13626. $composition = getProp($segment, 'composition');
  13627. $camera_movement = getProp($segment, 'camera_movement');
  13628. $voice_type = getProp($segment, 'voice_type');
  13629. $characters = getProp($segment, 'characters');
  13630. $dialogue = getProp($segment, 'dialogue');
  13631. $frame_type = getProp($segment, 'frame_type');
  13632. $tail_frame_description = getProp($segment, 'tail_frame_description');
  13633. // 判断是否是全能模式
  13634. if ((int)$ace_mode === 1) { // 全能模式
  13635. // 如果是新的分段,添加分段标题
  13636. if ($act_number !== $currentAct) {
  13637. $currentAct = $act_number;
  13638. $content .= "##{$act_title}\n";
  13639. $content .= "时长:{$act_duration}s\n";
  13640. }
  13641. }else {
  13642. // 如果是新的幕,添加幕标题
  13643. if ($act_number !== $currentAct) {
  13644. $currentAct = $act_number;
  13645. $content .= "##第{$act_number}幕:{$scene_name}\n";
  13646. }
  13647. }
  13648. // 添加分镜信息
  13649. $content .= "分镜{$segment_number}\n";
  13650. $content .= "分镜内容:\n{$segment_content}\n";
  13651. // $content .= "画面描述:{$scene_description}\n";
  13652. // $content .= "场景:{$scene_name}\n";
  13653. // $content .= "构图设计:{$composition}\n";
  13654. // $content .= "运镜调度:{$camera_movement}\n";
  13655. // if (!empty($voice_type)) {
  13656. // $content .= "配音角色:{$voice_type}\n";
  13657. // }
  13658. // if (!empty($characters)) {
  13659. // $content .= "出镜角色:{$characters}\n";
  13660. // }
  13661. // if (!empty($dialogue)) {
  13662. // $content .= "台词内容:\"{$dialogue}\"\n";
  13663. // }
  13664. // $content .= "画面类型:{$frame_type}\n";
  13665. // $content .= "尾帧描述:{$tail_frame_description}\n";
  13666. $content .= "\n";
  13667. }
  13668. }
  13669. $content = trim($content);
  13670. if($content) $content = "上集剧本内容:\n{$content}";
  13671. return [
  13672. [
  13673. 'role' => 'user',
  13674. 'content' => $origin_content
  13675. ],
  13676. [
  13677. 'role' => 'assistant',
  13678. 'content' => $content
  13679. ]
  13680. ];
  13681. }
  13682. private function getEpisodeChatMessages($animeId, $sequence): array
  13683. {
  13684. if ((int)$sequence <= 0) {
  13685. return [];
  13686. }
  13687. return DB::table('mp_anime_records')
  13688. ->where('anime_id', $animeId)
  13689. ->where('sequence', $sequence)
  13690. ->where('episode_id', '>', 0)
  13691. ->select('role', 'content')
  13692. ->orderBy('created_at')
  13693. ->orderBy('id')
  13694. ->get()
  13695. ->map(function ($value) {
  13696. return (array)$value;
  13697. })
  13698. ->toArray();
  13699. }
  13700. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  13701. {
  13702. $existingMap = [];
  13703. foreach ($existingItems as $item) {
  13704. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13705. if ($itemKey === '') {
  13706. continue;
  13707. }
  13708. $existingMap[$itemKey] = $item;
  13709. }
  13710. if (!$generatedItems) {
  13711. return array_values($existingItems);
  13712. }
  13713. $merged = [];
  13714. foreach ($generatedItems as $item) {
  13715. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13716. if ($itemKey === '') {
  13717. continue;
  13718. }
  13719. if (isset($existingMap[$itemKey])) {
  13720. if (trim((string)getProp($item, 'description')) === '') {
  13721. $merged[] = $existingMap[$itemKey];
  13722. continue;
  13723. }
  13724. // 检查内容是否发生变化
  13725. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  13726. if (!$isChanged) {
  13727. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  13728. $mergedItem = [
  13729. $nameKey => trim((string)getProp($item, $nameKey)),
  13730. 'description' => trim((string)getProp($item, 'description')),
  13731. ];
  13732. // 如果有 pic_prompt,添加到合并项中
  13733. $picPrompt = getProp($item, 'pic_prompt');
  13734. if (!empty($picPrompt)) {
  13735. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  13736. }
  13737. // 继承现有项的 URL
  13738. $existingUrl = getProp($existingMap[$itemKey], 'url');
  13739. if (!empty($existingUrl)) {
  13740. $mergedItem['url'] = $existingUrl;
  13741. }
  13742. // 继承现有项的 task_id
  13743. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  13744. if (!empty($existingTaskId)) {
  13745. $mergedItem['task_id'] = $existingTaskId;
  13746. }
  13747. // 继承现有项的 task_status
  13748. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  13749. if (!empty($existingTaskStatus)) {
  13750. $mergedItem['task_status'] = $existingTaskStatus;
  13751. }
  13752. // 保留生成项的音色字段
  13753. $voiceName = getProp($item, 'voice_name');
  13754. if (!empty($voiceName)) {
  13755. $mergedItem['voice_name'] = $voiceName;
  13756. }
  13757. $voiceType = getProp($item, 'voice_type');
  13758. if (!empty($voiceType)) {
  13759. $mergedItem['voice_type'] = $voiceType;
  13760. }
  13761. $audioUrl = getProp($item, 'voice_audio_url');
  13762. if (!empty($audioUrl)) {
  13763. $mergedItem['voice_audio_url'] = $audioUrl;
  13764. }
  13765. $merged[] = $mergedItem;
  13766. } else {
  13767. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  13768. $mergedItem = [
  13769. $nameKey => trim((string)getProp($item, $nameKey)),
  13770. 'description' => trim((string)getProp($item, 'description')),
  13771. ];
  13772. // 如果有 pic_prompt,添加到合并项中
  13773. $picPrompt = getProp($item, 'pic_prompt');
  13774. if (!empty($picPrompt)) {
  13775. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  13776. }
  13777. // 保留生成项的音色字段
  13778. $voiceName = getProp($item, 'voice_name');
  13779. if (!empty($voiceName)) {
  13780. $mergedItem['voice_name'] = $voiceName;
  13781. }
  13782. $voiceType = getProp($item, 'voice_type');
  13783. if (!empty($voiceType)) {
  13784. $mergedItem['voice_type'] = $voiceType;
  13785. }
  13786. $audioUrl = getProp($item, 'voice_audio_url');
  13787. if (!empty($audioUrl)) {
  13788. $mergedItem['voice_audio_url'] = $audioUrl;
  13789. }
  13790. // 不继承 URL、task_id 和 task_status(重置状态)
  13791. $merged[] = $mergedItem;
  13792. }
  13793. } else {
  13794. // 新增项,保留生成项的所有字段
  13795. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  13796. }
  13797. }
  13798. return $merged ?: array_values($existingItems);
  13799. }
  13800. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  13801. {
  13802. $resetItem = [
  13803. $nameKey => trim((string)getProp($item, $nameKey)),
  13804. 'description' => trim((string)getProp($item, 'description')),
  13805. ];
  13806. // 保留指定的字段
  13807. foreach ($preserveFields as $field) {
  13808. $value = getProp($item, $field);
  13809. if (!empty($value)) {
  13810. $resetItem[$field] = $value;
  13811. }
  13812. }
  13813. return $resetItem;
  13814. }
  13815. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  13816. {
  13817. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  13818. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  13819. if ($existingKey !== $generatedKey) {
  13820. return true;
  13821. }
  13822. // 比较 description 是否变化
  13823. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  13824. return true;
  13825. }
  13826. // 比较 pic_prompt 是否变化
  13827. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  13828. }
  13829. private function normalizeEpisodeResourceKey($value): string
  13830. {
  13831. $value = trim((string)$value);
  13832. if ($value === '') {
  13833. return '';
  13834. }
  13835. return strtolower((string)preg_replace('/\s+/u', '', $value));
  13836. }
  13837. // 生成全局角色图片
  13838. private function batchSetGlobalRoleImg($data, $is_force=false) {
  13839. $anime_id = getProp($data, 'anime_id');
  13840. if (!$anime_id) Utils::throwError('1002:请选择对话');
  13841. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  13842. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  13843. $art_style = getProp($anime, 'art_style');
  13844. $update_flag = false;
  13845. foreach ($roles as &$role) {
  13846. $role_name = getProp($role, 'role');
  13847. if ($role_name == '旁白') continue;
  13848. // 优先使用 pic_prompt,如果没有则使用 description
  13849. $pic_prompt = getProp($role, 'pic_prompt');
  13850. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  13851. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  13852. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  13853. // 参考图地址
  13854. $ref_img_url = getProp($role, 'url');
  13855. if (!$is_force && $ref_img_url) continue;
  13856. $update_flag = true;
  13857. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  13858. try {
  13859. $params = [
  13860. 'prompt' => $description,
  13861. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  13862. 'ref_img_urls' => [],
  13863. // 计费锚点(动漫/剧本),用于积分明细归属统计
  13864. 'anime_id' => $anime_id,
  13865. ];
  13866. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13867. $task_id = $task->id;
  13868. if (!$task_id) {
  13869. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  13870. }
  13871. $role['task_id'] = $task_id;
  13872. $role['task_status'] = 'processing';
  13873. } catch (\Exception $e) {
  13874. Utils::throwError("20003:" . $e->getMessage());
  13875. }
  13876. }
  13877. if (!$update_flag) return true;
  13878. // 保存角色信息
  13879. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  13880. 'roles' => json_encode($roles, 256),
  13881. 'generate_status' => '执行中',
  13882. 'generate_at' => date('Y-m-d H:i:s'),
  13883. 'updated_at' => date('Y-m-d H:i:s')
  13884. ]);
  13885. if (!$boolen) {
  13886. Utils::throwError('20003:保存角色信息失败');
  13887. }
  13888. return $boolen;
  13889. }
  13890. // 生成全局场景图片
  13891. private function batchSetGlobalSceneImg($data, $is_force=false) {
  13892. $anime_id = getProp($data, 'anime_id');
  13893. if (!$anime_id) Utils::throwError('1002:请选择对话');
  13894. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  13895. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  13896. $art_style = getProp($anime, 'art_style');
  13897. $update_flag = false;
  13898. foreach ($scenes as &$scene) {
  13899. $scene_name = getProp($scene, 'scene');
  13900. // 优先使用 pic_prompt,如果没有则使用 description
  13901. $pic_prompt = getProp($scene, 'pic_prompt');
  13902. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  13903. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  13904. // 参考图地址
  13905. $ref_img_url = getProp($scene, 'url');
  13906. if (!$is_force && $ref_img_url) continue;
  13907. $update_flag = true;
  13908. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  13909. try {
  13910. $params = [
  13911. 'prompt' => $description,
  13912. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  13913. 'ref_img_urls' => [],
  13914. // 计费锚点(动漫/剧本),用于积分明细归属统计
  13915. 'anime_id' => $anime_id,
  13916. ];
  13917. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13918. $task_id = $task->id;
  13919. if (!$task_id) {
  13920. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  13921. }
  13922. $scene['task_id'] = $task_id;
  13923. $scene['task_status'] = 'processing';
  13924. } catch (\Exception $e) {
  13925. Utils::throwError("20003:" . $e->getMessage());
  13926. }
  13927. }
  13928. if (!$update_flag) return true;
  13929. // 保存角色信息
  13930. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  13931. 'scenes' => json_encode($scenes, 256),
  13932. 'generate_status' => '执行中',
  13933. 'generate_at' => date('Y-m-d H:i:s'),
  13934. 'updated_at' => date('Y-m-d H:i:s')
  13935. ]);
  13936. if (!$boolen) {
  13937. Utils::throwError('20003:保存角色信息失败');
  13938. }
  13939. return $boolen;
  13940. }
  13941. // 生成分镜主体、场景和道具图片
  13942. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  13943. $character_prefix = '';
  13944. $scene_prefix = '';
  13945. $prop_prefix = '';
  13946. if ($art_style_type) {
  13947. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  13948. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  13949. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  13950. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  13951. }
  13952. $update_flag = false;
  13953. // 获取上一集的roles、scenes和props数据
  13954. $prev_roles = [];
  13955. $prev_scenes = [];
  13956. $prev_props = [];
  13957. if ($episode_number > 1) {
  13958. $prev_episode = DB::table('mp_anime_episodes')
  13959. ->where('anime_id', $anime_id)
  13960. ->where('episode_number', $episode_number - 1)
  13961. ->where('is_default', 1)
  13962. ->first();
  13963. if ($prev_episode) {
  13964. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  13965. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  13966. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  13967. dLog('deepseek')->info("获取上一集数据成功", [
  13968. 'anime_id' => $anime_id,
  13969. 'prev_episode_number' => $episode_number - 1,
  13970. 'prev_roles_count' => count($prev_roles),
  13971. 'prev_scenes_count' => count($prev_scenes),
  13972. 'prev_props_count' => count($prev_props)
  13973. ]);
  13974. }
  13975. }
  13976. // 处理角色图片生成
  13977. foreach ($roles as &$role) {
  13978. $role_name = getProp($role, 'role');
  13979. if ($role_name == '旁白') continue;
  13980. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  13981. if (isset($ref_products[$role_name])) {
  13982. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  13983. $role['three_view_image_url'] = isset($ref_products[$role_name]['three_view_image_url']) ? $ref_products[$role_name]['three_view_image_url'] : '';
  13984. if ($role['url']) continue;
  13985. }
  13986. $role_description = getProp($role, 'description');
  13987. $role_pic_prompt = getProp($role, 'pic_prompt');
  13988. $role_url = getProp($role, 'url');
  13989. // 检查是否可以从上一集继承
  13990. $inherited = false;
  13991. if (!$is_force && !empty($prev_roles)) {
  13992. foreach ($prev_roles as $prev_role) {
  13993. $prev_role_name = getProp($prev_role, 'role');
  13994. $prev_description = getProp($prev_role, 'description');
  13995. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  13996. $prev_url = getProp($prev_role, 'url');
  13997. $prev_task_id = getProp($prev_role, 'task_id');
  13998. $prev_task_status = getProp($prev_role, 'task_status');
  13999. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  14000. if ($role_name == $prev_role_name
  14001. && $role_description == $prev_description
  14002. && $role_pic_prompt == $prev_pic_prompt
  14003. && !empty($prev_url)) {
  14004. $role['task_id'] = $prev_task_id;
  14005. $role['task_status'] = $prev_task_status;
  14006. $role['url'] = $prev_url;
  14007. $inherited = true;
  14008. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  14009. 'anime_id' => $anime_id,
  14010. 'episode_number' => $episode_number,
  14011. 'task_id' => $prev_task_id,
  14012. 'url' => $prev_url
  14013. ]);
  14014. break;
  14015. }
  14016. }
  14017. }
  14018. // 如果已继承或已有url,跳过生成
  14019. if ($inherited || (!$is_force && $role_url)) {
  14020. continue;
  14021. }
  14022. // 优先使用 pic_prompt,如果没有则使用 description
  14023. $pic_prompt = getProp($role, 'pic_prompt');
  14024. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  14025. $description = buildStylePromptPrefix($character_prefix) . "主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  14026. $update_flag = true;
  14027. // 调用AIImageGenerationService的生成图片任务接口
  14028. try {
  14029. $params = [
  14030. 'prompt' => $description,
  14031. 'ref_img_urls' => [],
  14032. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  14033. 'anime_id' => $anime_id,
  14034. 'episode_number' => $episode_number,
  14035. ];
  14036. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  14037. $task_id = $task->id;
  14038. if (!$task_id) {
  14039. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  14040. continue; // 不中断,继续处理其他角色
  14041. }
  14042. $role['task_id'] = $task_id;
  14043. $role['task_status'] = 'processing';
  14044. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  14045. 'anime_id' => $anime_id,
  14046. 'episode_number' => $episode_number,
  14047. 'task_id' => $task_id
  14048. ]);
  14049. } catch (\Exception $e) {
  14050. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  14051. // 不抛出异常,继续处理其他角色
  14052. }
  14053. }
  14054. // 处理场景图片生成
  14055. foreach ($scenes as &$scene) {
  14056. $scene_name = getProp($scene, 'scene');
  14057. $scene_description = getProp($scene, 'description');
  14058. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  14059. $scene_url = getProp($scene, 'url');
  14060. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  14061. if (isset($ref_products[$scene_name])) {
  14062. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  14063. $scene['three_view_image_url'] = isset($ref_products[$scene_name]['three_view_image_url']) ? $ref_products[$scene_name]['three_view_image_url'] : '';
  14064. if ($scene['url']) continue;
  14065. }
  14066. // 检查是否可以从上一集继承
  14067. $inherited = false;
  14068. if (!$is_force && !empty($prev_scenes)) {
  14069. foreach ($prev_scenes as $prev_scene) {
  14070. $prev_scene_name = getProp($prev_scene, 'scene');
  14071. $prev_description = getProp($prev_scene, 'description');
  14072. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  14073. $prev_url = getProp($prev_scene, 'url');
  14074. $prev_task_id = getProp($prev_scene, 'task_id');
  14075. $prev_task_status = getProp($prev_scene, 'task_status');
  14076. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  14077. if ($scene_name == $prev_scene_name
  14078. && $scene_description == $prev_description
  14079. && $scene_pic_prompt == $prev_pic_prompt
  14080. && !empty($prev_url)) {
  14081. $scene['task_id'] = $prev_task_id;
  14082. $scene['task_status'] = $prev_task_status;
  14083. $scene['url'] = $prev_url;
  14084. $inherited = true;
  14085. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  14086. 'anime_id' => $anime_id,
  14087. 'episode_number' => $episode_number,
  14088. 'task_id' => $prev_task_id,
  14089. 'url' => $prev_url
  14090. ]);
  14091. break;
  14092. }
  14093. }
  14094. }
  14095. // 如果已继承或已有url,跳过生成
  14096. if ($inherited || (!$is_force && $scene_url)) {
  14097. continue;
  14098. }
  14099. // 优先使用 pic_prompt,如果没有则使用 description
  14100. $pic_prompt = getProp($scene, 'pic_prompt');
  14101. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  14102. $description = buildStylePromptPrefix($scene_prefix) . "场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  14103. $update_flag = true;
  14104. // 调用AIImageGenerationService的生成图片任务接口
  14105. try {
  14106. $params = [
  14107. 'prompt' => $description,
  14108. 'ref_img_urls' => [],
  14109. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  14110. 'anime_id' => $anime_id,
  14111. 'episode_number' => $episode_number,
  14112. ];
  14113. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  14114. $task_id = $task->id;
  14115. if (!$task_id) {
  14116. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  14117. continue; // 不中断,继续处理其他场景
  14118. }
  14119. $scene['task_id'] = $task_id;
  14120. $scene['task_status'] = 'processing';
  14121. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  14122. 'anime_id' => $anime_id,
  14123. 'episode_number' => $episode_number,
  14124. 'task_id' => $task_id
  14125. ]);
  14126. } catch (\Exception $e) {
  14127. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  14128. // 不抛出异常,继续处理其他场景
  14129. }
  14130. }
  14131. // 处理道具图片生成(逻辑与场景一致)
  14132. foreach ($props as &$prop) {
  14133. $prop_name = getProp($prop, 'prop');
  14134. $prop_description = getProp($prop, 'description');
  14135. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  14136. $prop_url = getProp($prop, 'url');
  14137. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  14138. if (isset($ref_products[$prop_name])) {
  14139. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  14140. $prop['three_view_image_url'] = isset($ref_products[$prop_name]['three_view_image_url']) ? $ref_products[$prop_name]['three_view_image_url'] : '';
  14141. if ($prop['url']) continue;
  14142. }
  14143. // 检查是否可以从上一集继承
  14144. $inherited = false;
  14145. if (!$is_force && !empty($prev_props)) {
  14146. foreach ($prev_props as $prev_prop) {
  14147. $prev_prop_name = getProp($prev_prop, 'prop');
  14148. $prev_description = getProp($prev_prop, 'description');
  14149. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  14150. $prev_url = getProp($prev_prop, 'url');
  14151. $prev_task_id = getProp($prev_prop, 'task_id');
  14152. $prev_task_status = getProp($prev_prop, 'task_status');
  14153. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  14154. if ($prop_name == $prev_prop_name
  14155. && $prop_description == $prev_description
  14156. && $prop_pic_prompt == $prev_pic_prompt
  14157. && !empty($prev_url)) {
  14158. $prop['task_id'] = $prev_task_id;
  14159. $prop['task_status'] = $prev_task_status;
  14160. $prop['url'] = $prev_url;
  14161. $inherited = true;
  14162. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  14163. 'anime_id' => $anime_id,
  14164. 'episode_number' => $episode_number,
  14165. 'task_id' => $prev_task_id,
  14166. 'url' => $prev_url
  14167. ]);
  14168. break;
  14169. }
  14170. }
  14171. }
  14172. // 如果已继承或已有url,跳过生成
  14173. if ($inherited || (!$is_force && $prop_url)) {
  14174. continue;
  14175. }
  14176. // 优先使用 pic_prompt,如果没有则使用 description
  14177. $pic_prompt = getProp($prop, 'pic_prompt');
  14178. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  14179. $description = buildStylePromptPrefix($prop_prefix) . "道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  14180. $update_flag = true;
  14181. // 调用AIImageGenerationService的生成图片任务接口
  14182. try {
  14183. $params = [
  14184. 'prompt' => $description,
  14185. 'ref_img_urls' => [],
  14186. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  14187. 'anime_id' => $anime_id,
  14188. 'episode_number' => $episode_number,
  14189. ];
  14190. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  14191. $task_id = $task->id;
  14192. if (!$task_id) {
  14193. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  14194. continue; // 不中断,继续处理其他道具
  14195. }
  14196. $prop['task_id'] = $task_id;
  14197. $prop['task_status'] = 'processing';
  14198. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  14199. 'anime_id' => $anime_id,
  14200. 'episode_number' => $episode_number,
  14201. 'task_id' => $task_id
  14202. ]);
  14203. } catch (\Exception $e) {
  14204. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  14205. // 不抛出异常,继续处理其他道具
  14206. }
  14207. }
  14208. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  14209. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  14210. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  14211. // // 保存剧集的角色和场景信息
  14212. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  14213. // 'roles' => json_encode($roles, 256),
  14214. // 'scenes' => json_encode($scenes, 256),
  14215. // 'generate_status' => '执行中',
  14216. // 'generate_at' => date('Y-m-d H:i:s'),
  14217. // 'updated_at' => date('Y-m-d H:i:s')
  14218. // ]);
  14219. // if (!$boolen) {
  14220. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  14221. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  14222. // }
  14223. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  14224. // 'episode_id' => $episode_id,
  14225. 'roles_count' => count($roles),
  14226. 'scenes_count' => count($scenes),
  14227. 'props_count' => count($props)
  14228. ]);
  14229. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  14230. }
  14231. /**
  14232. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  14233. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  14234. *
  14235. * @param int $anime_id 动漫对话ID
  14236. * @param array $episode_roles 剧集角色数据
  14237. * @param array $episode_scenes 剧集场景数据
  14238. * @param array $episode_props 剧集道具数据
  14239. * @return bool
  14240. */
  14241. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  14242. // 获取全局数据
  14243. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  14244. if (!$anime) {
  14245. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  14246. return false;
  14247. }
  14248. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  14249. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  14250. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  14251. $roles_added = false;
  14252. $roles_updated = false;
  14253. $scenes_added = false;
  14254. $props_added = false;
  14255. // 处理角色同步
  14256. foreach ($episode_roles as $episode_role) {
  14257. $episode_role_name = getProp($episode_role, 'role');
  14258. $episode_description = getProp($episode_role, 'description');
  14259. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  14260. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  14261. // 跳过旁白
  14262. if ($episode_role_name == '旁白') {
  14263. continue;
  14264. }
  14265. // 检查全局中是否已存在相同的角色
  14266. $exists = false;
  14267. $global_role_index = -1;
  14268. foreach ($global_roles as $index => $global_role) {
  14269. $global_role_name = getProp($global_role, 'role');
  14270. $global_description = getProp($global_role, 'description');
  14271. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  14272. // 如果role、description、pic_prompt三项都一致,则认为已存在
  14273. if ($episode_role_name == $global_role_name
  14274. && $episode_description == $global_description
  14275. && $episode_pic_prompt == $global_pic_prompt) {
  14276. $exists = true;
  14277. $global_role_index = $index;
  14278. break;
  14279. }
  14280. }
  14281. // 如果不存在,则添加到全局
  14282. if (!$exists) {
  14283. $global_roles[] = $episode_role;
  14284. $roles_added = true;
  14285. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  14286. 'anime_id' => $anime_id,
  14287. 'role' => $episode_role_name
  14288. ]);
  14289. } else {
  14290. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  14291. if (!empty($episode_voice_prompt)) {
  14292. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  14293. // 如果全局没有voice_prompt或与剧集不一致,则更新
  14294. if ($global_voice_prompt !== $episode_voice_prompt) {
  14295. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  14296. $roles_updated = true;
  14297. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  14298. 'anime_id' => $anime_id,
  14299. 'role' => $episode_role_name,
  14300. 'voice_prompt' => $episode_voice_prompt
  14301. ]);
  14302. }
  14303. }
  14304. }
  14305. }
  14306. // 处理场景同步
  14307. foreach ($episode_scenes as $episode_scene) {
  14308. $episode_scene_name = getProp($episode_scene, 'scene');
  14309. $episode_description = getProp($episode_scene, 'description');
  14310. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  14311. // 检查全局中是否已存在相同的场景
  14312. $exists = false;
  14313. foreach ($global_scenes as $global_scene) {
  14314. $global_scene_name = getProp($global_scene, 'scene');
  14315. $global_description = getProp($global_scene, 'description');
  14316. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  14317. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  14318. if ($episode_scene_name == $global_scene_name
  14319. && $episode_description == $global_description
  14320. && $episode_pic_prompt == $global_pic_prompt) {
  14321. $exists = true;
  14322. break;
  14323. }
  14324. }
  14325. // 如果不存在,则添加到全局
  14326. if (!$exists) {
  14327. $global_scenes[] = $episode_scene;
  14328. $scenes_added = true;
  14329. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  14330. 'anime_id' => $anime_id,
  14331. 'scene' => $episode_scene_name
  14332. ]);
  14333. }
  14334. }
  14335. // 处理道具同步(逻辑与场景一致)
  14336. foreach ($episode_props as $episode_prop) {
  14337. $episode_prop_name = getProp($episode_prop, 'prop');
  14338. $episode_description = getProp($episode_prop, 'description');
  14339. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  14340. // 检查全局中是否已存在相同的道具
  14341. $exists = false;
  14342. foreach ($global_props as $global_prop) {
  14343. $global_prop_name = getProp($global_prop, 'prop');
  14344. $global_description = getProp($global_prop, 'description');
  14345. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  14346. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  14347. if ($episode_prop_name == $global_prop_name
  14348. && $episode_description == $global_description
  14349. && $episode_pic_prompt == $global_pic_prompt) {
  14350. $exists = true;
  14351. break;
  14352. }
  14353. }
  14354. // 如果不存在,则添加到全局
  14355. if (!$exists) {
  14356. $global_props[] = $episode_prop;
  14357. $props_added = true;
  14358. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  14359. 'anime_id' => $anime_id,
  14360. 'prop' => $episode_prop_name
  14361. ]);
  14362. }
  14363. }
  14364. // 如果有新增或更新,则更新全局数据
  14365. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  14366. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  14367. if ($roles_added || $roles_updated) {
  14368. $update_data['roles'] = json_encode($global_roles, 256);
  14369. }
  14370. if ($scenes_added) {
  14371. $update_data['scenes'] = json_encode($global_scenes, 256);
  14372. }
  14373. if ($props_added) {
  14374. $update_data['props'] = json_encode($global_props, 256);
  14375. }
  14376. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  14377. dLog('deepseek')->info('剧集数据同步到全局完成', [
  14378. 'anime_id' => $anime_id,
  14379. 'roles_added' => $roles_added,
  14380. 'roles_updated' => $roles_updated,
  14381. 'scenes_added' => $scenes_added,
  14382. 'props_added' => $props_added,
  14383. 'global_roles_count' => count($global_roles),
  14384. 'global_scenes_count' => count($global_scenes),
  14385. 'global_props_count' => count($global_props)
  14386. ]);
  14387. }
  14388. return true;
  14389. }
  14390. /**
  14391. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  14392. *
  14393. * @param int $anime_id 动漫对话ID
  14394. * @param int $episode_id 分集ID
  14395. * @return bool
  14396. */
  14397. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  14398. // 获取全局角色和场景数据
  14399. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  14400. if (!$anime) {
  14401. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  14402. return false;
  14403. }
  14404. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  14405. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  14406. // 获取指定的分集
  14407. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  14408. if (!$episode) {
  14409. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  14410. return false;
  14411. }
  14412. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  14413. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  14414. $roles_updated = false;
  14415. $scenes_updated = false;
  14416. // 继承角色的task_id、task_status和url
  14417. foreach ($episode_roles as &$episode_role) {
  14418. $episode_role_name = getProp($episode_role, 'role');
  14419. $episode_description = getProp($episode_role, 'description');
  14420. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  14421. $episode_url = getProp($episode_role, 'url');
  14422. // 跳过旁白角色
  14423. if ($episode_role_name == '旁白') {
  14424. continue;
  14425. }
  14426. // 如果剧集中已有URL,跳过
  14427. if (!empty($episode_url)) {
  14428. continue;
  14429. }
  14430. // 遍历全局角色数据,查找匹配的角色
  14431. foreach ($global_roles as $global_role) {
  14432. $global_role_name = getProp($global_role, 'role');
  14433. $global_description = getProp($global_role, 'description');
  14434. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  14435. $global_url = getProp($global_role, 'url');
  14436. $global_task_id = getProp($global_role, 'task_id');
  14437. $global_task_status = getProp($global_role, 'task_status');
  14438. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  14439. if ($episode_role_name == $global_role_name
  14440. && $episode_description == $global_description
  14441. && $episode_pic_prompt == $global_pic_prompt) {
  14442. // 继承 task_id、task_status 和 url
  14443. if (!empty($global_task_id)) {
  14444. $episode_role['task_id'] = $global_task_id;
  14445. $episode_role['task_status'] = $global_task_status;
  14446. $roles_updated = true;
  14447. dLog('deepseek')->info('剧集角色继承全局task_id', [
  14448. 'episode_id' => $episode_id,
  14449. 'role' => $episode_role_name,
  14450. 'task_id' => $global_task_id,
  14451. 'task_status' => $global_task_status
  14452. ]);
  14453. }
  14454. if (!empty($global_url)) {
  14455. $episode_role['url'] = $global_url;
  14456. $roles_updated = true;
  14457. dLog('deepseek')->info('剧集角色继承全局url', [
  14458. 'episode_id' => $episode_id,
  14459. 'role' => $episode_role_name,
  14460. 'url' => $global_url
  14461. ]);
  14462. }
  14463. break;
  14464. }
  14465. }
  14466. }
  14467. // 继承场景的task_id、task_status和url
  14468. foreach ($episode_scenes as &$episode_scene) {
  14469. $episode_scene_name = getProp($episode_scene, 'scene');
  14470. $episode_description = getProp($episode_scene, 'description');
  14471. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  14472. $episode_url = getProp($episode_scene, 'url');
  14473. // 如果剧集中已有URL,跳过
  14474. if (!empty($episode_url)) {
  14475. continue;
  14476. }
  14477. // 遍历全局场景数据,查找匹配的场景
  14478. foreach ($global_scenes as $global_scene) {
  14479. $global_scene_name = getProp($global_scene, 'scene');
  14480. $global_description = getProp($global_scene, 'description');
  14481. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  14482. $global_url = getProp($global_scene, 'url');
  14483. $global_task_id = getProp($global_scene, 'task_id');
  14484. $global_task_status = getProp($global_scene, 'task_status');
  14485. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  14486. if ($episode_scene_name == $global_scene_name
  14487. && $episode_description == $global_description
  14488. && $episode_pic_prompt == $global_pic_prompt) {
  14489. // 继承 task_id、task_status 和 url
  14490. if (!empty($global_task_id)) {
  14491. $episode_scene['task_id'] = $global_task_id;
  14492. $episode_scene['task_status'] = $global_task_status;
  14493. $scenes_updated = true;
  14494. dLog('deepseek')->info('剧集场景继承全局task_id', [
  14495. 'episode_id' => $episode_id,
  14496. 'scene' => $episode_scene_name,
  14497. 'task_id' => $global_task_id,
  14498. 'task_status' => $global_task_status
  14499. ]);
  14500. }
  14501. if (!empty($global_url)) {
  14502. $episode_scene['url'] = $global_url;
  14503. $scenes_updated = true;
  14504. dLog('deepseek')->info('剧集场景继承全局url', [
  14505. 'episode_id' => $episode_id,
  14506. 'scene' => $episode_scene_name,
  14507. 'url' => $global_url
  14508. ]);
  14509. }
  14510. break;
  14511. }
  14512. }
  14513. }
  14514. // 如果有更新,则保存到数据库
  14515. if ($roles_updated || $scenes_updated) {
  14516. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  14517. if ($roles_updated) {
  14518. $update_data['roles'] = json_encode($episode_roles, 256);
  14519. }
  14520. if ($scenes_updated) {
  14521. $update_data['scenes'] = json_encode($episode_scenes, 256);
  14522. }
  14523. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  14524. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  14525. 'episode_id' => $episode_id,
  14526. 'roles_updated' => $roles_updated,
  14527. 'scenes_updated' => $scenes_updated
  14528. ]);
  14529. }
  14530. return true;
  14531. }
  14532. public function chatChangeImg($data) {
  14533. // 文生文计费预检(normal 档)
  14534. $uid = Site::getUid();
  14535. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'normal'), $uid);
  14536. $segment = getProp($data, 'segment');
  14537. $segment_content = getProp($segment, 'segment_content');
  14538. $prompt = getProp($data, 'prompt');
  14539. $ref_img = getProp($data, 'ref_img');
  14540. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  14541. // 处理文本模型
  14542. $model = getProp($data, 'model');
  14543. if (!$model) {
  14544. // 用户没有输入,从anime表获取
  14545. $segment_id = getProp($segment, 'segment_id');
  14546. if ($segment_id) {
  14547. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  14548. if ($episode_id) {
  14549. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  14550. if ($anime_id) {
  14551. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  14552. }
  14553. }
  14554. }
  14555. if (!$model) {
  14556. // anime表也没有,使用默认值
  14557. $model = 'doubao-seed-2-0-mini-260215';
  14558. }
  14559. }
  14560. // 验证模型是否在可用模型表中
  14561. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  14562. $model = 'doubao-seed-2-0-mini-260215';
  14563. }
  14564. $messages[] =
  14565. [
  14566. 'role' => 'user',
  14567. 'content' => $question
  14568. ];
  14569. $post_data = [
  14570. 'model' => $model,
  14571. 'messages' => $messages,
  14572. // 'max_tokens' => 8192,
  14573. 'temperature' => 0.7,
  14574. 'frequency_penalty' => 0,
  14575. 'presence_penalty' => 0,
  14576. 'response_format' => ['type' => 'text'],
  14577. 'stream' => false // 是否启用流式输出
  14578. ];
  14579. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  14580. if (is_array($chatResult)) {
  14581. extract($chatResult);
  14582. }else {
  14583. Utils::throwError('20003: 接口调用失败!');
  14584. }
  14585. // 文生文成功计费(normal 档):同时记录积分与 token 明细
  14586. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  14587. 'model' => $model,
  14588. 'source' => 'chatChangeImg',
  14589. ], 'normal');
  14590. return [
  14591. 'type' => 'done',
  14592. // 'episode' => $episode,
  14593. 'answer' => $fullContent,
  14594. 'reasoning' => $fullReasoningContent,
  14595. 'usage' => $usage
  14596. ];
  14597. }
  14598. /**
  14599. * 仅调用 deepseek 对话接口(非流式)
  14600. *
  14601. * @param array $post_data
  14602. * @param int $timeout
  14603. * @return array
  14604. */
  14605. private function chatOnly($post_data, $timeout = 1800) {
  14606. $post_data['max_tokens'] = 300000;
  14607. $client = new Client(['timeout' => $timeout, 'verify' => false]);
  14608. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  14609. $response = $result->getBody()->getContents();
  14610. $response_arr = json_decode($response, true);
  14611. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  14612. $fullContent = '';
  14613. $fullReasoningContent = [];
  14614. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  14615. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  14616. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  14617. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  14618. }
  14619. return [
  14620. 'fullContent' => $fullContent,
  14621. 'fullReasoningContent' => $fullReasoningContent,
  14622. 'usage' => $usage
  14623. ];
  14624. }
  14625. /**
  14626. * 用 deepseek-v4-flash 非流式分析报错,返回不超过50字的用户友好提示
  14627. *
  14628. * @param string $errorMessage
  14629. * @return string|null
  14630. */
  14631. public function analyzeErrorMessage($errorMessage)
  14632. {
  14633. try {
  14634. $post_data = [
  14635. 'model' => 'deepseek-v4-flash',
  14636. 'messages' => [
  14637. [
  14638. 'role' => 'system',
  14639. 'content' => '你是视频生成任务的报错分析助手。请根据用户给出的原始报错,用一句中文提示告诉用户问题原因和下一步怎么做,不超过50个字,直接输出提示内容,不要解释、不要输出代码。',
  14640. ],
  14641. [
  14642. 'role' => 'user',
  14643. 'content' => (string)$errorMessage,
  14644. ],
  14645. ],
  14646. 'temperature' => 0.3,
  14647. 'frequency_penalty' => 0,
  14648. 'presence_penalty' => 0,
  14649. 'response_format' => ['type' => 'text'],
  14650. 'stream' => false,
  14651. ];
  14652. $result = $this->chatOnly($post_data, 8);
  14653. // 调用成功即记录 token 使用明细(不扣积分),保证错误分析这类隐性 AI 调用进入统计口径
  14654. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  14655. 'model' => 'deepseek-v4-flash',
  14656. 'source' => 'analyzeErrorMessage',
  14657. ], 'deepseek-v4-flash');
  14658. $content = trim((string)($result['fullContent'] ?? ''));
  14659. if ($content === '') {
  14660. return null;
  14661. }
  14662. return mb_substr($content, 0, 50);
  14663. } catch (\Exception $e) {
  14664. dLog('deepseek')->error('视频任务报错分析失败: ' . $e->getMessage(), [
  14665. 'error_message' => $errorMessage
  14666. ]);
  14667. return null;
  14668. }
  14669. }
  14670. // 仅调用 GPT-5.4 对话接口(非流式)
  14671. private function gpt54ChatOnly($post_data) {
  14672. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  14673. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  14674. // gpt-5.4 中转已下线,强制映射到 gpt-5.6-sol
  14675. if ($modelName === 'gpt-5.4') {
  14676. $modelName = 'gpt-5.6-terra';
  14677. $post_data['model'] = $modelName;
  14678. }
  14679. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  14680. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  14681. $usedLunaFallback = false;
  14682. if (empty($apiKey)) {
  14683. Utils::throwError('20003:GPT-5.4 API Key未配置');
  14684. }
  14685. // 先探活,服务不可用时自动重试
  14686. $this->ensureGptServiceAvailable($apiKey);
  14687. $client = new Client(['timeout' => 1800, 'verify' => false]);
  14688. // 移除 thinking 参数,GPT-5.4 不支持
  14689. if (isset($post_data['thinking'])) {
  14690. unset($post_data['thinking']);
  14691. }
  14692. if (isset($post_data['reasoning_effort'])) {
  14693. unset($post_data['reasoning_effort']);
  14694. }
  14695. // GPT-5.x(推理型上游)只接受默认 temperature(1),传入其他值会返回 400:
  14696. // Unsupported value: 'temperature' does not support 1.35 with this model.
  14697. // Only the default (1) value is supported.
  14698. unset($post_data['temperature']);
  14699. $post_data['max_completion_tokens'] = 100000;
  14700. // GPT-5.x 上游不支持 max_tokens,与 gpt54StreamResponse 保持一致,显式移除避免 400。
  14701. unset($post_data['max_tokens']);
  14702. // GPT-5.x 上游不接受 frequency_penalty / presence_penalty,移除默认值 0 不影响行为。
  14703. unset($post_data['frequency_penalty'], $post_data['presence_penalty']);
  14704. // 确保 stream 为 false
  14705. $post_data['stream'] = false;
  14706. $maxRetries = $this->gptRetryTimes();
  14707. $interval = $this->gptRetryInterval();
  14708. $attempt = 0;
  14709. while (true) {
  14710. try {
  14711. $headers = [
  14712. 'Authorization' => 'Bearer ' . $apiKey,
  14713. 'Content-Type' => 'application/json'
  14714. ];
  14715. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  14716. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  14717. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  14718. 'json' => $post_data,
  14719. 'headers' => $headers
  14720. ]);
  14721. $response = $result->getBody()->getContents();
  14722. $response_arr = json_decode($response, true);
  14723. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  14724. $fullContent = '';
  14725. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  14726. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  14727. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  14728. }
  14729. return [
  14730. 'fullContent' => $fullContent,
  14731. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  14732. 'usage' => $usage
  14733. ];
  14734. } catch (\Exception $e) {
  14735. // 提前解析上游错误详情,便于日志中记录真实原因(如 content_filter)
  14736. $upstream_error = $this->resolveGptUpstreamError($e);
  14737. // 报错或超时时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  14738. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  14739. $usedLunaFallback = true;
  14740. $apiKey = $lunaApiKey;
  14741. dLog('deepseek')->warning('GPT-5.4 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  14742. continue;
  14743. }
  14744. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  14745. $error_context = ['error' => $e->getMessage()];
  14746. if ($upstream_error['status'] || $upstream_error['body'] !== '') {
  14747. $error_context['upstream_status'] = $upstream_error['status'];
  14748. $error_context['upstream_code'] = $upstream_error['code'];
  14749. $error_context['upstream_body'] = $upstream_error['body'];
  14750. }
  14751. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage(), $error_context);
  14752. logDB('deepseek', 'error', 'GPT-5.4 请求失败', $error_context);
  14753. throw $e;
  14754. }
  14755. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  14756. 'retry' => $attempt + 1,
  14757. 'max_retries' => $maxRetries,
  14758. 'error' => $e->getMessage()
  14759. ]);
  14760. sleep($interval);
  14761. $attempt++;
  14762. }
  14763. }
  14764. }
  14765. public function getContentByBid($bid) {
  14766. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  14767. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  14768. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  14769. $content = '';
  14770. foreach ($chapters as $chapter) {
  14771. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  14772. }
  14773. return $content;
  14774. }
  14775. public function getContentByScriptId($script_id) {
  14776. $content = '';
  14777. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  14778. if ($contents) {
  14779. $content = implode(PHP_EOL, $contents);
  14780. }else {
  14781. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  14782. }
  14783. return $content;
  14784. }
  14785. /**
  14786. * 根据文件类型提取文本内容
  14787. *
  14788. * @param mixed $file 文件对象或文件路径
  14789. * @return string
  14790. */
  14791. public function extractFileContent($file) {
  14792. // 获取文件路径和扩展名
  14793. if (is_string($file)) {
  14794. $filePath = $file;
  14795. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  14796. } else {
  14797. // Laravel UploadedFile 对象
  14798. $filePath = $file->getRealPath();
  14799. $extension = strtolower($file->getClientOriginalExtension());
  14800. }
  14801. $content = '';
  14802. switch ($extension) {
  14803. case 'txt':
  14804. $content = $this->extractTxtContent($filePath);
  14805. break;
  14806. case 'pdf':
  14807. $content = $this->extractPdfContent($filePath);
  14808. break;
  14809. case 'doc':
  14810. case 'docx':
  14811. $content = $this->extractWordContent($filePath);
  14812. break;
  14813. // case 'jpg':
  14814. // case 'jpeg':
  14815. // case 'png':
  14816. // case 'gif':
  14817. // case 'bmp':
  14818. // case 'webp':
  14819. // $content = $this->extractImageContent($filePath);
  14820. // break;
  14821. default:
  14822. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  14823. }
  14824. // 移除非法 UTF-8 字节,避免后续 JSON 编码或正则解析异常
  14825. if (!mb_check_encoding($content, 'UTF-8')) {
  14826. $cleaned = @iconv('UTF-8', 'UTF-8//IGNORE', $content);
  14827. $content = $cleaned === false ? $content : $cleaned;
  14828. }
  14829. return $content;
  14830. }
  14831. /**
  14832. * 提取 TXT 文件内容
  14833. */
  14834. private function extractTxtContent($filePath) {
  14835. if (!file_exists($filePath)) {
  14836. Utils::throwError('20003:文件不存在');
  14837. }
  14838. $content = file_get_contents($filePath);
  14839. // 尝试检测并转换编码
  14840. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  14841. if ($encoding && $encoding !== 'UTF-8') {
  14842. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  14843. }
  14844. return trim($content);
  14845. }
  14846. /**
  14847. * 提取 PDF 文件内容
  14848. */
  14849. private function extractPdfContent($filePath) {
  14850. if (!file_exists($filePath)) {
  14851. Utils::throwError('20003:文件不存在');
  14852. }
  14853. try {
  14854. $parser = new PdfParser();
  14855. $pdf = $parser->parseFile($filePath);
  14856. $content = $pdf->getText();
  14857. return trim($content);
  14858. } catch (\Exception $e) {
  14859. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  14860. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  14861. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  14862. }
  14863. }
  14864. /**
  14865. * 提取 Word 文件内容(支持 doc 和 docx)
  14866. */
  14867. private function extractWordContent($filePath) {
  14868. if (!file_exists($filePath)) {
  14869. Utils::throwError('20003:文件不存在');
  14870. }
  14871. try {
  14872. $phpWord = WordIOFactory::load($filePath);
  14873. $content = '';
  14874. foreach ($phpWord->getSections() as $section) {
  14875. foreach ($section->getElements() as $element) {
  14876. $content .= $this->extractWordElementText($element);
  14877. // 段落边界补换行(段落内的软换行已在元素递归中处理)
  14878. $content .= "\n";
  14879. }
  14880. }
  14881. return trim($content);
  14882. } catch (\Exception $e) {
  14883. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  14884. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  14885. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  14886. }
  14887. }
  14888. /**
  14889. * 递归提取 Word 元素中的文本
  14890. */
  14891. private function extractWordElementText($element) {
  14892. $text = '';
  14893. if ($element instanceof \PhpOffice\PhpWord\Element\TextBreak
  14894. || $element instanceof \PhpOffice\PhpWord\Element\LineBreak) {
  14895. // 软换行:保留 Word 中的换行显示,避免"第X集"标题与正文粘连
  14896. $text .= "\n";
  14897. } elseif (method_exists($element, 'getElements')) {
  14898. foreach ($element->getElements() as $childElement) {
  14899. $text .= $this->extractWordElementText($childElement);
  14900. }
  14901. } elseif (method_exists($element, 'getText')) {
  14902. $text .= $element->getText();
  14903. }
  14904. return $text;
  14905. }
  14906. /**
  14907. * 提取图片内容(使用火山引擎 OCR)
  14908. */
  14909. private function extractImageContent($filePath) {
  14910. if (!file_exists($filePath)) {
  14911. Utils::throwError('20003:文件不存在');
  14912. }
  14913. try {
  14914. // 读取图片并转换为 base64
  14915. $imageData = file_get_contents($filePath);
  14916. $base64Image = base64_encode($imageData);
  14917. // 调用火山引擎 OCR 服务
  14918. $content = $this->callVolcEngineOCR($base64Image);
  14919. return trim($content);
  14920. } catch (\Exception $e) {
  14921. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  14922. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  14923. Utils::throwError('20003:图片识别失败');
  14924. }
  14925. }
  14926. /**
  14927. * 调用火山引擎 OCR 服务识别图片文字
  14928. *
  14929. * @param string $base64Image base64 编码的图片数据
  14930. * @return string 识别的文字内容
  14931. */
  14932. private function callVolcEngineOCR($base64Image) {
  14933. $method = 'POST';
  14934. $service = 'cv';
  14935. $host = 'visual.volcengineapi.com';
  14936. $region = env('VOLC_REGION', 'cn-north-1');
  14937. $access_key = env('VOLC_AK');
  14938. $secret_key = env('VOLC_SK');
  14939. $action = 'OCRNormal';
  14940. $version = '2020-08-26';
  14941. if (!$access_key || !$secret_key) {
  14942. Utils::throwError('20003:请配置火山引擎 AK/SK');
  14943. }
  14944. // 请求体
  14945. $body = json_encode([
  14946. 'image_base64' => $base64Image
  14947. ]);
  14948. // 生成签名
  14949. $headers = $this->getVolcEngineSignHeaders(
  14950. $method, $service, $host, $region,
  14951. "Action={$action}&Version={$version}",
  14952. $access_key, $secret_key, $body
  14953. );
  14954. $client = new Client(['timeout' => 1800, 'verify' => false]);
  14955. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  14956. 'headers' => $headers,
  14957. 'body' => $body
  14958. ]);
  14959. $response_arr = json_decode($response->getBody()->getContents(), true);
  14960. // 提取识别的文字
  14961. $textLines = [];
  14962. if (isset($response_arr['data']['line_texts'])) {
  14963. $textLines = $response_arr['data']['line_texts'];
  14964. } elseif (isset($response_arr['data']['ocr_infos'])) {
  14965. foreach ($response_arr['data']['ocr_infos'] as $info) {
  14966. if (isset($info['text'])) {
  14967. $textLines[] = $info['text'];
  14968. }
  14969. }
  14970. }
  14971. if (empty($textLines)) {
  14972. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  14973. return '';
  14974. }
  14975. return implode("\n", $textLines);
  14976. }
  14977. /**
  14978. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  14979. */
  14980. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  14981. $contentType = 'application/json';
  14982. $accept = 'application/json';
  14983. // 获取当前UTC时间
  14984. $t = new DateTime('now', new DateTimeZone('UTC'));
  14985. $xDate = $t->format('Ymd\THis\Z');
  14986. $dateStamp = $t->format('Ymd');
  14987. // 计算 body 的 sha256 哈希
  14988. $payloadHash = hash('sha256', $body);
  14989. // 1. 拼接规范请求串
  14990. $canonicalUri = '/';
  14991. $canonicalQueryString = $queryString;
  14992. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  14993. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  14994. $canonicalRequest = implode("\n", [
  14995. $method,
  14996. $canonicalUri,
  14997. $canonicalQueryString,
  14998. $canonicalHeaders,
  14999. $signedHeaders,
  15000. $payloadHash
  15001. ]);
  15002. // 2. 拼接待签名字符串
  15003. $algorithm = 'HMAC-SHA256';
  15004. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  15005. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  15006. $stringToSign = implode("\n", [
  15007. $algorithm,
  15008. $xDate,
  15009. $credentialScope,
  15010. $hashedCanonicalRequest
  15011. ]);
  15012. // 3. 计算签名
  15013. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  15014. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  15015. // 4. 添加签名到请求头
  15016. $authorizationHeader = sprintf(
  15017. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  15018. $algorithm,
  15019. $access_key,
  15020. $credentialScope,
  15021. $signedHeaders,
  15022. $signature
  15023. );
  15024. return [
  15025. 'Accept' => $accept,
  15026. 'Content-Type' => $contentType,
  15027. 'Host' => $host,
  15028. 'X-Date' => $xDate,
  15029. 'X-Content-Sha256'=> $payloadHash,
  15030. 'Authorization' => $authorizationHeader
  15031. ];
  15032. }
  15033. public function generateScriptWords($cid, $model = 'r1') {
  15034. ini_set('max_execution_time', 0);
  15035. if (!$cid) Utils::throwError('20003: 请选择章节!');
  15036. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  15037. // 模型兼容性处理和思考模式设置
  15038. $thinkingMode = 'disabled';
  15039. $reasoningEffort = 'high';
  15040. if ($model == 'r1') {
  15041. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  15042. $thinkingMode = 'enabled';
  15043. } else {
  15044. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  15045. $thinkingMode = 'disabled';
  15046. }
  15047. $messages = [
  15048. [
  15049. 'role' => 'system',
  15050. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  15051. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  15052. 2.非对话部分请全部用旁白角色代替
  15053. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  15054. ],
  15055. [
  15056. 'role' => 'user',
  15057. 'content' => $content
  15058. ]
  15059. ];
  15060. $post_data = [
  15061. 'model' => $model,
  15062. 'messages' => $messages,
  15063. // 'max_tokens' => 8192,
  15064. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  15065. 'frequency_penalty' => 0,
  15066. 'presence_penalty' => 0,
  15067. 'thinking' => ['type' => $thinkingMode],
  15068. 'response_format' => [
  15069. 'type' => 'text'
  15070. ],
  15071. 'stream' => false
  15072. ];
  15073. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  15074. // 根据模型类型选择调用方法
  15075. $fullContent = '';
  15076. $usage = [];
  15077. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  15078. if (is_array($chatResult)) {
  15079. $fullContent = $chatResult['fullContent'];
  15080. $usage = $chatResult['usage'] ?? [];
  15081. }
  15082. // 仅记录 token 使用明细(不扣积分)
  15083. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  15084. 'model' => $model,
  15085. 'cid' => $cid,
  15086. 'source' => 'generateScriptWords',
  15087. ], $model);
  15088. return $fullContent;
  15089. }
  15090. /**
  15091. * 智能化解析集数信息
  15092. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  15093. *
  15094. * @param string $prompt 用户输入的提示词
  15095. * @return int|null 解析出的集数,如果没有找到则返回null
  15096. */
  15097. private function extractEpisodeNumber($prompt)
  15098. {
  15099. if (empty($prompt)) {
  15100. return null;
  15101. }
  15102. // 定义各种可能的表达模式
  15103. $patterns = [
  15104. // 基本模式:改成N集、调整成N集、修改成N集
  15105. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  15106. // 扩展模式:分成N集、拆分成N集、分割成N集
  15107. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  15108. // 数量模式:N集、共N集、总共N集
  15109. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  15110. // 制作模式:制作N集、生成N集、创建N集
  15111. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  15112. // 计划模式:计划N集、预计N集、打算N集
  15113. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  15114. // 需要模式:需要N集、要N集
  15115. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  15116. // 中文数字模式:改成三集、调整成五集等
  15117. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  15118. // 英文数字模式
  15119. '/(?: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',
  15120. ];
  15121. // 中文数字转阿拉伯数字的映射
  15122. $chineseNumbers = [
  15123. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  15124. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  15125. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  15126. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  15127. ];
  15128. // 逐个尝试匹配模式
  15129. foreach ($patterns as $pattern) {
  15130. if (preg_match($pattern, $prompt, $matches)) {
  15131. $number = trim($matches[1]);
  15132. // 如果是中文数字,转换为阿拉伯数字
  15133. if (isset($chineseNumbers[$number])) {
  15134. return $chineseNumbers[$number];
  15135. }
  15136. // 如果是阿拉伯数字,直接返回
  15137. if (is_numeric($number)) {
  15138. $episodeNum = intval($number);
  15139. // 合理性检查:集数应该在1-100之间
  15140. if ($episodeNum >= 1 && $episodeNum <= 100) {
  15141. return $episodeNum;
  15142. }
  15143. }
  15144. }
  15145. }
  15146. return null;
  15147. }
  15148. /**
  15149. * 调用火山引擎对话(Chat) API
  15150. *
  15151. * @param array $params 包含以下参数:
  15152. * - model: 模型ID(必填)
  15153. * - messages: 消息列表(必填)
  15154. * - stream: 是否流式输出(可选,默认false)
  15155. * - max_tokens: 最大输出token数(可选)
  15156. * - temperature: 采样温度(可选,默认1)
  15157. * - top_p: 核采样概率(可选,默认0.7)
  15158. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  15159. * - presence_penalty: 存在惩罚系数(可选,默认0)
  15160. * - stop: 停止词(可选)
  15161. * - tools: 工具列表(可选)
  15162. * @return array|Generator 非流式返回数组,流式返回生成器
  15163. */
  15164. public function volcEngineChatCompletion(array $params)
  15165. {
  15166. // 百度 GLM 已由 dispatchStreamByModel / dispatchChatOnlyByModel 统一分发,此处不再转发
  15167. $frontModel = getProp($params, 'model', '');
  15168. if (in_array($frontModel, $this->baidu_glm_text_models, true)) {
  15169. Utils::throwError('20003:百度GLM模型请使用统一分发方法dispatchStreamByModel/dispatchChatOnlyByModel调用');
  15170. }
  15171. $apiKey = env('VOLC_AI_API_KEY');
  15172. if (empty($apiKey)) {
  15173. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  15174. }
  15175. // 构建请求参数
  15176. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  15177. $requestData = [
  15178. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  15179. 'messages' => $params['messages'] ?? [],
  15180. ];
  15181. if (!in_array($originalModel, $this->valid_text_models)) {
  15182. Utils::throwError('20003:该模型不支持!');
  15183. }
  15184. // 添加可选参数
  15185. if (isset($params['stream'])) {
  15186. $requestData['stream'] = $params['stream'];
  15187. }
  15188. if (isset($params['stream_options'])) {
  15189. $requestData['stream_options'] = $params['stream_options'];
  15190. }
  15191. if (isset($params['max_tokens'])) {
  15192. $requestData['max_tokens'] = $params['max_tokens'];
  15193. }else if (isset($params['max_completion_tokens'])) {
  15194. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  15195. }else {
  15196. $requestData['max_completion_tokens'] = 100000;
  15197. }
  15198. if (isset($params['temperature'])) {
  15199. $requestData['temperature'] = $params['temperature'];
  15200. }
  15201. if (isset($params['top_p'])) {
  15202. $requestData['top_p'] = $params['top_p'];
  15203. }
  15204. if (isset($params['frequency_penalty'])) {
  15205. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  15206. }
  15207. if (isset($params['presence_penalty'])) {
  15208. $requestData['presence_penalty'] = $params['presence_penalty'];
  15209. }
  15210. if (isset($params['stop'])) {
  15211. $requestData['stop'] = $params['stop'];
  15212. }
  15213. if (isset($params['tools'])) {
  15214. $requestData['tools'] = $params['tools'];
  15215. }
  15216. if (isset($params['tool_choice'])) {
  15217. $requestData['tool_choice'] = $params['tool_choice'];
  15218. }
  15219. if (isset($params['response_format'])) {
  15220. $requestData['response_format'] = $params['response_format'];
  15221. }
  15222. if (isset($params['thinking'])) {
  15223. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  15224. if (is_array($params['thinking'])) {
  15225. $requestData['thinking'] = $params['thinking'];
  15226. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  15227. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  15228. }
  15229. } else {
  15230. $requestData['thinking'] = ['type' => $params['thinking']];
  15231. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  15232. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  15233. }
  15234. }
  15235. } else {
  15236. $requestData['thinking'] = ['type' => 'disabled'];
  15237. }
  15238. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  15239. $client = new Client(['verify' => false, 'timeout' => 1800]);
  15240. try {
  15241. // 判断是否为流式输出
  15242. $isStream = isset($params['stream']) && $params['stream'] === true;
  15243. if ($isStream) {
  15244. // 流式输出
  15245. // 流式请求默认声明返回 usage(未显式传参时)
  15246. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  15247. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  15248. } else {
  15249. // 非流式输出
  15250. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  15251. 'headers' => [
  15252. 'Authorization' => 'Bearer ' . $apiKey,
  15253. 'Content-Type' => 'application/json',
  15254. ],
  15255. 'json' => $requestData
  15256. ]);
  15257. $responseData = json_decode($response->getBody(), true);
  15258. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  15259. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  15260. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  15261. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  15262. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  15263. }
  15264. return [
  15265. 'fullContent' => $fullContent,
  15266. 'fullReasoningContent' => $fullReasoningContent,
  15267. 'usage' => $usage
  15268. ];
  15269. }
  15270. } catch (\Exception $e) {
  15271. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  15272. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  15273. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  15274. }
  15275. }
  15276. /**
  15277. * 火山引擎对话API流式输出
  15278. *
  15279. * @param Client $client HTTP客户端
  15280. * @param string $apiKey API密钥
  15281. * @param array $requestData 请求数据
  15282. * @return Generator
  15283. */
  15284. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  15285. {
  15286. try {
  15287. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  15288. 'headers' => [
  15289. 'Authorization' => 'Bearer ' . $apiKey,
  15290. 'Content-Type' => 'application/json',
  15291. ],
  15292. 'json' => $requestData,
  15293. 'stream' => true
  15294. ]);
  15295. $body = $response->getBody();
  15296. $buffer = '';
  15297. $fullContent = '';
  15298. $fullReasoningContent = '';
  15299. $usage = [];
  15300. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  15301. // 逐行读取流式响应
  15302. while (!$body->eof()) {
  15303. $chunk = $body->read(1024);
  15304. $buffer .= $chunk;
  15305. // 按行分割
  15306. $lines = explode("\n", $buffer);
  15307. $buffer = array_pop($lines);
  15308. foreach ($lines as $line) {
  15309. $line = trim($line);
  15310. if (empty($line)) {
  15311. continue;
  15312. }
  15313. // 检查是否是SSE数据行
  15314. if (strpos($line, 'data: ') !== 0) {
  15315. continue;
  15316. }
  15317. $data = substr($line, 6);
  15318. if ($data === '[DONE]') {
  15319. dLog('deepseek')->info('收到结束标记');
  15320. break 2;
  15321. }
  15322. try {
  15323. $json = json_decode($data, true);
  15324. if (json_last_error() !== JSON_ERROR_NONE) {
  15325. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  15326. continue;
  15327. }
  15328. if (isset($json['choices'][0]['delta'])) {
  15329. $delta = $json['choices'][0]['delta'];
  15330. // 处理思维链内容
  15331. if (isset($delta['reasoning_content'])) {
  15332. $fullReasoningContent .= $delta['reasoning_content'];
  15333. yield [
  15334. 'type' => 'reasoning',
  15335. 'content' => $delta['reasoning_content'],
  15336. 'full_reasoning' => $fullReasoningContent
  15337. ];
  15338. }
  15339. // 处理回答内容
  15340. if (isset($delta['content'])) {
  15341. $fullContent .= $delta['content'];
  15342. yield [
  15343. 'type' => 'content',
  15344. 'content' => $delta['content'],
  15345. ];
  15346. }
  15347. }
  15348. // 获取使用统计信息
  15349. if (isset($json['usage'])) {
  15350. $usage = $json['usage'];
  15351. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  15352. }
  15353. } catch (\Exception $e) {
  15354. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  15355. continue;
  15356. }
  15357. }
  15358. }
  15359. dLog('deepseek')->info('流式读取完成', [
  15360. 'content_length' => strlen($fullContent),
  15361. 'reasoning_length' => strlen($fullReasoningContent)
  15362. ]);
  15363. yield [
  15364. 'type' => 'done',
  15365. 'full_content' => $fullContent,
  15366. 'full_reasoning' => $fullReasoningContent,
  15367. 'usage' => $usage
  15368. ];
  15369. } catch (\Exception $e) {
  15370. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  15371. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  15372. throw $e;
  15373. }
  15374. }
  15375. /**
  15376. * 检查并创建图片生成任务
  15377. *
  15378. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  15379. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  15380. * @param string $nameKey 资源名称字段('role' 或 'scene')
  15381. * @param string $art_style 美术风格
  15382. * @return array 更新后的资源列表
  15383. */
  15384. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  15385. {
  15386. // 确保参数为数组
  15387. $merged_items = is_array($merged_items) ? $merged_items : [];
  15388. $global_items = is_array($global_items) ? $global_items : [];
  15389. // 构建全局资源映射表,用于快速查找
  15390. $global_map = [];
  15391. foreach ($global_items as $item) {
  15392. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  15393. if ($itemKey === '') {
  15394. continue;
  15395. }
  15396. $global_map[$itemKey] = $item;
  15397. }
  15398. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  15399. foreach ($merged_items as &$item) {
  15400. $item_name = getProp($item, $nameKey);
  15401. $item_description = getProp($item, 'description');
  15402. // $item_url = getProp($item, 'url');
  15403. // // 如果已有图片URL,跳过
  15404. // if (!empty($item_url)) {
  15405. // continue;
  15406. // }
  15407. // 如果是旁白角色,跳过
  15408. if ($nameKey === 'role' && $item_name === '旁白') {
  15409. continue;
  15410. }
  15411. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  15412. if ($itemKey === '') {
  15413. continue;
  15414. }
  15415. $need_create_task = false;
  15416. // 条件1:在全局资源中找不到匹配的名称
  15417. if (!isset($global_map[$itemKey])) {
  15418. $need_create_task = true;
  15419. } else {
  15420. // 条件2:名称匹配但描述或 pic_prompt 不一致
  15421. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  15422. $current_description = trim((string)$item_description);
  15423. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  15424. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  15425. // 如果 description 或 pic_prompt 有变化,需要重新生成
  15426. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  15427. $need_create_task = true;
  15428. }
  15429. }
  15430. // 如果需要创建任务,调用图片生成服务
  15431. if ($need_create_task) {
  15432. try {
  15433. // 优先使用 pic_prompt,如果没有则使用 description
  15434. $pic_prompt = getProp($item, 'pic_prompt');
  15435. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  15436. // 添加美术风格前缀
  15437. if ($art_style) {
  15438. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  15439. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  15440. $description = "{$prefix}:{$description}";
  15441. }
  15442. $params = [
  15443. 'prompt' => $description,
  15444. 'ref_img_urls' => []
  15445. ];
  15446. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  15447. $task_id = $task->id;
  15448. if ($task_id) {
  15449. $item['task_id'] = $task_id;
  15450. $item['task_status'] = 'processing';
  15451. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  15452. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  15453. }
  15454. } catch (\Exception $e) {
  15455. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  15456. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  15457. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  15458. // 不抛出异常,继续处理其他资源
  15459. }
  15460. }
  15461. }
  15462. return $merged_items;
  15463. }
  15464. /**
  15465. * 同步新出现的主体和场景到全局
  15466. *
  15467. * @param int $anime_id 动漫ID
  15468. * @param array $merged_roles 合并后的角色列表
  15469. * @param array $merged_scenes 合并后的场景列表
  15470. * @param array $global_roles 全局角色列表
  15471. * @param array $global_scenes 全局场景列表
  15472. * @return void
  15473. */
  15474. private function syncNewResourcesToGlobal(
  15475. int $anime_id,
  15476. array $merged_roles,
  15477. array $merged_scenes,
  15478. array $global_roles,
  15479. array $global_scenes
  15480. ): void {
  15481. // 构建全局角色映射表
  15482. $global_role_map = [];
  15483. foreach ($global_roles as $role) {
  15484. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  15485. if ($roleKey !== '') {
  15486. $global_role_map[$roleKey] = $role;
  15487. }
  15488. }
  15489. // 构建全局场景映射表
  15490. $global_scene_map = [];
  15491. foreach ($global_scenes as $scene) {
  15492. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  15493. if ($sceneKey !== '') {
  15494. $global_scene_map[$sceneKey] = $scene;
  15495. }
  15496. }
  15497. $need_update = false;
  15498. $new_global_roles = $global_roles;
  15499. $new_global_scenes = $global_scenes;
  15500. // 检查并添加新角色到全局
  15501. foreach ($merged_roles as $role) {
  15502. $role_name = getProp($role, 'role');
  15503. // 跳过旁白
  15504. if ($role_name === '旁白') {
  15505. continue;
  15506. }
  15507. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  15508. if ($roleKey === '') {
  15509. continue;
  15510. }
  15511. // 如果全局中不存在该角色,添加到全局
  15512. if (!isset($global_role_map[$roleKey])) {
  15513. $new_global_roles[] = [
  15514. 'role' => $role_name,
  15515. 'description' => getProp($role, 'description', ''),
  15516. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  15517. 'voice_name' => getProp($role, 'voice_name', ''),
  15518. 'voice_type' => getProp($role, 'voice_type', ''),
  15519. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  15520. 'url' => getProp($role, 'url', ''),
  15521. 'task_id' => getProp($role, 'task_id', ''),
  15522. 'task_status' => getProp($role, 'task_status', ''),
  15523. ];
  15524. $global_role_map[$roleKey] = true; // 标记已添加
  15525. $need_update = true;
  15526. dLog('deepseek')->info("新角色同步到全局", [
  15527. 'anime_id' => $anime_id,
  15528. 'role' => $role_name,
  15529. 'task_id' => getProp($role, 'task_id', ''),
  15530. ]);
  15531. }
  15532. // else {
  15533. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  15534. // $global_role = $global_role_map[$roleKey];
  15535. // if (is_array($global_role)) {
  15536. // $updated = false;
  15537. // $update_fields = [];
  15538. // // 检查描述是否更新
  15539. // $current_description = trim((string)getProp($role, 'description'));
  15540. // $global_description = trim((string)getProp($global_role, 'description'));
  15541. // if ($current_description !== '' && $current_description !== $global_description) {
  15542. // $updated = true;
  15543. // $update_fields[] = 'description';
  15544. // }
  15545. // // 检查pic_prompt是否更新
  15546. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  15547. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  15548. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  15549. // $updated = true;
  15550. // $update_fields[] = 'pic_prompt';
  15551. // }
  15552. // // 检查图片任务信息是否更新
  15553. // $current_task_id = getProp($role, 'task_id');
  15554. // $global_task_id = getProp($global_role, 'task_id');
  15555. // if ($current_task_id && $current_task_id !== $global_task_id) {
  15556. // $updated = true;
  15557. // $update_fields[] = 'task_id';
  15558. // }
  15559. // // 如果有更新,同步到全局
  15560. // if ($updated) {
  15561. // foreach ($new_global_roles as &$global_role_item) {
  15562. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  15563. // if ($global_role_key === $roleKey) {
  15564. // if (in_array('description', $update_fields)) {
  15565. // $global_role_item['description'] = $current_description;
  15566. // }
  15567. // if (in_array('pic_prompt', $update_fields)) {
  15568. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  15569. // }
  15570. // if (in_array('task_id', $update_fields)) {
  15571. // $global_role_item['task_id'] = $current_task_id;
  15572. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  15573. // $global_role_item['url'] = getProp($role, 'url', '');
  15574. // }
  15575. // break;
  15576. // }
  15577. // }
  15578. // $need_update = true;
  15579. // dLog('deepseek')->info("角色信息更新到全局", [
  15580. // 'anime_id' => $anime_id,
  15581. // 'role' => $role_name,
  15582. // 'update_fields' => implode(',', $update_fields),
  15583. // ]);
  15584. // }
  15585. // }
  15586. // }
  15587. }
  15588. // 检查并添加新场景到全局
  15589. foreach ($merged_scenes as $scene) {
  15590. $scene_name = getProp($scene, 'scene');
  15591. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  15592. if ($sceneKey === '') {
  15593. continue;
  15594. }
  15595. // 如果全局中不存在该场景,添加到全局
  15596. if (!isset($global_scene_map[$sceneKey])) {
  15597. $new_global_scenes[] = [
  15598. 'scene' => $scene_name,
  15599. 'description' => getProp($scene, 'description', ''),
  15600. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  15601. 'url' => getProp($scene, 'url', ''),
  15602. 'task_id' => getProp($scene, 'task_id', ''),
  15603. 'task_status' => getProp($scene, 'task_status', ''),
  15604. ];
  15605. $global_scene_map[$sceneKey] = true; // 标记已添加
  15606. $need_update = true;
  15607. dLog('deepseek')->info("新场景同步到全局", [
  15608. 'anime_id' => $anime_id,
  15609. 'scene' => $scene_name,
  15610. 'task_id' => getProp($scene, 'task_id', ''),
  15611. ]);
  15612. }
  15613. // else {
  15614. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  15615. // $global_scene = $global_scene_map[$sceneKey];
  15616. // if (is_array($global_scene)) {
  15617. // $updated = false;
  15618. // $update_fields = [];
  15619. // // 检查描述是否更新
  15620. // $current_description = trim((string)getProp($scene, 'description'));
  15621. // $global_description = trim((string)getProp($global_scene, 'description'));
  15622. // if ($current_description !== '' && $current_description !== $global_description) {
  15623. // $updated = true;
  15624. // $update_fields[] = 'description';
  15625. // }
  15626. // // 检查pic_prompt是否更新
  15627. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  15628. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  15629. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  15630. // $updated = true;
  15631. // $update_fields[] = 'pic_prompt';
  15632. // }
  15633. // // 检查图片任务信息是否更新
  15634. // $current_task_id = getProp($scene, 'task_id');
  15635. // $global_task_id = getProp($global_scene, 'task_id');
  15636. // if ($current_task_id && $current_task_id !== $global_task_id) {
  15637. // $updated = true;
  15638. // $update_fields[] = 'task_id';
  15639. // }
  15640. // // 如果有更新,同步到全局
  15641. // if ($updated) {
  15642. // foreach ($new_global_scenes as &$global_scene_item) {
  15643. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  15644. // if ($global_scene_key === $sceneKey) {
  15645. // if (in_array('description', $update_fields)) {
  15646. // $global_scene_item['description'] = $current_description;
  15647. // }
  15648. // if (in_array('pic_prompt', $update_fields)) {
  15649. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  15650. // }
  15651. // if (in_array('task_id', $update_fields)) {
  15652. // $global_scene_item['task_id'] = $current_task_id;
  15653. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  15654. // $global_scene_item['url'] = getProp($scene, 'url', '');
  15655. // }
  15656. // break;
  15657. // }
  15658. // }
  15659. // $need_update = true;
  15660. // dLog('deepseek')->info("场景信息更新到全局", [
  15661. // 'anime_id' => $anime_id,
  15662. // 'scene' => $scene_name,
  15663. // 'update_fields' => implode(',', $update_fields),
  15664. // ]);
  15665. // }
  15666. // }
  15667. // }
  15668. }
  15669. // 如果有新增或更新,更新数据库
  15670. if ($need_update) {
  15671. $update_data = [
  15672. 'roles' => json_encode($new_global_roles, 256),
  15673. 'scenes' => json_encode($new_global_scenes, 256),
  15674. 'updated_at' => date('Y-m-d H:i:s'),
  15675. ];
  15676. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  15677. if ($result !== false) {
  15678. dLog('deepseek')->info("全局角色和场景更新成功", [
  15679. 'anime_id' => $anime_id,
  15680. 'roles_count' => count($new_global_roles),
  15681. 'scenes_count' => count($new_global_scenes),
  15682. ]);
  15683. } else {
  15684. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  15685. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  15686. }
  15687. }
  15688. }
  15689. }