DeepSeekService.php 855 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762
  1. <?php
  2. namespace App\Services\DeepSeek;
  3. use App\Consts\ErrorConst;
  4. use App\Consts\BaseConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use GuzzleHttp\Client;
  8. use DateTime;
  9. use DateTimeZone;
  10. use App\Models\MpTaskCenter;
  11. use App\Models\MpUserPointsDetail;
  12. use App\Services\AIGeneration\AIImageGenerationService;
  13. use App\Services\PointsService;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Log;
  16. use Illuminate\Support\Facades\Redis;
  17. use OSS\Core\OssException;
  18. use OSS\OssClient;
  19. use Smalot\PdfParser\Parser as PdfParser;
  20. use TCPDF;
  21. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  22. use Predis\Command\Traits\Get\Get;
  23. class DeepSeekService
  24. {
  25. private $url;
  26. private $api_key;
  27. private $sys_message;
  28. private $headers;
  29. private $valid_text_models;
  30. private $gpt_text_models;
  31. private $gemini_text_models;
  32. protected $aiImageGenerationService;
  33. protected $pointsService;
  34. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  35. $this->aiImageGenerationService = $aiImageGenerationService;
  36. $this->pointsService = $pointsService;
  37. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  38. $this->api_key = env('DEEPSEEK_API_KEY');
  39. $this->headers = [
  40. 'Authorization' => 'Bearer '.$this->api_key,
  41. 'Content-Type' => 'application/json; charset=UTF-8'
  42. ];
  43. // 火山引擎模型列表
  44. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  45. // GPT文本模型列表
  46. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  47. // Gemini文本模型列表
  48. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  49. $this->sys_message = [
  50. 'role' => 'system',
  51. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  52. 强制要求:\n
  53. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  54. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  55. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  56. 普通要求:\n
  57. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  58. 2.<分集剧本>的要求如下:
  59.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  60.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  61.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  62.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  63. \n\n
  64. 示例如下:\n
  65. ###剧本名:西昆仑
  66. ###故事梗概
  67. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  68. ###剧本亮点
  69. 亮点1:绝境奇药,生死一线
  70. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  71. 亮点2:结拜兄妹,化解尴尬
  72. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  73. 亮点3:纤发夺命,情愫暗涌
  74. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  75. ###人物关系
  76. 阿雪与梁萧之间存在兄妹之情。
  77. ###核心矛盾
  78. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  79. ###主体列表
  80. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  81. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  82. 阴阳球:天地异宝,能化生精气,救人于危难。
  83. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  84. ###美术风格
  85. 基础画风风格词:厚涂古风
  86. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  87. ###场景列表
  88. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  89. ###分集剧本
  90. ##分集01
  91. 第1集: 第一集的标题
  92. 场景描述:地点、时间、场景
  93. 运镜:固定近距离
  94. 出场角色:男主、女主
  95. 台词内容:
  96. 女主: 女主对话
  97. 男主:男主对话
  98. 女主: 女主对话
  99. 男主: 男主对话
  100. ##分集02
  101. 第2集: 第二集的标题
  102. 场景描述:地点、时间、场景
  103. 运镜:固定近距离
  104. 出场角色:男主、女主
  105. 台词内容:
  106. 女主: 女主对话
  107. 男主:男主对话
  108. 女主: 女主对话
  109. 男主: 男主对话"
  110. ];
  111. }
  112. /**
  113. * 通用文生文方法 - 支持多模型流式输出、图片输入;视频输入仅 Gemini 模型支持
  114. *
  115. * @param array $data 请求参数
  116. * @return \Generator 返回生成器,用于流式输出
  117. */
  118. public function generateText($data) {
  119. // 获取请求参数
  120. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  121. $messages = getProp($data, 'messages', []);
  122. $systemPrompt = getProp($data, 'system_prompt', '');
  123. $prompt = getProp($data, 'prompt', '');
  124. $images = getProp($data, 'images', []); // 支持多张图片
  125. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  126. $videos = getProp($data, 'videos', []); // Gemini 支持视频文件
  127. $videoUrls = getProp($data, 'video_urls', []); // Gemini 支持视频URL
  128. $isGeminiModel = in_array($model, $this->gemini_text_models);
  129. if ((!empty($videos) || !empty($videoUrls)) && !$isGeminiModel) {
  130. Utils::throwError('20003:仅Gemini模型支持视频输入');
  131. }
  132. // Gemini 多模态(图片/视频 -> 文本)按模型预检积分;纯文本不扣费
  133. $uid = Site::getUid();
  134. $chargeModality = '';
  135. $chargePoints = 0;
  136. $hasImageMedia = !empty($images) || !empty($imageUrls)
  137. || $this->messagesContainMedia($messages, ['image_url', 'image']);
  138. $hasVideoMedia = !empty($videos) || !empty($videoUrls)
  139. || $this->messagesContainMedia($messages, ['video_url', 'video']);
  140. if ($isGeminiModel && ($hasImageMedia || $hasVideoMedia)) {
  141. $chargeModality = $hasVideoMedia ? 'video' : 'image';
  142. $pricingModel = $this->geminiMultimodalPricingModel($model);
  143. if ($pricingModel !== '') {
  144. $chargePoints = $this->pointsService->getVideoChargePoints(['model' => $pricingModel]);
  145. if ($chargePoints > 0) {
  146. $this->pointsService->checkUserPointsEnough($chargePoints, $uid);
  147. }
  148. }
  149. }
  150. // 如果没有提供messages,则根据system_prompt、content和images构建
  151. if (empty($messages)) {
  152. $messages = [];
  153. // 添加系统提示词
  154. if (!empty($systemPrompt)) {
  155. $messages[] = [
  156. 'role' => 'system',
  157. 'content' => $systemPrompt
  158. ];
  159. }
  160. // 构建用户消息内容(支持文本+图片)
  161. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  162. $userMessage = [
  163. 'role' => 'user',
  164. 'content' => []
  165. ];
  166. // 添加文本内容
  167. if (!empty($prompt)) {
  168. $userMessage['content'][] = [
  169. 'type' => 'text',
  170. 'text' => $prompt
  171. ];
  172. }
  173. // 处理上传的图片文件
  174. if (!empty($images)) {
  175. if (!is_array($images)) {
  176. $images = [$images];
  177. }
  178. foreach ($images as $image) {
  179. $imageBase64 = $this->processImageToBase64($image);
  180. if ($imageBase64) {
  181. $userMessage['content'][] = [
  182. 'type' => 'image_url',
  183. 'image_url' => [
  184. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  185. ]
  186. ];
  187. }
  188. }
  189. }
  190. // 处理图片URL
  191. if (!empty($imageUrls)) {
  192. if (!is_array($imageUrls)) {
  193. $imageUrls = [$imageUrls];
  194. }
  195. foreach ($imageUrls as $url) {
  196. if (!empty($url)) {
  197. $userMessage['content'][] = [
  198. 'type' => 'image_url',
  199. 'image_url' => [
  200. 'url' => $url
  201. ]
  202. ];
  203. }
  204. }
  205. }
  206. // 处理上传的视频文件(仅 Gemini)
  207. if (!empty($videos) && $isGeminiModel) {
  208. if (!is_array($videos)) {
  209. $videos = [$videos];
  210. }
  211. foreach ($videos as $video) {
  212. $inlineData = $this->processMediaToInlineData($video);
  213. if ($inlineData) {
  214. $userMessage['content'][] = [
  215. 'type' => 'video',
  216. 'inline_data' => $inlineData
  217. ];
  218. }
  219. }
  220. }
  221. // 处理视频URL(仅 Gemini)
  222. if (!empty($videoUrls) && $isGeminiModel) {
  223. if (!is_array($videoUrls)) {
  224. $videoUrls = [$videoUrls];
  225. }
  226. foreach ($videoUrls as $url) {
  227. if (!empty($url)) {
  228. $userMessage['content'][] = [
  229. 'type' => 'video_url',
  230. 'video_url' => ['url' => $url]
  231. ];
  232. }
  233. }
  234. }
  235. // 如果只有文本内容,简化为字符串格式
  236. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  237. $userMessage['content'] = $userMessage['content'][0]['text'];
  238. }
  239. $messages[] = $userMessage;
  240. }
  241. }
  242. // 验证messages不为空
  243. if (empty($messages)) {
  244. Utils::throwError('20003:请提供有效的对话内容');
  245. }
  246. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  247. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  248. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  249. if ($model === 'deepseek-chat') {
  250. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  251. $model = 'deepseek-v4-flash';
  252. $thinkingMode = 'disabled';
  253. } elseif ($model === 'deepseek-reasoner') {
  254. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  255. $model = 'deepseek-v4-flash';
  256. $thinkingMode = 'enabled';
  257. }
  258. // 构建请求参数
  259. $post_data = [
  260. 'model' => $model,
  261. 'messages' => $messages,
  262. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  263. 'temperature' => getProp($data, 'temperature', 1),
  264. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  265. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  266. 'thinking' => ['type' => $thinkingMode],
  267. 'stream' => true // 启用流式输出
  268. ];
  269. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  270. // 添加可选参数
  271. if (isset($data['top_p'])) {
  272. $post_data['top_p'] = $data['top_p'];
  273. }
  274. if (isset($data['response_format'])) {
  275. $post_data['response_format'] = $data['response_format'];
  276. }
  277. // 根据模型类型选择调用方法
  278. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  279. // DeepSeek 官方模型使用 DeepSeek API
  280. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  281. } else if (in_array($model, $this->gpt_text_models)) {
  282. // GPT 模型使用 TokenRouter API
  283. $streamGenerator = $this->gpt54StreamResponse($post_data);
  284. } else if (in_array($model, $this->gemini_text_models)) {
  285. // Gemini 模型使用 Gemini API
  286. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  287. } else if (in_array($model, $this->valid_text_models)) {
  288. // 火山引擎支持的模型使用火山引擎 API
  289. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  290. } else {
  291. Utils::throwError('20003:不支持的模型: ' . $model);
  292. }
  293. if ($chargePoints > 0) {
  294. return $this->wrapGenerateTextCharge($streamGenerator, $uid, $model, $chargePoints, $chargeModality);
  295. }
  296. // 纯文本(不扣积分):流式生成成功后仅记录 token 使用明细
  297. return $this->wrapGenerateTextTokenRecord($streamGenerator, $uid, $model);
  298. }
  299. /**
  300. * 流式生成成功后仅记录 token 明细(纯文本免费场景,不扣积分)
  301. *
  302. * @param \Generator $generator
  303. * @param int $uid
  304. * @param string $model
  305. * @return \Generator
  306. */
  307. private function wrapGenerateTextTokenRecord(\Generator $generator, int $uid, string $model, string $source = 'generateText'): \Generator
  308. {
  309. $recorded = false;
  310. foreach ($generator as $chunk) {
  311. if (!$recorded && isset($chunk['type']) && $chunk['type'] === 'done') {
  312. $this->recordTextTokenOnly($uid, $this->pointsService->getTokensFromUsage(getProp($chunk, 'usage', [])), [
  313. 'model' => $model,
  314. 'source' => $source,
  315. ], $model);
  316. $recorded = true;
  317. }
  318. yield $chunk;
  319. }
  320. }
  321. /**
  322. * 流式生成成功后再按 Gemini 多模态规则扣费
  323. *
  324. * @param \Generator $generator
  325. * @param int $uid
  326. * @param string $model
  327. * @param int $points
  328. * @param string $modality
  329. * @return \Generator
  330. */
  331. private function wrapGenerateTextCharge(\Generator $generator, int $uid, string $model, int $points, string $modality): \Generator
  332. {
  333. $charged = false;
  334. foreach ($generator as $chunk) {
  335. if (!$charged && isset($chunk['type']) && $chunk['type'] === 'done') {
  336. $fullContent = (string)getProp($chunk, 'full_content', getProp($chunk, 'answer', ''));
  337. if ($fullContent !== '') {
  338. $this->chargeGeminiMultimodal($uid, $model, $points, $modality, getProp($chunk, 'usage', []));
  339. $charged = true;
  340. }
  341. }
  342. yield $chunk;
  343. }
  344. }
  345. /**
  346. * Gemini 多模态(图片/视频 -> 文本)成功后扣费并记录 token 明细
  347. *
  348. * @param int $uid
  349. * @param string $model
  350. * @param int $points
  351. * @param string $modality
  352. * @param mixed $usage
  353. * @return void
  354. */
  355. private function chargeGeminiMultimodal(int $uid, string $model, int $points, string $modality, $usage): void
  356. {
  357. $result = $this->pointsService->recordChatCharge(
  358. $uid,
  359. $points,
  360. $this->pointsService->getTokensFromUsage($usage),
  361. [
  362. 'model' => $model,
  363. 'modality' => $modality,
  364. 'source' => 'generateText',
  365. ],
  366. '',
  367. $model
  368. );
  369. if (empty($result['charged'])) {
  370. throw new \Exception('Gemini多模态计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  371. }
  372. }
  373. /**
  374. * Gemini 文本模型 ID 转 mp_video_models 中的按次计费模型 ID
  375. *
  376. * @param string $model
  377. * @return string
  378. */
  379. private function geminiMultimodalPricingModel(string $model): string
  380. {
  381. $map = [
  382. 'gemini-3.1-flash-image-preview-t' => 'gemini-3.1-flash',
  383. 'gemini-3.1-pro-preview' => 'gemini-3.1-pro',
  384. 'gemini-3-flash-preview' => 'gemini-3.0-flash',
  385. 'gemini-3-pro-preview' => 'gemini-3.0-pro',
  386. 'gemini-3.6-flash' => 'gemini-3.6-flash',
  387. ];
  388. return $map[$model] ?? '';
  389. }
  390. /**
  391. * 检查 OpenAI 风格消息中是否包含指定媒体类型
  392. *
  393. * @param array $messages
  394. * @param array $mediaTypes
  395. * @return bool
  396. */
  397. private function messagesContainMedia(array $messages, array $mediaTypes): bool
  398. {
  399. foreach ($messages as $message) {
  400. $content = getProp($message, 'content', '');
  401. if (!is_array($content)) {
  402. continue;
  403. }
  404. foreach ($content as $part) {
  405. if (is_array($part) && in_array(getProp($part, 'type', ''), $mediaTypes, true)) {
  406. return true;
  407. }
  408. }
  409. }
  410. return false;
  411. }
  412. public function createGenerateText($data) {
  413. $file = getProp($data, 'file');
  414. $episode_num = getProp($data, 'episode_num');
  415. $uid = Site::getUid();
  416. $cpid = Site::getCpid();
  417. if (!$file) {
  418. Utils::throwError('20003:请上传文件');
  419. }
  420. // 提取文件内容
  421. $content = $this->extractFileContent($file);
  422. if (!$content) {
  423. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  424. }
  425. // 拆分章节并校验章节总数、标题连续性
  426. if ($episode_num) {
  427. $this->validateGenerateTextChapters($content, (int)$episode_num);
  428. }
  429. // 获取原始文件名(不含扩展名)作为script_name
  430. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  431. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  432. // 字节安全剥离,不依赖服务器locale设置
  433. $originalName = $file->getClientOriginalName();
  434. $extension = $file->getClientOriginalExtension();
  435. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  436. ? substr($originalName, 0, -strlen($extension) - 1)
  437. : $originalName;
  438. if ($script_name === '') {
  439. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  440. }
  441. // 如果同一用户的剧本名存在则提示
  442. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  443. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  444. }
  445. // 插入数据到mp_scripts表
  446. $script_id = DB::table('mp_scripts')->insertGetId([
  447. 'script_name' => $script_name,
  448. 'user_id' => $uid,
  449. 'cpid' => $cpid,
  450. 'content' => $content,
  451. 'created_at' => date('Y-m-d H:i:s'),
  452. 'updated_at' => date('Y-m-d H:i:s')
  453. ]);
  454. return [
  455. 'script_id' => $script_id,
  456. 'script_name' => $script_name
  457. ];
  458. }
  459. /**
  460. * AI对话调用成功后的积分扣费(返回结果前调用)
  461. *
  462. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  463. *
  464. * @param int $uid
  465. * @param int $tokens
  466. * @param array $chargeInfo
  467. * @return void
  468. */
  469. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo): void
  470. {
  471. // api_type 记录真实模型名(缺失时回退 deepseek 大类),保证明细与统计口径准确
  472. $model = (string)getProp($chargeInfo, 'model', '');
  473. $result = $this->pointsService->recordChatCharge(
  474. $uid,
  475. $this->pointsService->getChatChargePoints($model),
  476. $tokens,
  477. $chargeInfo,
  478. '',
  479. $model !== '' ? $model : 'deepseek'
  480. );
  481. if (empty($result['charged'])) {
  482. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  483. }
  484. }
  485. /**
  486. * 安全获取当前登录用户ID
  487. *
  488. * 命令行/队列等无用户上下文的场景返回 0,由记录方法自行跳过。
  489. *
  490. * @return int
  491. */
  492. private function getCurrentUid(): int
  493. {
  494. try {
  495. return (int)Site::getUid();
  496. } catch (\Throwable $e) {
  497. return 0;
  498. }
  499. }
  500. /**
  501. * 记录文生文 token 使用明细(仅记录,不扣积分)
  502. *
  503. * 用于不按积分计费的文生文接口;记录失败不影响主流程。
  504. *
  505. * @param int $uid 用户ID(0 时跳过)
  506. * @param int $tokens 消耗 token 数
  507. * @param array $chargeInfo 计费/来源信息(model、source 等)
  508. * @param string $apiType API 类型/模型标识
  509. * @return void
  510. */
  511. private function recordTextTokenOnly(int $uid, int $tokens, array $chargeInfo, string $apiType = ''): void
  512. {
  513. try {
  514. $this->pointsService->recordTokenOnlyDetail(
  515. $uid,
  516. $tokens,
  517. $chargeInfo,
  518. MpUserPointsDetail::TYPE_CHAT,
  519. $apiType,
  520. ''
  521. );
  522. } catch (\Throwable $e) {
  523. dLog('points')->warning('token明细记录异常(不影响主流程): ' . $e->getMessage(), [
  524. 'uid' => $uid,
  525. 'source' => $chargeInfo['source'] ?? '',
  526. ]);
  527. }
  528. }
  529. /**
  530. * 拆分剧本内容并校验章节总数与标题连续性
  531. *
  532. * @param string $content
  533. * @param int $episodeNum
  534. * @return void
  535. */
  536. private function validateGenerateTextChapters($content, $episodeNum)
  537. {
  538. $chapters = splitContent($content);
  539. if (count($chapters) !== $episodeNum) {
  540. Utils::throwError('20003:章节总数与集数不一致,请检查上传内容');
  541. }
  542. if (empty($chapters)) {
  543. return;
  544. }
  545. // 先尝试从标题正则中解析序号,确认是否从1开始连续递增
  546. $numbers = [];
  547. $unparsedIndex = null;
  548. foreach ($chapters as $index => $chapter) {
  549. $num = $this->parseChapterNumber($chapter['title']);
  550. if ($num === null) {
  551. $unparsedIndex = $index;
  552. break;
  553. }
  554. $numbers[] = $num;
  555. }
  556. if ($unparsedIndex === null) {
  557. $expected = 1;
  558. foreach ($numbers as $index => $num) {
  559. if ($num !== $expected) {
  560. $title = mb_substr(trim((string)$chapters[$index]['title']), 0, 40);
  561. Utils::throwError('20003:章节序号不连续:第' . ($index + 1) . '个章节“' . $title . '”序号为' . $num . ',预期为' . $expected);
  562. }
  563. $expected++;
  564. }
  565. return;
  566. }
  567. // 标题格式无法用正则确认时,交给模型分析
  568. $titles = array_column($chapters, 'title');
  569. $aiResult = $this->validateChapterSequenceByAI($titles);
  570. if ($aiResult['valid'] === false) {
  571. $badIndex = $aiResult['invalid_index'] ?: $unparsedIndex + 1;
  572. if (isset($chapters[$badIndex - 1])) {
  573. $title = mb_substr(trim((string)$chapters[$badIndex - 1]['title']), 0, 40);
  574. Utils::throwError('20003:章节序号不连续:第' . $badIndex . '个章节“' . $title . '”序号异常,请检查');
  575. }
  576. Utils::throwError('20003:章节序号不连续,请检查章节标题格式');
  577. }
  578. if ($aiResult['valid'] === null) {
  579. if (isset($chapters[$unparsedIndex])) {
  580. $title = mb_substr(trim((string)$chapters[$unparsedIndex]['title']), 0, 40);
  581. Utils::throwError('20003:无法确认第' . ($unparsedIndex + 1) . '个章节“' . $title . '”的章节序号,请检查标题格式');
  582. }
  583. Utils::throwError('20003:无法确认章节标题连续性,请检查章节标题格式');
  584. }
  585. }
  586. /**
  587. * 从章节标题中解析序号,支持阿拉伯数字和中文数字
  588. *
  589. * @param string $title
  590. * @return int|null
  591. */
  592. private function parseChapterNumber($title)
  593. {
  594. if (!preg_match('/第\s*([一二两三四五六七八九十百千万0-9]+)\s*[章节集幕场回话]/u', $title, $match)) {
  595. return null;
  596. }
  597. return $this->convertChineseNumber($match[1]);
  598. }
  599. /**
  600. * 中文数字转阿拉伯数字(支持到千)
  601. *
  602. * @param string $numStr
  603. * @return int
  604. */
  605. private function convertChineseNumber($numStr)
  606. {
  607. if (preg_match('/^\d+$/', $numStr)) {
  608. return (int)$numStr;
  609. }
  610. $map = [
  611. '零' => 0,
  612. '一' => 1,
  613. '二' => 2,
  614. '两' => 2,
  615. '三' => 3,
  616. '四' => 4,
  617. '五' => 5,
  618. '六' => 6,
  619. '七' => 7,
  620. '八' => 8,
  621. '九' => 9
  622. ];
  623. $total = 0;
  624. $section = 0;
  625. $length = mb_strlen($numStr);
  626. for ($i = 0; $i < $length; $i++) {
  627. $char = mb_substr($numStr, $i, 1);
  628. if (isset($map[$char])) {
  629. $section = $map[$char];
  630. } elseif ($char === '十') {
  631. $total += $section === 0 ? 10 : $section * 10;
  632. $section = 0;
  633. } elseif ($char === '百') {
  634. $total += $section === 0 ? 100 : $section * 100;
  635. $section = 0;
  636. } elseif ($char === '千') {
  637. $total += $section === 0 ? 1000 : $section * 1000;
  638. $section = 0;
  639. }
  640. }
  641. return $total + $section;
  642. }
  643. /**
  644. * 用 deepseek-v4-flash 非流式判断章节标题是否从1开始连续编号
  645. *
  646. * @param array $titles
  647. * @return array{valid: bool|null, invalid_index: int|null}
  648. */
  649. private function validateChapterSequenceByAI($titles)
  650. {
  651. $titleLines = [];
  652. foreach (array_slice($titles, 0, 200) as $index => $title) {
  653. $titleLines[] = ($index + 1) . '. ' . mb_substr(trim((string)$title), 0, 80);
  654. }
  655. $result = [
  656. 'valid' => null,
  657. 'invalid_index' => null
  658. ];
  659. $post_data = [
  660. 'model' => 'deepseek-v4-flash',
  661. 'messages' => [
  662. [
  663. 'role' => 'system',
  664. 'content' => '你是剧本章节校验助手。用户会给出章节标题列表,请判断这些标题中的编号是否从第1章/第1集开始连续递增,支持阿拉伯数字和中文数字。只输出 JSON,格式为 {"valid":true};若不连续则输出 {"valid":false,"invalid_index":N},其中 N 是第一个序号异常的章节序号(从1开始),不要输出其他内容。',
  665. ],
  666. [
  667. 'role' => 'user',
  668. 'content' => implode("\n", $titleLines),
  669. ],
  670. ],
  671. 'temperature' => 0,
  672. 'frequency_penalty' => 0,
  673. 'presence_penalty' => 0,
  674. 'stream' => false,
  675. ];
  676. try {
  677. $result = $this->chatOnly($post_data, 8);
  678. $content = trim((string)($result['fullContent'] ?? ''));
  679. if (preg_match('/"valid"\s*:\s*(true|false)/i', $content, $match)) {
  680. $result['valid'] = strtolower($match[1]) === 'true';
  681. }
  682. if (preg_match('/"invalid_index"\s*:\s*(\d+)/i', $content, $match)) {
  683. $result['invalid_index'] = (int)$match[1];
  684. }
  685. // 仅记录 token 使用明细(不扣积分):该校验为流程内的额外模型调用
  686. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  687. 'model' => 'deepseek-v4-flash',
  688. 'source' => 'validateChapterSequenceByAI',
  689. ], 'deepseek-v4-flash');
  690. } catch (\Exception $e) {
  691. dLog('deepseek')->error('章节连续性AI校验失败: ' . $e->getMessage());
  692. }
  693. return $result;
  694. }
  695. /**
  696. * 通用文生文(流式版本)- newGenerateText 的 stream=1 分支
  697. * 支持与 newGenerateText 相同的参数(模板/剧本/JSON输出/图片输入),
  698. * 输出格式与 generateText 一致:yield type=content / reasoning / done
  699. *
  700. * @param array $data 请求参数
  701. * @return \Generator
  702. */
  703. public function newGenerateTextStream($data) {
  704. $model = getProp($data, 'model', 'deepseek-v4-pro');
  705. $messages = getProp($data, 'messages', []);
  706. $systemPrompt = getProp($data, 'system_prompt', '');
  707. $prompt = getProp($data, 'prompt', '');
  708. $images = getProp($data, 'images', []);
  709. $imageUrls = getProp($data, 'image_urls', []);
  710. $responseFormat = getProp($data, 'response_format', 'text');
  711. $templateId = getProp($data, 'template_id', 0);
  712. $script_id = getProp($data, 'script_id', 0);
  713. $sequence = getProp($data, 'sequence', 0);
  714. $generateTaskId = 0;
  715. $uid = Site::getUid();
  716. if ($script_id > 0) {
  717. $existingTask = DB::table('mp_script_generate_tasks')
  718. ->where('uid', $uid)
  719. ->where('script_id', $script_id)
  720. ->orderByDesc('id')
  721. ->first();
  722. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  723. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  724. }
  725. }
  726. // 如果提供了script_id,从数据库获取剧本内容作为原文
  727. $originalContent = '';
  728. $hasValidScript = false;
  729. if ($script_id > 0) {
  730. $script = DB::table('mp_scripts')
  731. ->where('id', $script_id)
  732. ->where('is_deleted', 0)
  733. ->first();
  734. if (!$script) {
  735. Utils::throwError('20003:剧本不存在或已删除');
  736. }
  737. $originalContent = $script->content ?? '';
  738. if (empty($originalContent)) {
  739. Utils::throwError('20003:剧本内容为空');
  740. }
  741. $hasValidScript = true;
  742. if (!empty($prompt)) {
  743. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  744. } else {
  745. $prompt = "原文内容:\n" . $originalContent;
  746. }
  747. }
  748. // 如果提供了template_id,从数据库获取template_prompt
  749. if ($templateId > 0) {
  750. $template = DB::table('mp_prompt_templates')
  751. ->where('id', $templateId)
  752. ->where('is_deleted', 0)
  753. ->first();
  754. if (!$template) {
  755. Utils::throwError('20003:模板不存在或已删除');
  756. }
  757. $templatePrompt = $template->template_prompt ?? '';
  758. if (!empty($templatePrompt)) {
  759. if (!empty($prompt)) {
  760. $prompt = $templatePrompt . "\n\n" . $prompt;
  761. } else {
  762. $prompt = $templatePrompt;
  763. }
  764. }
  765. }
  766. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  767. if (empty($messages)) {
  768. $messages = [];
  769. if (!empty($systemPrompt)) {
  770. $messages[] = [
  771. 'role' => 'system',
  772. 'content' => $systemPrompt
  773. ];
  774. }
  775. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  776. $userMessage = [
  777. 'role' => 'user',
  778. 'content' => []
  779. ];
  780. if (!empty($prompt)) {
  781. $userMessage['content'][] = [
  782. 'type' => 'text',
  783. 'text' => $prompt
  784. ];
  785. }
  786. if (!empty($images)) {
  787. if (!is_array($images)) {
  788. $images = [$images];
  789. }
  790. foreach ($images as $image) {
  791. $imageBase64 = $this->processImageToBase64($image);
  792. if ($imageBase64) {
  793. $userMessage['content'][] = [
  794. 'type' => 'image_url',
  795. 'image_url' => [
  796. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  797. ]
  798. ];
  799. }
  800. }
  801. }
  802. if (!empty($imageUrls)) {
  803. if (!is_array($imageUrls)) {
  804. $imageUrls = [$imageUrls];
  805. }
  806. foreach ($imageUrls as $url) {
  807. if (!empty($url)) {
  808. $userMessage['content'][] = [
  809. 'type' => 'image_url',
  810. 'image_url' => [
  811. 'url' => $url
  812. ]
  813. ];
  814. }
  815. }
  816. }
  817. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  818. $userMessage['content'] = $userMessage['content'][0]['text'];
  819. }
  820. $messages[] = $userMessage;
  821. }
  822. }
  823. if (empty($messages)) {
  824. Utils::throwError('20003:请提供有效的对话内容');
  825. }
  826. // 模型兼容性处理
  827. $thinkingMode = getProp($data, 'thinking', 'disabled');
  828. $reasoningEffort = getProp($data, 'reasoning_effort', 'high');
  829. if ($model === 'deepseek-chat') {
  830. $model = 'deepseek-v4-flash';
  831. $thinkingMode = 'disabled';
  832. } elseif ($model === 'deepseek-reasoner') {
  833. $model = 'deepseek-v4-flash';
  834. $thinkingMode = 'enabled';
  835. }
  836. // 构建请求参数(流式)
  837. $post_data = [
  838. 'model' => $model,
  839. 'messages' => $messages,
  840. 'temperature' => getProp($data, 'temperature', 1),
  841. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  842. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  843. 'thinking' => ['type' => $thinkingMode],
  844. 'stream' => true
  845. ];
  846. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  847. if (isset($data['top_p'])) {
  848. $post_data['top_p'] = $data['top_p'];
  849. }
  850. // response_format=json 时附加 JSON 说明与响应格式(与 newGenerateText 一致)
  851. if ($responseFormat === 'json') {
  852. $hasJsonKeyword = false;
  853. foreach ($post_data['messages'] as $message) {
  854. if (isset($message['content'])) {
  855. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  856. if (stripos($content, 'json') !== false) {
  857. $hasJsonKeyword = true;
  858. break;
  859. }
  860. }
  861. }
  862. if (!$hasJsonKeyword) {
  863. $lastMessageIndex = count($post_data['messages']) - 1;
  864. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  865. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  866. if (is_string($lastContent)) {
  867. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  868. } elseif (is_array($lastContent)) {
  869. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  870. if ($contentPart['type'] === 'text') {
  871. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  872. break;
  873. }
  874. }
  875. }
  876. }
  877. }
  878. $post_data['response_format'] = ['type' => 'json_object'];
  879. }
  880. // 如果提供了script_id,创建剧本资产生成任务
  881. if ($script_id > 0) {
  882. $uid = Site::getUid();
  883. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  884. 'uid' => $uid,
  885. 'script_id' => $script_id,
  886. 'sequence' => $sequence,
  887. 'status' => 'processing',
  888. 'prompt' => getProp($data, 'prompt', ''),
  889. 'started_at' => date('Y-m-d H:i:s'),
  890. 'created_at' => date('Y-m-d H:i:s'),
  891. 'updated_at' => date('Y-m-d H:i:s')
  892. ]);
  893. }
  894. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  895. if ($hasValidScript) {
  896. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  897. }
  898. // 根据模型类型选择流式调用方法
  899. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  900. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  901. } elseif (in_array($model, $this->gpt_text_models)) {
  902. $streamGenerator = $this->gpt54StreamResponse($post_data);
  903. } elseif (in_array($model, $this->gemini_text_models)) {
  904. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  905. } elseif (in_array($model, $this->valid_text_models)) {
  906. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  907. } else {
  908. Utils::throwError('20003:不支持的模型: ' . $model);
  909. }
  910. // 流式输出包装:done 时更新任务状态、扣费并保存对话记录
  911. return $this->wrapNewGenerateTextStream($streamGenerator, [
  912. 'uid' => $uid,
  913. 'model' => $model,
  914. 'generate_task_id' => $generateTaskId,
  915. 'has_valid_script' => $hasValidScript,
  916. 'script_id' => $script_id,
  917. 'sequence' => $sequence,
  918. 'original_prompt' => getProp($data, 'prompt', ''),
  919. 'response_format' => $responseFormat,
  920. ]);
  921. }
  922. /**
  923. * 流式生成收尾包装:done 时更新剧本资产生成任务、扣除积分并保存对话记录
  924. *
  925. * @param \Generator $generator
  926. * @param array $ctx
  927. * @return \Generator
  928. */
  929. private function wrapNewGenerateTextStream(\Generator $generator, array $ctx): \Generator
  930. {
  931. $fullContent = '';
  932. $usage = [];
  933. $finished = false;
  934. try {
  935. foreach ($generator as $chunk) {
  936. if (isset($chunk['type']) && $chunk['type'] === 'content') {
  937. $fullContent .= (string)getProp($chunk, 'content', '');
  938. }
  939. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  940. $fullContent = (string)getProp($chunk, 'full_content', $fullContent);
  941. $usage = getProp($chunk, 'usage', []);
  942. // 流式场景下部分模型/中转站不强制 JSON 输出,兜底提取标准 JSON
  943. if (($ctx['response_format'] ?? 'text') === 'json') {
  944. $fullContent = $this->extractJsonContent($fullContent);
  945. }
  946. $finished = true;
  947. }
  948. yield $chunk;
  949. }
  950. if ($finished) {
  951. if (!empty($ctx['generate_task_id'])) {
  952. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  953. 'status' => 'success',
  954. 'result' => $fullContent,
  955. 'completed_at' => date('Y-m-d H:i:s'),
  956. 'updated_at' => date('Y-m-d H:i:s'),
  957. ]);
  958. }
  959. if ($ctx['has_valid_script'] && $fullContent !== '') {
  960. $this->chargeChatSuccess($ctx['uid'], $this->pointsService->getTokensFromUsage($usage), [
  961. 'model' => $ctx['model'],
  962. 'script_id' => $ctx['script_id'],
  963. 'sequence' => $ctx['sequence'],
  964. 'source' => 'newGenerateText',
  965. ]);
  966. }
  967. if (!empty($ctx['script_id'])) {
  968. $now = now();
  969. DB::table('mp_script_records')->insert([
  970. [
  971. 'uid' => $ctx['uid'],
  972. 'script_id' => $ctx['script_id'],
  973. 'sequence' => $ctx['sequence'],
  974. 'role' => 'user',
  975. 'content' => $ctx['original_prompt'],
  976. 'created_at' => $now,
  977. 'updated_at' => $now,
  978. ],
  979. [
  980. 'uid' => $ctx['uid'],
  981. 'script_id' => $ctx['script_id'],
  982. 'sequence' => $ctx['sequence'],
  983. 'role' => 'assistant',
  984. 'content' => $fullContent,
  985. 'created_at' => $now,
  986. 'updated_at' => $now,
  987. ],
  988. ]);
  989. }
  990. }
  991. } catch (\Throwable $e) {
  992. if (!empty($ctx['generate_task_id'])) {
  993. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  994. 'status' => 'failed',
  995. 'error_message' => $e->getMessage(),
  996. 'completed_at' => date('Y-m-d H:i:s'),
  997. 'updated_at' => date('Y-m-d H:i:s'),
  998. ]);
  999. }
  1000. yield [
  1001. 'type' => 'error',
  1002. 'message' => $e->getMessage(),
  1003. ];
  1004. }
  1005. }
  1006. /**
  1007. * 从模型输出中提取标准 JSON(剥离 markdown 代码块及前后说明文字)
  1008. *
  1009. * @param string $content
  1010. * @return string
  1011. */
  1012. private function extractJsonContent(string $content): string
  1013. {
  1014. $content = trim($content);
  1015. if ($content === '') {
  1016. return $content;
  1017. }
  1018. // 剥离 ```json ... ``` 代码块
  1019. if (preg_match('/```(?:json)?\s*(.*?)```/s', $content, $m)) {
  1020. $content = trim($m[1]);
  1021. }
  1022. // 提取第一个 { 到最后一个 } 之间的内容(去除前后说明文字)
  1023. $first = strpos($content, '{');
  1024. $last = strrpos($content, '}');
  1025. if ($first !== false && $last !== false && $last > $first) {
  1026. $content = substr($content, $first, $last - $first + 1);
  1027. }
  1028. // 校验是否为合法 JSON,非法则原样返回(不强行截断)
  1029. json_decode($content, true);
  1030. if (json_last_error() !== JSON_ERROR_NONE) {
  1031. return trim($content);
  1032. }
  1033. return $content;
  1034. }
  1035. /**
  1036. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  1037. *
  1038. * @param array $data 请求参数
  1039. * @return array 返回结果数组
  1040. */
  1041. public function newGenerateText($data) {
  1042. // stream=1 时改为流式请求大模型(输出格式参考 generateText:yield type=content/reasoning/done)
  1043. if ((int)getProp($data, 'stream', 0) === 1) {
  1044. return $this->newGenerateTextStream($data);
  1045. }
  1046. // 获取请求参数
  1047. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  1048. $messages = getProp($data, 'messages', []);
  1049. $systemPrompt = getProp($data, 'system_prompt', '');
  1050. $prompt = getProp($data, 'prompt', '');
  1051. $images = getProp($data, 'images', []); // 支持多张图片
  1052. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  1053. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  1054. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  1055. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  1056. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  1057. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  1058. $generateTaskId = 0;
  1059. $uid = Site::getUid();
  1060. if ($script_id > 0) {
  1061. $existingTask = DB::table('mp_script_generate_tasks')
  1062. ->where('uid', $uid)
  1063. ->where('script_id', $script_id)
  1064. ->orderByDesc('id')
  1065. ->first();
  1066. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  1067. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  1068. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  1069. }
  1070. }
  1071. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  1072. $originalContent = '';
  1073. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  1074. if ($script_id > 0) {
  1075. $script = DB::table('mp_scripts')
  1076. ->where('id', $script_id)
  1077. ->where('is_deleted', 0)
  1078. ->first();
  1079. if (!$script) {
  1080. Utils::throwError('20003:剧本不存在或已删除');
  1081. }
  1082. $originalContent = $script->content ?? '';
  1083. if (empty($originalContent)) {
  1084. Utils::throwError('20003:剧本内容为空');
  1085. }
  1086. $hasValidScript = true;
  1087. // 将剧本内容添加到提示词前面
  1088. if (!empty($originalContent)) {
  1089. if (!empty($prompt)) {
  1090. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  1091. } else {
  1092. $prompt = "原文内容:\n" . $originalContent;
  1093. }
  1094. }
  1095. }
  1096. // 新增: 如果提供了template_id,从数据库获取template_prompt
  1097. if ($templateId > 0) {
  1098. $template = DB::table('mp_prompt_templates')
  1099. ->where('id', $templateId)
  1100. ->where('is_deleted', 0)
  1101. ->first();
  1102. if (!$template) {
  1103. Utils::throwError('20003:模板不存在或已删除');
  1104. }
  1105. $templatePrompt = $template->template_prompt ?? '';
  1106. // 将模板提示词和用户输入的prompt组合
  1107. // 模板为准,用户输入作为补充要求
  1108. if (!empty($templatePrompt)) {
  1109. if (!empty($prompt)) {
  1110. $prompt = $templatePrompt . "\n\n" . $prompt;
  1111. } else {
  1112. $prompt = $templatePrompt;
  1113. }
  1114. }
  1115. }
  1116. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  1117. if (empty($messages)) {
  1118. $messages = [];
  1119. // 添加系统提示词
  1120. if (!empty($systemPrompt)) {
  1121. $messages[] = [
  1122. 'role' => 'system',
  1123. 'content' => $systemPrompt
  1124. ];
  1125. }
  1126. // 构建用户消息内容(支持文本+图片)
  1127. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1128. $userMessage = [
  1129. 'role' => 'user',
  1130. 'content' => []
  1131. ];
  1132. // 添加文本内容
  1133. if (!empty($prompt)) {
  1134. $userMessage['content'][] = [
  1135. 'type' => 'text',
  1136. 'text' => $prompt
  1137. ];
  1138. }
  1139. // 处理上传的图片文件
  1140. if (!empty($images)) {
  1141. if (!is_array($images)) {
  1142. $images = [$images];
  1143. }
  1144. foreach ($images as $image) {
  1145. $imageBase64 = $this->processImageToBase64($image);
  1146. if ($imageBase64) {
  1147. $userMessage['content'][] = [
  1148. 'type' => 'image_url',
  1149. 'image_url' => [
  1150. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  1151. ]
  1152. ];
  1153. }
  1154. }
  1155. }
  1156. // 处理图片URL
  1157. if (!empty($imageUrls)) {
  1158. if (!is_array($imageUrls)) {
  1159. $imageUrls = [$imageUrls];
  1160. }
  1161. foreach ($imageUrls as $url) {
  1162. if (!empty($url)) {
  1163. $userMessage['content'][] = [
  1164. 'type' => 'image_url',
  1165. 'image_url' => [
  1166. 'url' => $url
  1167. ]
  1168. ];
  1169. }
  1170. }
  1171. }
  1172. // 如果只有文本内容,简化为字符串格式
  1173. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  1174. $userMessage['content'] = $userMessage['content'][0]['text'];
  1175. }
  1176. $messages[] = $userMessage;
  1177. }
  1178. }
  1179. // 验证messages不为空
  1180. if (empty($messages)) {
  1181. Utils::throwError('20003:请提供有效的对话内容');
  1182. }
  1183. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1184. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1185. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1186. if ($model === 'deepseek-chat') {
  1187. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1188. $model = 'deepseek-v4-flash';
  1189. $thinkingMode = 'disabled';
  1190. } elseif ($model === 'deepseek-reasoner') {
  1191. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1192. $model = 'deepseek-v4-flash';
  1193. $thinkingMode = 'enabled';
  1194. }
  1195. // 构建请求参数(非流式)
  1196. $post_data = [
  1197. 'model' => $model,
  1198. 'messages' => $messages,
  1199. 'temperature' => getProp($data, 'temperature', 1),
  1200. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  1201. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  1202. 'thinking' => ['type' => $thinkingMode],
  1203. 'stream' => false // 非流式输出
  1204. ];
  1205. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1206. // 添加可选参数
  1207. if (isset($data['top_p'])) {
  1208. $post_data['top_p'] = $data['top_p'];
  1209. }
  1210. // 新增: 根据response_format设置响应格式
  1211. if ($responseFormat === 'json') {
  1212. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  1213. $hasJsonKeyword = false;
  1214. foreach ($post_data['messages'] as $message) {
  1215. if (isset($message['content'])) {
  1216. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  1217. if (stripos($content, 'json') !== false) {
  1218. $hasJsonKeyword = true;
  1219. break;
  1220. }
  1221. }
  1222. }
  1223. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  1224. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  1225. if (!$hasJsonKeyword) {
  1226. $lastMessageIndex = count($post_data['messages']) - 1;
  1227. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  1228. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  1229. // 如果content是字符串,直接追加
  1230. if (is_string($lastContent)) {
  1231. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  1232. }
  1233. // 如果content是数组(包含文本和图片),在文本部分追加
  1234. else if (is_array($lastContent)) {
  1235. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  1236. if ($contentPart['type'] === 'text') {
  1237. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  1238. break;
  1239. }
  1240. }
  1241. }
  1242. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  1243. }
  1244. }
  1245. // 设置response_format参数(所有支持的模型)
  1246. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1247. // DeepSeek模型
  1248. $post_data['response_format'] = ['type' => 'json_object'];
  1249. } else if (in_array($model, $this->gpt_text_models)) {
  1250. // GPT模型
  1251. $post_data['response_format'] = ['type' => 'json_object'];
  1252. } else if (in_array($model, $this->valid_text_models)) {
  1253. // 火山引擎模型
  1254. $post_data['response_format'] = ['type' => 'json_object'];
  1255. }
  1256. }
  1257. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  1258. if ($script_id > 0) {
  1259. $uid = Site::getUid();
  1260. // 创建新的生成任务
  1261. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  1262. 'uid' => $uid,
  1263. 'script_id' => $script_id,
  1264. 'sequence' => $sequence,
  1265. 'status' => 'processing',
  1266. 'prompt' => getProp($data, 'prompt', ''),
  1267. 'started_at' => date('Y-m-d H:i:s'),
  1268. 'created_at' => date('Y-m-d H:i:s'),
  1269. 'updated_at' => date('Y-m-d H:i:s')
  1270. ]);
  1271. }
  1272. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  1273. if ($hasValidScript) {
  1274. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  1275. }
  1276. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  1277. try {
  1278. $aiResult = null;
  1279. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1280. // DeepSeek 官方模型使用现有的 chatOnly 方法
  1281. $result = $this->chatOnly($post_data);
  1282. // 记录实际使用的模型
  1283. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  1284. $aiResult = [
  1285. 'content' => $result['fullContent'],
  1286. 'reasoning_content' => $result['fullReasoningContent'],
  1287. 'usage' => $result['usage'],
  1288. 'model' => $model,
  1289. 'finish_reason' => 'stop'
  1290. ];
  1291. } else if (in_array($model, $this->gpt_text_models)) {
  1292. // GPT 模型使用现有的 gpt54ChatOnly 方法
  1293. $result = $this->gpt54ChatOnly($post_data);
  1294. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  1295. $aiResult = [
  1296. 'content' => $result['fullContent'],
  1297. 'reasoning_content' => '',
  1298. 'usage' => $result['usage'],
  1299. 'model' => $model,
  1300. 'finish_reason' => 'stop'
  1301. ];
  1302. } else if (in_array($model, $this->gemini_text_models)) {
  1303. // Gemini 模型使用 Gemini API(非流式)
  1304. $result = $this->geminiChatOnly($post_data, $model);
  1305. dLog('deepseek')->info('newGenerateText使用Gemini模型', ['requested_model' => $model]);
  1306. $aiResult = [
  1307. 'content' => $result['fullContent'],
  1308. 'reasoning_content' => $result['fullReasoningContent'] ?? '',
  1309. 'usage' => $result['usage'],
  1310. 'model' => $model,
  1311. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  1312. ];
  1313. } else if (in_array($model, $this->valid_text_models)) {
  1314. // 火山引擎支持的模型使用火山引擎 API(非流式)
  1315. $post_data['stream'] = false;
  1316. $result = $this->volcEngineChatCompletion($post_data);
  1317. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  1318. 'requested_model' => $model,
  1319. 'result_keys' => array_keys($result),
  1320. 'has_fullContent' => isset($result['fullContent']),
  1321. 'has_content' => isset($result['content'])
  1322. ]);
  1323. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  1324. $aiResult = [
  1325. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  1326. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  1327. 'usage' => $result['usage'] ?? [],
  1328. 'model' => $model,
  1329. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  1330. ];
  1331. } else {
  1332. Utils::throwError('20003:不支持的模型: ' . $model);
  1333. }
  1334. } catch (\Exception $e) {
  1335. // 生成失败,更新任务状态
  1336. if ($generateTaskId) {
  1337. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1338. 'status' => 'failed',
  1339. 'error_message' => $e->getMessage(),
  1340. 'completed_at' => date('Y-m-d H:i:s'),
  1341. 'updated_at' => date('Y-m-d H:i:s')
  1342. ]);
  1343. }
  1344. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  1345. }
  1346. // 生成成功,更新任务状态
  1347. if ($generateTaskId && $aiResult) {
  1348. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1349. 'status' => 'success',
  1350. 'result' => getProp($aiResult, 'content', ''),
  1351. 'completed_at' => date('Y-m-d H:i:s'),
  1352. 'updated_at' => date('Y-m-d H:i:s')
  1353. ]);
  1354. $aiResult['generate_task_id'] = $generateTaskId;
  1355. }
  1356. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  1357. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  1358. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  1359. 'model' => $model,
  1360. 'script_id' => $script_id,
  1361. 'sequence' => $sequence,
  1362. 'source' => 'newGenerateText',
  1363. ]);
  1364. }
  1365. // 新增: 如果提供了script_id,保存对话记录
  1366. if ($script_id > 0 && $aiResult) {
  1367. try {
  1368. $uid = Site::getUid();
  1369. $now = now();
  1370. // 获取用户原始的prompt(不包含剧本内容)
  1371. $originalPrompt = getProp($data, 'prompt', '');
  1372. $recordsToInsert = [
  1373. [
  1374. 'uid' => $uid,
  1375. 'script_id' => $script_id,
  1376. 'sequence' => $sequence,
  1377. 'role' => 'user',
  1378. 'content' => $originalPrompt,
  1379. 'created_at' => $now,
  1380. 'updated_at' => $now,
  1381. ],
  1382. [
  1383. 'uid' => $uid,
  1384. 'script_id' => $script_id,
  1385. 'sequence' => $sequence,
  1386. 'role' => 'assistant',
  1387. 'content' => $aiResult['content'],
  1388. 'created_at' => $now,
  1389. 'updated_at' => $now,
  1390. ]
  1391. ];
  1392. DB::table('mp_script_records')->insert($recordsToInsert);
  1393. // 获取刚插入的记录ID(假设按插入顺序返回)
  1394. $insertedRecords = DB::table('mp_script_records')
  1395. ->where('uid', $uid)
  1396. ->where('script_id', $script_id)
  1397. ->where('sequence', $sequence)
  1398. ->orderBy('id', 'desc')
  1399. ->limit(2)
  1400. ->get()
  1401. ->map(function ($record) {
  1402. return [
  1403. 'rid' => $record->id,
  1404. 'script_id' => $record->script_id,
  1405. 'sequence' => $record->sequence,
  1406. 'role' => $record->role,
  1407. 'content' => $record->content,
  1408. 'created_at' => $record->created_at,
  1409. ];
  1410. })
  1411. ->reverse()
  1412. ->values()
  1413. ->toArray();
  1414. // 将记录信息添加到返回结果中
  1415. $aiResult['records'] = $insertedRecords;
  1416. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  1417. } catch (\Exception $e) {
  1418. // 记录错误但不影响主流程
  1419. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  1420. }
  1421. }
  1422. return $aiResult;
  1423. }
  1424. /**
  1425. * 通用 Gemini 文生文方法(支持流式和非流式)
  1426. *
  1427. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  1428. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  1429. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  1430. * system_prompt 系统提示词(可选)
  1431. * prompt 用户提示词(可选)
  1432. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  1433. * image_urls 图片/视频URL列表(可选,同上)
  1434. * temperature 温度(可选,默认 1)
  1435. * top_p 核采样(可选)
  1436. * max_tokens 最大输出 token(可选,默认 8192)
  1437. * response_format text/json(可选)
  1438. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  1439. * thinking_budget 思考预算(可选,默认 20)
  1440. * stream 是否流式(可选,默认 false)
  1441. *
  1442. * @param array $data 请求参数
  1443. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  1444. */
  1445. public function geminiGenerateText($data) {
  1446. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  1447. $isStream = (bool)getProp($data, 'stream', false);
  1448. if (!in_array($model, $this->gemini_text_models)) {
  1449. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  1450. }
  1451. $requestData = $this->buildGeminiRequestBody($data, $model);
  1452. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  1453. if ($isStream) {
  1454. // 流式返回生成器,成功后记录 token 使用明细(不扣积分)
  1455. return $this->wrapGenerateTextTokenRecord(
  1456. $this->geminiStreamResponse($requestData, $model),
  1457. $this->getCurrentUid(),
  1458. $model,
  1459. 'geminiGenerateText'
  1460. );
  1461. }
  1462. // 非流式:成功后记录 token 使用明细(不扣积分)
  1463. $result = $this->geminiChatOnly($requestData, $model);
  1464. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  1465. 'model' => $model,
  1466. 'source' => 'geminiGenerateText',
  1467. ], $model);
  1468. return $result;
  1469. }
  1470. /**
  1471. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  1472. */
  1473. private function geminiMediaMaxBytes() {
  1474. return 14 * 1024 * 1024;
  1475. }
  1476. /**
  1477. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  1478. */
  1479. private function buildGeminiRequestBody($data, $model) {
  1480. $messages = getProp($data, 'messages', []);
  1481. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  1482. if (empty($messages)) {
  1483. $systemPrompt = getProp($data, 'system_prompt', '');
  1484. $prompt = getProp($data, 'prompt', '');
  1485. $images = getProp($data, 'images', []);
  1486. $imageUrls = getProp($data, 'image_urls', []);
  1487. $messages = [];
  1488. if (!empty($systemPrompt)) {
  1489. $messages[] = [
  1490. 'role' => 'system',
  1491. 'content' => $systemPrompt
  1492. ];
  1493. }
  1494. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1495. $userMessage = ['role' => 'user', 'content' => []];
  1496. if (!empty($prompt)) {
  1497. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  1498. }
  1499. if (!empty($images)) {
  1500. if (!is_array($images)) {
  1501. $images = [$images];
  1502. }
  1503. foreach ($images as $image) {
  1504. $inlineData = $this->processMediaToInlineData($image);
  1505. if ($inlineData) {
  1506. $userMessage['content'][] = [
  1507. 'type' => 'image',
  1508. 'inline_data' => $inlineData
  1509. ];
  1510. }
  1511. }
  1512. }
  1513. if (!empty($imageUrls)) {
  1514. if (!is_array($imageUrls)) {
  1515. $imageUrls = [$imageUrls];
  1516. }
  1517. foreach ($imageUrls as $url) {
  1518. if (!empty($url)) {
  1519. $inlineData = $this->processMediaToInlineData($url);
  1520. if ($inlineData) {
  1521. $userMessage['content'][] = [
  1522. 'type' => 'image',
  1523. 'inline_data' => $inlineData
  1524. ];
  1525. }
  1526. }
  1527. }
  1528. }
  1529. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  1530. $userMessage['content'] = $userMessage['content'][0]['text'];
  1531. }
  1532. $messages[] = $userMessage;
  1533. }
  1534. }
  1535. if (empty($messages)) {
  1536. Utils::throwError('20003:请提供有效的对话内容');
  1537. }
  1538. // 转换为 Gemini contents 格式
  1539. $systemInstruction = '';
  1540. $contents = [];
  1541. foreach ($messages as $message) {
  1542. $role = getProp($message, 'role', 'user');
  1543. $content = getProp($message, 'content', '');
  1544. if ($role === 'system') {
  1545. if (is_array($content)) {
  1546. $systemInstruction = $this->extractGeminiTextFromParts($content);
  1547. } else {
  1548. $systemInstruction = (string)$content;
  1549. }
  1550. continue;
  1551. }
  1552. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  1553. $parts = [];
  1554. if (is_array($content)) {
  1555. foreach ($content as $part) {
  1556. $partType = getProp($part, 'type', 'text');
  1557. if ($partType === 'text') {
  1558. $text = (string)getProp($part, 'text', '');
  1559. if ($text !== '') {
  1560. $parts[] = ['text' => $text];
  1561. }
  1562. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  1563. if (in_array($partType, ['image_url', 'video_url'])) {
  1564. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  1565. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  1566. } elseif (isset($part['inline_data'])) {
  1567. // 已处理过的 inline_data 直接使用
  1568. $parts[] = ['inline_data' => $part['inline_data']];
  1569. continue;
  1570. } else {
  1571. $url = '';
  1572. }
  1573. $inlineData = $this->processMediaToInlineData($url);
  1574. if ($inlineData) {
  1575. $parts[] = ['inline_data' => $inlineData];
  1576. }
  1577. }
  1578. }
  1579. } else {
  1580. $text = (string)$content;
  1581. if ($text !== '') {
  1582. $parts[] = ['text' => $text];
  1583. }
  1584. }
  1585. if (!empty($parts)) {
  1586. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  1587. }
  1588. }
  1589. if (empty($contents)) {
  1590. Utils::throwError('20003:请提供有效的对话内容');
  1591. }
  1592. // 构建生成配置
  1593. $generationConfig = [];
  1594. if (getProp($data, 'temperature', null) !== null) {
  1595. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  1596. }
  1597. if (getProp($data, 'top_p', null) !== null) {
  1598. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  1599. }
  1600. if (getProp($data, 'frequency_penalty', null) !== null) {
  1601. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  1602. }
  1603. if (getProp($data, 'presence_penalty', null) !== null) {
  1604. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  1605. }
  1606. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  1607. if ($maxOutputTokens <= 0) {
  1608. $maxOutputTokens = 8192;
  1609. }
  1610. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  1611. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  1612. $maxOutputTokens = 32768;
  1613. }
  1614. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  1615. // response_format 映射:text -> text/plain,json -> application/json
  1616. $responseFormat = getProp($data, 'response_format', 'text');
  1617. if (is_array($responseFormat)) {
  1618. $responseFormat = getProp($responseFormat, 'type', 'text');
  1619. }
  1620. if (in_array($responseFormat, ['json', 'json_object'])) {
  1621. $generationConfig['responseMimeType'] = 'application/json';
  1622. } else {
  1623. $generationConfig['responseMimeType'] = 'text/plain';
  1624. }
  1625. $requestData = [
  1626. 'contents' => $contents,
  1627. 'generationConfig' => $generationConfig,
  1628. ];
  1629. if ($systemInstruction !== '') {
  1630. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  1631. }
  1632. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  1633. $thinkingMode = getProp($data, 'thinking', null);
  1634. if (is_array($thinkingMode)) {
  1635. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  1636. }
  1637. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  1638. if ($thinkingMode === null) {
  1639. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  1640. }
  1641. if ($thinkingMode === 'enabled') {
  1642. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  1643. if ($thinkingBudget <= 0) {
  1644. $thinkingBudget = 20;
  1645. }
  1646. $requestData['generationConfig']['thinkingConfig'] = [
  1647. 'thinkingBudget' => $thinkingBudget
  1648. ];
  1649. } elseif ($defaultThinking) {
  1650. // 该模型仅支持思考模式,传 0 会返回 400
  1651. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  1652. } else {
  1653. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  1654. }
  1655. return $requestData;
  1656. }
  1657. /**
  1658. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  1659. *
  1660. * 模型名 -> env 变量名映射:
  1661. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  1662. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  1663. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  1664. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  1665. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  1666. */
  1667. private function getGeminiApiKey($model) {
  1668. $map = [
  1669. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  1670. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  1671. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  1672. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  1673. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  1674. ];
  1675. if (isset($map[$model])) {
  1676. $key = env($map[$model]);
  1677. if (!empty($key)) {
  1678. return $key;
  1679. }
  1680. }
  1681. return env('GEMINI_API_KEY', '');
  1682. }
  1683. /**
  1684. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  1685. */
  1686. private function geminiChatOnly($requestData, $model) {
  1687. $apiKey = $this->getGeminiApiKey($model);
  1688. if (empty($apiKey)) {
  1689. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1690. }
  1691. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1692. if (isset($requestData['messages'])) {
  1693. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1694. }
  1695. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1696. . '/models/' . $model . ':generateContent';
  1697. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1698. $headers = [
  1699. 'Authorization' => 'Bearer ' . $apiKey,
  1700. 'Content-Type' => 'application/json'
  1701. ];
  1702. $maxRetries = $this->gptRetryTimes();
  1703. $interval = $this->gptRetryInterval();
  1704. $attempt = 0;
  1705. while (true) {
  1706. try {
  1707. $response = $client->post($url, [
  1708. 'json' => $requestData,
  1709. 'headers' => $headers
  1710. ]);
  1711. $responseArr = json_decode($response->getBody()->getContents(), true);
  1712. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  1713. $fullContent = $this->extractGeminiContent($responseArr);
  1714. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  1715. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  1716. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  1717. ? $responseArr['candidates'][0]['finishReason']
  1718. : '';
  1719. return [
  1720. 'fullContent' => $fullContent,
  1721. 'fullReasoningContent' => $fullReasoningContent,
  1722. 'usage' => $usage,
  1723. 'finish_reason' => $finishReason
  1724. ];
  1725. } catch (\Exception $e) {
  1726. $retryable = true;
  1727. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1728. $status = $e->getResponse()->getStatusCode();
  1729. $retryable = $status >= 500 || $status == 429;
  1730. }
  1731. if (!$retryable || $attempt >= $maxRetries) {
  1732. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  1733. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  1734. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  1735. }
  1736. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  1737. 'retry' => $attempt + 1,
  1738. 'max_retries' => $maxRetries,
  1739. 'error' => $e->getMessage()
  1740. ]);
  1741. sleep($interval);
  1742. $attempt++;
  1743. }
  1744. }
  1745. }
  1746. /**
  1747. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  1748. */
  1749. private function geminiStreamResponse($requestData, $model) {
  1750. $apiKey = $this->getGeminiApiKey($model);
  1751. if (empty($apiKey)) {
  1752. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1753. }
  1754. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1755. if (isset($requestData['messages'])) {
  1756. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1757. }
  1758. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1759. . '/models/' . $model . ':generateContent?alt=sse';
  1760. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1761. $headers = [
  1762. 'Authorization' => 'Bearer ' . $apiKey,
  1763. 'Content-Type' => 'application/json'
  1764. ];
  1765. try {
  1766. $response = $client->post($url, [
  1767. 'json' => $requestData,
  1768. 'headers' => $headers,
  1769. 'stream' => true
  1770. ]);
  1771. $body = $response->getBody();
  1772. $fullContent = '';
  1773. $fullReasoningContent = '';
  1774. $usage = [];
  1775. $buffer = '';
  1776. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1777. while (!$body->eof()) {
  1778. $chunk = $body->read(1024);
  1779. $buffer .= $chunk;
  1780. $lines = explode("\n", $buffer);
  1781. $buffer = array_pop($lines);
  1782. foreach ($lines as $line) {
  1783. $line = trim($line);
  1784. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1785. continue;
  1786. }
  1787. $data = substr($line, 6);
  1788. if ($data === '[DONE]') {
  1789. break 2;
  1790. }
  1791. try {
  1792. $json = json_decode($data, true);
  1793. if (json_last_error() !== JSON_ERROR_NONE) {
  1794. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1795. continue;
  1796. }
  1797. // 思考内容(thoughts)
  1798. $thoughts = $this->extractGeminiThoughts($json);
  1799. if ($thoughts !== '') {
  1800. $fullReasoningContent .= $thoughts;
  1801. yield [
  1802. 'type' => 'reasoning',
  1803. 'content' => $thoughts,
  1804. 'full_reasoning' => $fullReasoningContent
  1805. ];
  1806. }
  1807. // 回答内容
  1808. $partText = $this->extractGeminiContent($json);
  1809. if ($partText !== '') {
  1810. $fullContent .= $partText;
  1811. yield [
  1812. 'type' => 'content',
  1813. 'content' => $partText,
  1814. ];
  1815. }
  1816. // 使用统计
  1817. if (isset($json['usageMetadata'])) {
  1818. $usage = $json['usageMetadata'];
  1819. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  1820. }
  1821. } catch (\Exception $e) {
  1822. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1823. continue;
  1824. }
  1825. }
  1826. }
  1827. dLog('deepseek')->info('Gemini流式读取完成', [
  1828. 'content_length' => strlen($fullContent),
  1829. 'reasoning_length' => strlen($fullReasoningContent)
  1830. ]);
  1831. yield [
  1832. 'type' => 'done',
  1833. 'full_content' => $fullContent,
  1834. 'full_reasoning' => $fullReasoningContent,
  1835. 'usage' => $usage
  1836. ];
  1837. } catch (\Exception $e) {
  1838. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  1839. yield [
  1840. 'type' => 'error',
  1841. 'msg' => $e->getMessage(),
  1842. 'code' => $e->getCode()
  1843. ];
  1844. }
  1845. }
  1846. /**
  1847. * 从 Gemini 响应中提取回答文本
  1848. */
  1849. private function extractGeminiContent($responseArr) {
  1850. $text = '';
  1851. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  1852. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  1853. if (isset($part['text'])) {
  1854. $text .= $part['text'];
  1855. }
  1856. }
  1857. }
  1858. return $text;
  1859. }
  1860. /**
  1861. * 从 Gemini 响应中提取思考内容
  1862. */
  1863. private function extractGeminiReasoningContent($responseArr) {
  1864. $reasoning = '';
  1865. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1866. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1867. if (isset($thought['text'])) {
  1868. $reasoning .= $thought['text'];
  1869. }
  1870. }
  1871. }
  1872. return $reasoning;
  1873. }
  1874. /**
  1875. * 从 Gemini 流式响应中提取本次增量思考内容
  1876. */
  1877. private function extractGeminiThoughts($responseArr) {
  1878. $thoughts = '';
  1879. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1880. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1881. if (isset($thought['text'])) {
  1882. $thoughts .= $thought['text'];
  1883. }
  1884. }
  1885. }
  1886. return $thoughts;
  1887. }
  1888. /**
  1889. * 提取消息数组中的纯文本
  1890. */
  1891. private function extractGeminiTextFromParts($parts) {
  1892. $text = '';
  1893. if (is_array($parts)) {
  1894. foreach ($parts as $part) {
  1895. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  1896. $text .= (string)getProp($part, 'text', '');
  1897. }
  1898. }
  1899. }
  1900. return $text;
  1901. }
  1902. /**
  1903. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  1904. *
  1905. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  1906. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  1907. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  1908. *
  1909. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  1910. * @return array|null ['mime_type' => string, 'data' => string]
  1911. */
  1912. private function processMediaToInlineData($media) {
  1913. if (empty($media)) {
  1914. return null;
  1915. }
  1916. $localPath = null;
  1917. $isTempFile = false;
  1918. try {
  1919. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  1920. if (is_string($media) && strpos($media, 'data:') === 0) {
  1921. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  1922. return [
  1923. 'mime_type' => $matches[1],
  1924. 'data' => $matches[2]
  1925. ];
  1926. }
  1927. return null;
  1928. }
  1929. // 2. 获取本地文件路径
  1930. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  1931. $localPath = $this->downloadMediaToTemp($media);
  1932. $isTempFile = true;
  1933. } elseif (is_string($media)) {
  1934. $localPath = $media;
  1935. } else {
  1936. // Laravel UploadedFile 对象
  1937. $localPath = $media->getRealPath();
  1938. }
  1939. if (!$localPath || !file_exists($localPath)) {
  1940. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  1941. return null;
  1942. }
  1943. $fileSize = filesize($localPath);
  1944. $maxBytes = $this->geminiMediaMaxBytes();
  1945. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  1946. $mimeType = $this->detectMediaMime($localPath);
  1947. $isVideo = strpos($mimeType, 'video/') === 0;
  1948. $needCompress = $fileSize > $maxBytes;
  1949. $duration = 0;
  1950. if ($isVideo) {
  1951. $duration = $this->getMediaDuration($localPath);
  1952. if ($duration > 300) {
  1953. $needCompress = true;
  1954. }
  1955. }
  1956. $finalPath = $localPath;
  1957. $compressedPath = null;
  1958. if ($needCompress && $this->ffmpegAvailable()) {
  1959. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  1960. if ($compressed && file_exists($compressed)) {
  1961. $compressedPath = $compressed;
  1962. if (filesize($compressed) < $fileSize || $isVideo) {
  1963. $finalPath = $compressed;
  1964. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  1965. } else {
  1966. @unlink($compressed);
  1967. $compressedPath = null;
  1968. }
  1969. }
  1970. }
  1971. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  1972. $finalSize = filesize($finalPath);
  1973. if ($finalSize > $maxBytes) {
  1974. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  1975. 'path' => $localPath,
  1976. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  1977. 'limit_mb' => 14
  1978. ]);
  1979. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  1980. }
  1981. // 兜底校验:视频时长超过5分钟且未能压缩成功
  1982. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  1983. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  1984. }
  1985. $data = base64_encode(file_get_contents($finalPath));
  1986. return [
  1987. 'mime_type' => $mimeType,
  1988. 'data' => $data
  1989. ];
  1990. } catch (\App\Exceptions\ApiException $e) {
  1991. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  1992. throw $e;
  1993. } catch (\Exception $e) {
  1994. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  1995. return null;
  1996. } finally {
  1997. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  1998. @unlink($compressedPath);
  1999. }
  2000. if ($isTempFile && $localPath && file_exists($localPath)) {
  2001. @unlink($localPath);
  2002. }
  2003. }
  2004. }
  2005. /**
  2006. * 下载远程多媒体到临时目录
  2007. *
  2008. * @return string|null 本地临时文件路径
  2009. */
  2010. private function downloadMediaToTemp($url) {
  2011. try {
  2012. $tempDir = storage_path('app/temp/gemini');
  2013. if (!is_dir($tempDir)) {
  2014. mkdir($tempDir, 0775, true);
  2015. }
  2016. $extension = 'tmp';
  2017. $pathInfo = parse_url($url, PHP_URL_PATH);
  2018. if ($pathInfo) {
  2019. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  2020. if ($ext && strlen($ext) <= 10) {
  2021. $extension = strtolower($ext);
  2022. }
  2023. }
  2024. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  2025. $client = new Client(['timeout' => 300, 'verify' => false]);
  2026. $response = $client->get($url, ['sink' => $tmpFile]);
  2027. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  2028. @unlink($tmpFile);
  2029. return null;
  2030. }
  2031. return $tmpFile;
  2032. } catch (\Exception $e) {
  2033. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  2034. return null;
  2035. }
  2036. }
  2037. /**
  2038. * 检测多媒体文件 MIME 类型
  2039. */
  2040. private function detectMediaMime($filePath) {
  2041. $imageInfo = @getimagesize($filePath);
  2042. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  2043. return $imageInfo['mime'];
  2044. }
  2045. // 视频按扩展名粗略判断
  2046. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  2047. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  2048. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  2049. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  2050. if (isset($videoExts[$ext])) {
  2051. return $videoExts[$ext];
  2052. }
  2053. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  2054. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  2055. if (isset($imageExts[$ext])) {
  2056. return $imageExts[$ext];
  2057. }
  2058. return 'application/octet-stream';
  2059. }
  2060. /**
  2061. * 获取多媒体时长(秒),非视频或失败返回 0
  2062. */
  2063. private function getMediaDuration($filePath) {
  2064. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  2065. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  2066. $output = trim((string)shell_exec($cmd));
  2067. $duration = (float)$output;
  2068. return $duration > 0 ? $duration : 0;
  2069. }
  2070. /**
  2071. * 检查 ffmpeg 是否可用
  2072. */
  2073. private function ffmpegAvailable() {
  2074. static $available = null;
  2075. if ($available !== null) {
  2076. return $available;
  2077. }
  2078. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2079. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  2080. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  2081. $available = false;
  2082. return $available;
  2083. }
  2084. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  2085. $output = shell_exec($cmd);
  2086. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  2087. return $available;
  2088. }
  2089. /**
  2090. * 使用 ffmpeg 压缩多媒体文件
  2091. *
  2092. * @param string $inputFile 输入文件路径
  2093. * @param bool $isVideo 是否为视频
  2094. * @param float $duration 视频时长(秒),非视频传 0
  2095. * @return string|null 压缩后的文件路径,失败返回 null
  2096. */
  2097. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  2098. try {
  2099. $tempDir = storage_path('app/temp/gemini');
  2100. if (!is_dir($tempDir)) {
  2101. mkdir($tempDir, 0775, true);
  2102. }
  2103. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2104. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  2105. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  2106. if ($isVideo) {
  2107. // 视频:时长超过5分钟则加速压缩到5分钟以内
  2108. $speedFactor = 1.0;
  2109. if ($duration > 300) {
  2110. $speedFactor = $duration / 300;
  2111. }
  2112. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  2113. $finalDuration = $duration / max(1.0, $speedFactor);
  2114. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  2115. $targetBitrate = max(300, min(6000, $targetBitrate));
  2116. $filters = [];
  2117. $filters[] = 'scale=min(1280,iw):-2';
  2118. $filters[] = 'fps=24';
  2119. if ($speedFactor > 1.0) {
  2120. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  2121. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  2122. $fullCount = (int)ceil($speedFactor / 2.0);
  2123. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2124. if ($lastTempo < 0.5) {
  2125. $fullCount++;
  2126. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2127. }
  2128. for ($i = 0; $i < $fullCount; $i++) {
  2129. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  2130. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  2131. }
  2132. }
  2133. $filterStr = implode(',', $filters);
  2134. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  2135. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  2136. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  2137. } else {
  2138. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  2139. $imageInfo = @getimagesize($inputFile);
  2140. $scaleW = 2048;
  2141. $scaleH = 2048;
  2142. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  2143. if ($imageInfo[0] >= $imageInfo[1]) {
  2144. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  2145. $scaleW = 2048;
  2146. } else {
  2147. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  2148. $scaleH = 2048;
  2149. }
  2150. }
  2151. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  2152. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  2153. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  2154. }
  2155. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  2156. $output = shell_exec($cmd);
  2157. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  2158. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  2159. 'input' => $inputFile,
  2160. 'output' => $output
  2161. ]);
  2162. @unlink($outputFile);
  2163. return null;
  2164. }
  2165. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  2166. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  2167. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  2168. ]);
  2169. return $outputFile;
  2170. } catch (\Exception $e) {
  2171. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  2172. return null;
  2173. }
  2174. }
  2175. /**
  2176. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  2177. *
  2178. * @param array $data
  2179. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  2180. */
  2181. public function getScriptGenerateTasks($data) {
  2182. $uid = Site::getUid();
  2183. return DB::table('mp_script_generate_tasks as t')
  2184. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  2185. ->where('t.uid', $uid)
  2186. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  2187. ->orderByDesc('t.id')
  2188. ->paginate(15);
  2189. }
  2190. public function saveScriptChatHistory($data) {
  2191. $uid = Site::getUid();
  2192. $rid = getProp($data, 'rid');
  2193. $script_id = getProp($data, 'script_id');
  2194. $sequence = getProp($data, 'sequence', 0);
  2195. $content = getProp($data, 'content');
  2196. if (!$rid) {
  2197. Utils::throwError('20003:请选择对话记录ID');
  2198. }
  2199. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  2200. if (!$record) {
  2201. Utils::throwError('20003:对话记录不存在');
  2202. }
  2203. if (!$script_id) {
  2204. Utils::throwError('20003:请选择剧本');
  2205. }
  2206. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  2207. if (!$script) {
  2208. Utils::throwError('20003:剧本不存在');
  2209. }
  2210. // 批量插入数据
  2211. return DB::table('mp_script_records')->where('id', $rid)->update([
  2212. 'content' => $content,
  2213. 'updated_at' => date('Y-m-d H:i:s')
  2214. ]);
  2215. }
  2216. /**
  2217. * 获取剧本的历史对话记录
  2218. *
  2219. * @param array $data 请求参数
  2220. * @return array 返回历史记录数组
  2221. */
  2222. public function getScriptChatHistory($data) {
  2223. $uid = Site::getUid();
  2224. $script_id = getProp($data, 'script_id');
  2225. $rid = getProp($data, 'rid');
  2226. $sequence = getProp($data, 'sequence', null);
  2227. if (!$script_id) {
  2228. Utils::throwError('20003:请提供剧本ID');
  2229. }
  2230. // 验证剧本是否存在
  2231. $script = DB::table('mp_scripts')
  2232. ->where('id', $script_id)
  2233. ->where('is_deleted', 0)
  2234. ->first();
  2235. if (!$script) {
  2236. Utils::throwError('20003:剧本不存在');
  2237. }
  2238. // 构建查询
  2239. $query = DB::table('mp_script_records')
  2240. ->where('script_id', $script_id);
  2241. // ->where('uid', $uid);
  2242. // 如果提供了 sequence,则过滤指定剧集
  2243. if ($sequence !== null) {
  2244. $query->where('sequence', $sequence);
  2245. }
  2246. // 记录ID筛选
  2247. if ($rid) {
  2248. $query->where('id', $rid);
  2249. }
  2250. // 查询记录并按 id 正序排序
  2251. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  2252. ->orderBy('created_at', 'asc')
  2253. ->orderBy('id', 'asc')
  2254. ->get()
  2255. ->map(function ($record) {
  2256. return [
  2257. 'rid' => $record->id,
  2258. 'script_id' => $record->script_id,
  2259. 'sequence' => $record->sequence,
  2260. 'role' => $record->role,
  2261. 'content' => $record->content,
  2262. 'products' => $record->products ? json_decode($record->products) : [],
  2263. 'created_at' => $record->created_at,
  2264. ];
  2265. })
  2266. ->toArray();
  2267. return $records;
  2268. }
  2269. /**
  2270. * 处理图片转换为base64
  2271. *
  2272. * @param mixed $image 图片文件对象或文件路径
  2273. * @return string|null base64编码的图片数据
  2274. */
  2275. private function processImageToBase64($image) {
  2276. try {
  2277. // 获取文件路径
  2278. if (is_string($image)) {
  2279. $filePath = $image;
  2280. } else {
  2281. // Laravel UploadedFile 对象
  2282. $filePath = $image->getRealPath();
  2283. }
  2284. if (!file_exists($filePath)) {
  2285. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  2286. return null;
  2287. }
  2288. // 验证是否为图片文件
  2289. $imageInfo = @getimagesize($filePath);
  2290. if ($imageInfo === false) {
  2291. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  2292. return null;
  2293. }
  2294. // 读取图片并转换为base64
  2295. $imageData = file_get_contents($filePath);
  2296. $base64Image = base64_encode($imageData);
  2297. dLog('deepseek')->info('图片转换成功', [
  2298. 'size' => strlen($imageData),
  2299. 'type' => $imageInfo['mime']
  2300. ]);
  2301. return $base64Image;
  2302. } catch (\Exception $e) {
  2303. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  2304. return null;
  2305. }
  2306. }
  2307. private function getArtStylePromptMappings($art_style='')
  2308. {
  2309. $arr = [
  2310. '唯美真人风格' => [
  2311. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2312. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  2313. ],
  2314. '真人古风风格' => [
  2315. 'aliases' => ['真人古风风格', '真人古风'],
  2316. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  2317. ],
  2318. '日系动漫风格' => [
  2319. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2320. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  2321. ],
  2322. '国漫风格' => [
  2323. 'aliases' => ['国漫风格', '国漫'],
  2324. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  2325. ],
  2326. 'Q版卡通风格' => [
  2327. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2328. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  2329. ],
  2330. '简约扁平风格' => [
  2331. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2332. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  2333. ],
  2334. '武侠风格' => [
  2335. 'aliases' => ['武侠风格', '武侠'],
  2336. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  2337. ],
  2338. '古风仙侠风格' => [
  2339. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2340. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  2341. ],
  2342. '新中式水墨风格' => [
  2343. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2344. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  2345. ],
  2346. '写实插画风格' => [
  2347. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2348. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  2349. ],
  2350. '3D卡通风格' => [
  2351. 'aliases' => ['3D卡通风格', '3D卡通'],
  2352. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  2353. ],
  2354. '条漫风格' => [
  2355. 'aliases' => ['条漫风格', '条漫'],
  2356. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  2357. ],
  2358. '赛博朋克风格' => [
  2359. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2360. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  2361. ],
  2362. '暗黑悬疑风格' => [
  2363. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2364. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  2365. ],
  2366. '治愈清新风格' => [
  2367. 'aliases' => ['治愈清新风格', '治愈清新'],
  2368. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  2369. ],
  2370. '3D真人风格' => [
  2371. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  2372. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  2373. ],
  2374. ];
  2375. if($art_style) {
  2376. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2377. }
  2378. return $arr;
  2379. $arr = [
  2380. '唯美真人风格' => [
  2381. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2382. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  2383. 2. 色彩色调
  2384. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  2385. 3. 画质精度
  2386. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  2387. 4. 画面观感
  2388. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  2389. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  2390. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  2391. ],
  2392. '真人古风风格' => [
  2393. 'aliases' => ['真人古风风格', '真人古风'],
  2394. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  2395. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  2396. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  2397. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  2398. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  2399. ],
  2400. '日系动漫风格' => [
  2401. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2402. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  2403. 正向提示词(中文)
  2404. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  2405. 必须遵守规则
  2406. • 全程保持日系动漫风格,不混入其他画风
  2407. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  2408. • 画面适配所选画面比例,构图居中,主体突出
  2409. • 线条干净、色彩统一,不杂乱、不突兀
  2410. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  2411. ],
  2412. '国漫风格' => [
  2413. 'aliases' => ['国漫风格', '国漫'],
  2414. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  2415. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  2416. 必须遵守规则
  2417. • 严格保持国漫画风,不串风格、不混画风
  2418. • 角色形象统一,不随意改变五官、身材、服饰
  2419. • 画面构图稳定,适合漫剧叙事展示
  2420. • 色调统一,不出现脏色、杂色
  2421. 禁止/避免词汇
  2422. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  2423. ],
  2424. 'Q版卡通风格' => [
  2425. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2426. 'prompt' => "风格说明
  2427. 头大身小,造型可爱圆润,简约干净
  2428. 正向提示词(中文)
  2429. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  2430. 必须遵守规则
  2431. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  2432. • 角色造型统一,表情可爱,不诡异
  2433. • 画面简洁清爽,无多余复杂元素
  2434. • 色彩明亮柔和,不刺眼
  2435. 禁止/避免词汇
  2436. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  2437. ],
  2438. '简约扁平风格' => [
  2439. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2440. 'prompt' => "风格说明
  2441. 色块简洁、无复杂渐变,现代极简风
  2442. 正向提示词(中文)
  2443. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  2444. 必须遵守规则
  2445. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  2446. • 构图简洁,主体突出,无多余装饰
  2447. • 色彩统一、干净,不杂乱
  2448. 禁止/避免词汇
  2449. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  2450. ],
  2451. '武侠风格' => [
  2452. 'aliases' => ['武侠风格', '武侠'],
  2453. 'prompt' => "风格说明
  2454. 江湖气息,线条硬朗,动作感强
  2455. 正向提示词(中文)
  2456. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  2457. 必须遵守规则
  2458. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  2459. • 角色形象、服饰、身材比例统一
  2460. • 画面动作自然,不扭曲、不畸形
  2461. 禁止/避免词汇
  2462. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  2463. ],
  2464. '古风仙侠风格' => [
  2465. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2466. 'prompt' => "风格说明
  2467. 飘逸汉服、云雾仙气、唯美空灵
  2468. 正向提示词(中文)
  2469. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  2470. 必须遵守规则
  2471. • 保持古风仙侠统一画风,不混入现代、科幻元素
  2472. • 角色服饰、发型、形象前后一致
  2473. • 场景仙气飘逸,色调清雅统一
  2474. • 画面唯美柔和,不阴暗、不诡异
  2475. 禁止/避免词汇
  2476. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  2477. ],
  2478. '新中式水墨风格' => [
  2479. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2480. 'prompt' => "风格说明
  2481. 淡墨渲染,毛笔笔触,留白意境
  2482. 正向提示词(中文)
  2483. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  2484. 必须遵守规则
  2485. • 严格保持水墨质感,不混入厚涂、写实、卡通
  2486. • 色调淡雅统一,不浓艳杂乱
  2487. • 画面干净有意境,不堆砌元素
  2488. 禁止/避免词汇
  2489. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  2490. ],
  2491. '写实插画风格' => [
  2492. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2493. 'prompt' => "风格说明
  2494. 接近真人比例,光影真实,质感细腻
  2495. 正向提示词(中文)
  2496. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  2497. 必须遵守规则
  2498. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  2499. • 角色五官、身材、服饰高度统一
  2500. • 画面清晰、光影自然、不扭曲
  2501. 禁止/避免词汇
  2502. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  2503. ],
  2504. '3D卡通风格' => [
  2505. 'aliases' => ['3D卡通风格', '3D卡通'],
  2506. 'prompt' => "风格说明
  2507. 3D建模质感,柔和渲染,圆润可爱
  2508. 正向提示词(中文)
  2509. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  2510. 必须遵守规则
  2511. • 保持3D卡通统一质感,不出现2D杂乱线条
  2512. • 角色模型、比例、形象前后一致
  2513. • 画面干净,不模糊、不穿模
  2514. 禁止/避免词汇
  2515. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  2516. ],
  2517. '条漫风格' => [
  2518. 'aliases' => ['条漫风格', '条漫'],
  2519. 'prompt' => "风格说明
  2520. 纵向分镜,上下滑动阅读,轻量化
  2521. 正向提示词(中文)
  2522. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  2523. 必须遵守规则
  2524. • 保持条漫纵向阅读逻辑,构图简洁
  2525. • 画风统一,不混写实、3D、水墨
  2526. • 画面干净,不杂乱
  2527. 禁止/避免词汇
  2528. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  2529. ],
  2530. '赛博朋克风格' => [
  2531. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2532. 'prompt' => "风格说明
  2533. 霓虹灯光、未来都市、暗色调、科技机械
  2534. 正向提示词(中文)
  2535. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  2536. 必须遵守规则
  2537. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  2538. • 色调以暗调+霓虹为主,色彩统一
  2539. • 画面科技感强,不杂乱
  2540. 禁止/避免词汇
  2541. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  2542. ],
  2543. '暗黑悬疑风格' => [
  2544. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2545. 'prompt' => "风格说明
  2546. 低饱和、冷色调、阴影重、神秘压抑
  2547. 正向提示词(中文)
  2548. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  2549. 必须遵守规则
  2550. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  2551. • 画面氛围压抑神秘,但不低俗、不血腥
  2552. • 角色形象统一,不崩坏
  2553. 禁止/避免词汇
  2554. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  2555. ],
  2556. '治愈清新风格' => [
  2557. 'aliases' => ['治愈清新风格', '治愈清新'],
  2558. 'prompt' => "风格说明
  2559. 马卡龙色系、柔光、温暖干净
  2560. 正向提示词(中文)
  2561. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  2562. 必须遵守规则
  2563. • 保持治愈清新统一色调,不阴暗、不诡异
  2564. • 画面柔和干净,无杂乱元素
  2565. • 角色形象柔和可爱,不狰狞
  2566. 禁止/避免词汇
  2567. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  2568. ],
  2569. ];
  2570. return $arr;
  2571. }
  2572. public function getArtStylePromptByInput($inputArtStyle): string
  2573. {
  2574. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  2575. if ($normalizedInput === '') {
  2576. return '';
  2577. }
  2578. return $this->getArtStylePromptMappings($normalizedInput);
  2579. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  2580. // foreach ($mapping['aliases'] as $alias) {
  2581. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  2582. // if ($normalizedAlias === '') {
  2583. // continue;
  2584. // }
  2585. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  2586. // return $mapping['prompt'];
  2587. // }
  2588. // }
  2589. // }
  2590. return '';
  2591. }
  2592. public function getArtStyleShortPromptByInput($inputArtStyle) {
  2593. $stylePrefixes = [
  2594. '唯美真人风格' => [
  2595. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  2596. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  2597. ],
  2598. '真人古风风格' => [
  2599. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  2600. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  2601. ],
  2602. '日系动漫风格' => [
  2603. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  2604. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  2605. ],
  2606. '国漫风格' => [
  2607. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  2608. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  2609. ],
  2610. 'Q版卡通风格' => [
  2611. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  2612. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  2613. ],
  2614. '简约扁平风格' => [
  2615. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  2616. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  2617. ],
  2618. '武侠风格' => [
  2619. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  2620. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  2621. ],
  2622. '古风仙侠风格' => [
  2623. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  2624. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  2625. ],
  2626. '新中式水墨风格' => [
  2627. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  2628. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  2629. ],
  2630. '写实插画风格' => [
  2631. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  2632. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  2633. ],
  2634. '3D卡通风格' => [
  2635. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  2636. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  2637. ],
  2638. '条漫风格' => [
  2639. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  2640. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  2641. ],
  2642. '赛博朋克风格' => [
  2643. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  2644. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  2645. ],
  2646. '暗黑悬疑风格' => [
  2647. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  2648. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  2649. ],
  2650. '治愈清新风格' => [
  2651. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  2652. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  2653. ]
  2654. ];
  2655. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  2656. }
  2657. private function normalizeArtStyleInput($value): string
  2658. {
  2659. $value = trim((string)$value);
  2660. if ($value === '') {
  2661. return '';
  2662. }
  2663. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  2664. return mb_strtolower($value, 'UTF-8');
  2665. }
  2666. private function replaceArtStyleSection(string $content, string $artStyle): string
  2667. {
  2668. if ($content === '' || $artStyle === '') {
  2669. return $content;
  2670. }
  2671. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  2672. if (!preg_match($pattern, $content)) {
  2673. return $content;
  2674. }
  2675. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  2676. }
  2677. /**
  2678. * DeepSeek流式输出处理方法
  2679. *
  2680. * @param array $post_data DeepSeek API请求参数
  2681. * @return \Generator 返回生成器,用于流式输出
  2682. */
  2683. private function unwrapJsonWrappedContent($content) {
  2684. $trimmed = ltrim((string)$content);
  2685. if ($trimmed === '' || ($trimmed[0] !== '{' && $trimmed[0] !== '[')) {
  2686. return $content;
  2687. }
  2688. $decoded = json_decode($trimmed, true);
  2689. if (!is_array($decoded)) {
  2690. return $content;
  2691. }
  2692. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2693. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2694. return $decoded[$key];
  2695. }
  2696. }
  2697. return $content;
  2698. }
  2699. private function deepSeekStreamResponse($post_data) {
  2700. // 设置最大输出tokens
  2701. $post_data['max_tokens'] = 300000;
  2702. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2703. $post_data['stream_options'] = ['include_usage' => true];
  2704. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2705. $response = $client->post($this->url, [
  2706. 'json' => $post_data,
  2707. 'headers' => $this->headers,
  2708. 'stream' => true // 启用流式响应
  2709. ]);
  2710. $body = $response->getBody();
  2711. $fullContent = '';
  2712. $fullReasoningContent = '';
  2713. $usage = [];
  2714. $buffer = '';
  2715. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  2716. // 逐行读取流式响应
  2717. while (!$body->eof()) {
  2718. $chunk = $body->read(1024); // 每次读取 1KB
  2719. $buffer .= $chunk;
  2720. // 按行分割
  2721. $lines = explode("\n", $buffer);
  2722. // 保留最后一个不完整的行
  2723. $buffer = array_pop($lines);
  2724. foreach ($lines as $line) {
  2725. $line = trim($line);
  2726. // 跳过空行
  2727. if (empty($line)) {
  2728. continue;
  2729. }
  2730. // 检查是否是 SSE 数据行
  2731. if (strpos($line, 'data: ') !== 0) {
  2732. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2733. continue;
  2734. }
  2735. $data = substr($line, 6); // 移除 "data: " 前缀
  2736. if ($data === '[DONE]') {
  2737. dLog('deepseek')->info('收到结束标记');
  2738. break 2; // 跳出两层循环
  2739. }
  2740. try {
  2741. $json = json_decode($data, true);
  2742. if (json_last_error() !== JSON_ERROR_NONE) {
  2743. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2744. continue;
  2745. }
  2746. if (isset($json['choices'][0]['delta'])) {
  2747. $delta = $json['choices'][0]['delta'];
  2748. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2749. if (isset($delta['reasoning_content'])) {
  2750. $fullReasoningContent .= $delta['reasoning_content'];
  2751. yield [
  2752. 'type' => 'reasoning',
  2753. 'content' => $delta['reasoning_content'],
  2754. 'full_reasoning' => $fullReasoningContent
  2755. ];
  2756. }
  2757. // 处理最终回答内容
  2758. if (isset($delta['content'])) {
  2759. $fullContent .= $delta['content'];
  2760. yield [
  2761. 'type' => 'content',
  2762. 'content' => $delta['content'],
  2763. ];
  2764. }
  2765. }
  2766. // 获取使用统计信息
  2767. if (isset($json['usage'])) {
  2768. $usage = $json['usage'];
  2769. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2770. }
  2771. } catch (\Exception $e) {
  2772. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2773. continue;
  2774. }
  2775. }
  2776. }
  2777. dLog('deepseek')->info('流式读取完成', [
  2778. 'content_length' => strlen($fullContent),
  2779. 'reasoning_length' => strlen($fullReasoningContent)
  2780. ]);
  2781. yield [
  2782. 'type' => 'done',
  2783. 'full_content' => $fullContent,
  2784. 'full_reasoning' => $fullReasoningContent,
  2785. 'usage' => $usage
  2786. ];
  2787. }
  2788. /**
  2789. * GPT 重试次数(env 可配置,默认 5 次)
  2790. */
  2791. private function gptRetryTimes()
  2792. {
  2793. return (int)env('GPT_RETRY_TIMES', 5);
  2794. }
  2795. /**
  2796. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  2797. */
  2798. private function gptRetryInterval()
  2799. {
  2800. return (int)env('GPT_RETRY_INTERVAL', 10);
  2801. }
  2802. /**
  2803. * 判断 GPT 请求异常是否可重试
  2804. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  2805. */
  2806. private function isGptRetryableException(\Exception $e)
  2807. {
  2808. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  2809. return false;
  2810. }
  2811. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  2812. $status = $e->getResponse()->getStatusCode();
  2813. return $status >= 500 || $status == 429;
  2814. }
  2815. return true;
  2816. }
  2817. /**
  2818. * GPT 中转站探活:GET /v1/models,5 秒短超时
  2819. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  2820. */
  2821. private function checkGptServiceAvailable($apiKey = null)
  2822. {
  2823. if ($apiKey === null) {
  2824. $apiKey = env('GPT_54_API_KEY');
  2825. }
  2826. if (empty($apiKey)) {
  2827. return false;
  2828. }
  2829. try {
  2830. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  2831. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  2832. 'headers' => [
  2833. 'Authorization' => 'Bearer ' . $apiKey,
  2834. 'Content-Type' => 'application/json'
  2835. ]
  2836. ]);
  2837. $status = $response->getStatusCode();
  2838. return $status < 500 && $status != 429;
  2839. } catch (\Exception $e) {
  2840. return false;
  2841. }
  2842. }
  2843. /**
  2844. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  2845. * 全部失败抛出友好错误
  2846. */
  2847. private function ensureGptServiceAvailable($apiKey = null)
  2848. {
  2849. $maxRetries = $this->gptRetryTimes();
  2850. $interval = $this->gptRetryInterval();
  2851. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  2852. if ($this->checkGptServiceAvailable($apiKey)) {
  2853. return;
  2854. }
  2855. if ($attempt < $maxRetries) {
  2856. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  2857. 'retry' => $attempt + 1,
  2858. 'max_retries' => $maxRetries
  2859. ]);
  2860. sleep($interval);
  2861. }
  2862. }
  2863. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  2864. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  2865. 'max_retries' => $maxRetries,
  2866. 'interval' => $interval
  2867. ]);
  2868. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  2869. }
  2870. /**
  2871. * GPT 流式输出处理方法
  2872. *
  2873. * @param array $post_data GPT API请求参数
  2874. * @return \Generator 返回生成器,用于流式输出
  2875. */
  2876. private function gpt54StreamResponse($post_data) {
  2877. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  2878. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  2879. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  2880. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  2881. $usedLunaFallback = false;
  2882. // 流式请求长时间无任何返回(TTFB)超过该秒数时切换备用 Key(env 可配置,默认 600 秒)
  2883. $ttfbTimeoutSeconds = (int)env('GPT_SWITCH_LUNA_AFTER_SECONDS', 600);
  2884. if (empty($apiKey)) {
  2885. Utils::throwError('20003:GPT API Key未配置');
  2886. }
  2887. // 先探活,服务不可用时自动重试
  2888. $this->ensureGptServiceAvailable($apiKey);
  2889. $client = new Client(['timeout' => 1800, 'verify' => false, 'read_timeout' => $ttfbTimeoutSeconds]);
  2890. // 移除 thinking 参数,GPT-5.4 不支持
  2891. if (isset($post_data['thinking'])) {
  2892. unset($post_data['thinking']);
  2893. }
  2894. if (isset($post_data['reasoning_effort'])) {
  2895. unset($post_data['reasoning_effort']);
  2896. }
  2897. // 中转站不识别 response_format,可能被误转成 JSON 输出模式
  2898. if (isset($post_data['response_format'])) {
  2899. unset($post_data['response_format']);
  2900. }
  2901. $post_data['max_completion_tokens'] = 100000;
  2902. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2903. $post_data['stream_options'] = ['include_usage' => true];
  2904. $maxRetries = $this->gptRetryTimes();
  2905. $interval = $this->gptRetryInterval();
  2906. $attempt = 0;
  2907. while (true) {
  2908. $fullContent = '';
  2909. $usage = [];
  2910. $buffer = '';
  2911. $suspectJsonWrap = false;
  2912. $pendingContent = '';
  2913. $requestStartedAt = microtime(true);
  2914. $headers = [
  2915. 'Authorization' => 'Bearer ' . $apiKey,
  2916. 'Content-Type' => 'application/json',
  2917. 'Accept' => 'text/event-stream'
  2918. ];
  2919. try {
  2920. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  2921. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  2922. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  2923. 'json' => $post_data,
  2924. 'headers' => $headers,
  2925. 'stream' => true // 启用流式响应
  2926. ]);
  2927. $body = $response->getBody();
  2928. dLog('deepseek')->info('开始读取 GPT 流式响应');
  2929. // 逐行读取流式响应
  2930. while (!$body->eof()) {
  2931. // 长时间没有任何内容返回时,切换备用 Key 重试
  2932. if ($fullContent === '' && empty($usage) && (microtime(true) - $requestStartedAt) > $ttfbTimeoutSeconds) {
  2933. throw new \RuntimeException('GPT 流式响应长时间无返回,等待切换备用 Key');
  2934. }
  2935. $chunk = $body->read(1024); // 每次读取 1KB
  2936. $buffer .= $chunk;
  2937. // 按行分割
  2938. $lines = explode("\n", $buffer);
  2939. // 保留最后一个不完整的行
  2940. $buffer = array_pop($lines);
  2941. foreach ($lines as $line) {
  2942. $line = trim($line);
  2943. // 跳过空行
  2944. if (empty($line)) {
  2945. continue;
  2946. }
  2947. // 检查是否是 SSE 数据行
  2948. if (strpos($line, 'data: ') !== 0) {
  2949. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2950. continue;
  2951. }
  2952. $data = substr($line, 6); // 移除 "data: " 前缀
  2953. if ($data === '[DONE]') {
  2954. dLog('deepseek')->info('收到结束标记');
  2955. break 2; // 跳出 foreach 和流读取循环
  2956. }
  2957. try {
  2958. $json = json_decode($data, true);
  2959. if (json_last_error() !== JSON_ERROR_NONE) {
  2960. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2961. continue;
  2962. }
  2963. if (isset($json['choices'][0]['delta'])) {
  2964. $delta = $json['choices'][0]['delta'];
  2965. // 处理回答内容
  2966. if (isset($delta['content'])) {
  2967. $fullContent .= $delta['content'];
  2968. $trimmed = ltrim($fullContent);
  2969. if (!$suspectJsonWrap && $trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
  2970. // 可能模型把整段正文包成了 JSON 字符串,先暂缓输出
  2971. $suspectJsonWrap = true;
  2972. }
  2973. if (!$suspectJsonWrap) {
  2974. // 中转可能一次返回大段内容,按小块输出保持流式节奏
  2975. $chunkSize = 256;
  2976. $chunkLength = mb_strlen($delta['content']);
  2977. for ($offset = 0; $offset < $chunkLength; $offset += $chunkSize) {
  2978. yield [
  2979. 'type' => 'content',
  2980. 'content' => mb_substr($delta['content'], $offset, $chunkSize),
  2981. ];
  2982. }
  2983. } else {
  2984. $pendingContent .= $delta['content'];
  2985. }
  2986. }
  2987. }
  2988. // 获取使用统计信息
  2989. if (isset($json['usage'])) {
  2990. $usage = $json['usage'];
  2991. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2992. }
  2993. } catch (\Exception $e) {
  2994. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2995. continue;
  2996. }
  2997. }
  2998. }
  2999. dLog('deepseek')->info('流式读取完成', [
  3000. 'content_length' => strlen($fullContent)
  3001. ]);
  3002. // 兼容模型偶发把整段正文包裹成 JSON 字符串返回
  3003. if ($suspectJsonWrap) {
  3004. $decoded = json_decode(trim($fullContent), true);
  3005. $unwrapped = null;
  3006. if (is_array($decoded)) {
  3007. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  3008. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  3009. $unwrapped = $decoded[$key];
  3010. break;
  3011. }
  3012. }
  3013. }
  3014. if ($unwrapped !== null) {
  3015. $fullContent = $unwrapped;
  3016. $chunkSize = 256;
  3017. $contentLength = mb_strlen($fullContent);
  3018. for ($offset = 0; $offset < $contentLength; $offset += $chunkSize) {
  3019. yield [
  3020. 'type' => 'content',
  3021. 'content' => mb_substr($fullContent, $offset, $chunkSize),
  3022. ];
  3023. }
  3024. } elseif ($pendingContent !== '') {
  3025. // 误判:补发暂缓内容,避免内容丢失
  3026. yield [
  3027. 'type' => 'content',
  3028. 'content' => $pendingContent,
  3029. ];
  3030. }
  3031. }
  3032. yield [
  3033. 'type' => 'done',
  3034. 'full_content' => $fullContent,
  3035. 'full_reasoning' => '',
  3036. 'usage' => $usage
  3037. ];
  3038. return;
  3039. } catch (\Exception $e) {
  3040. // 报错或长时间无返回时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  3041. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  3042. $usedLunaFallback = true;
  3043. $apiKey = $lunaApiKey;
  3044. dLog('deepseek')->warning('GPT 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  3045. continue;
  3046. }
  3047. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  3048. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  3049. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  3050. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  3051. throw $e;
  3052. }
  3053. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  3054. 'retry' => $attempt + 1,
  3055. 'max_retries' => $maxRetries,
  3056. 'error' => $e->getMessage()
  3057. ]);
  3058. sleep($interval);
  3059. $attempt++;
  3060. }
  3061. }
  3062. }
  3063. // 与推理模型对话
  3064. public function chatWithReasoner($data) {
  3065. $content = getProp($data, 'content');
  3066. $model = getProp($data, 'model', 'r1');
  3067. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3068. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3069. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3070. if ($model == 'r1') {
  3071. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  3072. $thinkingMode = 'disabled';
  3073. } else {
  3074. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  3075. $thinkingMode = 'disabled';
  3076. }
  3077. // 获取可选情感(根据音色可支持情感选)
  3078. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  3079. $emotion_list = [];
  3080. foreach ($timbre_emotion as $emotion) {
  3081. $tmp = explode(',', $emotion);
  3082. $emotion_list = array_merge($emotion_list, $tmp);
  3083. }
  3084. $emotion_list = array_unique($emotion_list);
  3085. $emotion_str = implode('、', $emotion_list);
  3086. // // 获取可选情感
  3087. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  3088. // $emotion_str = implode('、', $emotion_list);
  3089. // 是否启用情感
  3090. $enable_emotion = getProp($data, 'enable_emotion', 0);
  3091. if ($enable_emotion) {
  3092. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  3093. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3094. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  3095. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  3096. }else {
  3097. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  3098. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3099. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  3100. }
  3101. $messages = [
  3102. [
  3103. 'role' => 'system',
  3104. 'content' => $sys_content
  3105. ],
  3106. [
  3107. 'role' => 'user',
  3108. 'content' => $content
  3109. ]
  3110. ];
  3111. $post_data = [
  3112. 'model' => $model,
  3113. 'messages' => $messages,
  3114. // 'max_tokens' => 8192,
  3115. 'temperature' => 1,
  3116. 'frequency_penalty' => 0,
  3117. 'presence_penalty' => 0,
  3118. 'thinking' => ['type' => $thinkingMode],
  3119. 'response_format' => [
  3120. 'type' => 'text'
  3121. ],
  3122. 'stream' => false
  3123. ];
  3124. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3125. // 根据模型类型选择调用方法
  3126. $fullContent = '';
  3127. $usage = [];
  3128. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3129. // DeepSeek 官方模型使用 DeepSeek API
  3130. $chatResult = $this->chatOnly($post_data);
  3131. } else if (in_array($model, $this->gpt_text_models)) {
  3132. // GPT-5.4 模型使用 TokenRouter API
  3133. $chatResult = $this->gpt54ChatOnly($post_data);
  3134. } else {
  3135. // 其他模型使用火山引擎API
  3136. $chatResult = $this->volcEngineChatCompletion($post_data);
  3137. }
  3138. if (is_array($chatResult)) {
  3139. $fullContent = $chatResult['fullContent'];
  3140. $usage = $chatResult['usage'];
  3141. }
  3142. // 处理获取到的剧本数据
  3143. $script_content = handleScriptWords($fullContent, $enable_emotion);
  3144. $result = [
  3145. 'origin_content' => $fullContent,
  3146. 'roles' => getProp($script_content, 'roles'),
  3147. 'words' => getProp($script_content, 'words'),
  3148. ];
  3149. // 仅记录 token 使用明细(不扣积分)
  3150. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  3151. 'model' => $model,
  3152. 'source' => 'chatWithReasoner',
  3153. ], $model);
  3154. return $result;
  3155. }
  3156. public function resetParagraphAudio($data) {
  3157. $bid = getProp($data, 'bid');
  3158. $cid = getProp($data, 'cid');
  3159. $version_id = getProp($data, 'version_id');
  3160. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  3161. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  3162. 'generate_status' => '待制作',
  3163. 'updated_at' => date('Y-m-d H:i:s')
  3164. ]);
  3165. }
  3166. public function saveParagraphAudio($data) {
  3167. $bid = getProp($data, 'bid');
  3168. $cid = getProp($data, 'cid');
  3169. $version_id = getProp($data, 'version_id');
  3170. $sequence = getProp($data, 'sequence');
  3171. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  3172. // 获取所有情感
  3173. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3174. $emotion_list = array_flip($emotion_list);
  3175. // 获取音色支持情感
  3176. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  3177. $timbre_emotion = explode(',', $timbre_emotion);
  3178. $emotion = getProp($data, 'emotion');
  3179. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  3180. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3181. $list = [
  3182. 'bid' => $bid,
  3183. 'cid' => $cid,
  3184. 'version_id' => $version_id,
  3185. 'sequence' => $sequence,
  3186. 'role' => getProp($data, 'role'),
  3187. 'gender' => getProp($data, 'gender'),
  3188. 'text' => trim(getProp($data, 'text')),
  3189. 'emotion' => $emotion,
  3190. 'emotion_type' => $emotion_type,
  3191. 'voice_type' => getProp($data, 'voice_type'),
  3192. 'voice_name' => getProp($data, 'voice_name'),
  3193. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  3194. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  3195. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  3196. 'pitch' => getProp($data, 'pitch', 0),
  3197. // 'paragraph_audio_url' => '',
  3198. 'generate_status' => '制作中',
  3199. 'error_msg' => '',
  3200. 'updated_at' => date('Y-m-d H:i:s')
  3201. ];
  3202. $continue = false;
  3203. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  3204. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  3205. $list['generate_status'] = '制作成功';
  3206. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  3207. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  3208. $continue = true;
  3209. }
  3210. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  3211. if ($id) {
  3212. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  3213. }else {
  3214. $list['created_at'] = date('Y-m-d H:i:s');
  3215. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  3216. $boolen = $id ? true : false;
  3217. }
  3218. // 如果更新成功则加入查询队列
  3219. if ($boolen) {
  3220. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  3221. Redis::sadd($redis_key, $id);
  3222. }
  3223. if ($boolen && !$continue) {
  3224. $boolen = false;
  3225. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3226. // 根据ID通过API通知合成音频
  3227. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  3228. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  3229. $response = $result->getBody()->getContents();
  3230. $response_arr = json_decode($response, true);
  3231. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3232. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3233. Log::info('通知火山生成段落音频失败: '.$error_msg);
  3234. Utils::throwError('20003:通知火山生成段落音频失败');
  3235. }
  3236. $boolen = true;
  3237. }
  3238. return $boolen;
  3239. }
  3240. public function insertAudioEffect($data) {
  3241. $audio_id = getProp($data, 'audio_id');
  3242. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3243. $bid = getProp($chapter_audio, 'bid');
  3244. $version_id = getProp($chapter_audio, 'version_id');
  3245. $cid = getProp($chapter_audio, 'cid');
  3246. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3247. $audio_effect_json = getProp($data, 'audio_effect_json');
  3248. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  3249. try {
  3250. DB::beginTransaction();
  3251. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3252. if (!$count) {
  3253. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3254. }else {
  3255. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3256. }
  3257. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3258. 'audio_effect_status' => '添加中',
  3259. 'audio_effect_json' => $audio_effect_json,
  3260. 'updated_at' => date('Y-m-d H:i:s')
  3261. ]);
  3262. if (!$boolen1) {
  3263. DB::rollBack();
  3264. Utils::throwError('20003:更新生成数据失败');
  3265. }
  3266. $id = DB::table('mp_audio_tasks')->insertGetId([
  3267. 'audio_id' => $audio_id,
  3268. 'generate_status' => '执行中',
  3269. 'generate_json' => json_encode([], 256),
  3270. 'bid' => $bid,
  3271. 'book_name' => getProp($chapter_audio, 'book_name'),
  3272. 'version_id' => $version_id,
  3273. 'version_name' => getProp($chapter_audio, 'version_name'),
  3274. 'cid' => $cid,
  3275. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3276. 'task_name' => $task_name,
  3277. 'created_at' => date('Y-m-d H:i:s'),
  3278. 'updated_at' => date('Y-m-d H:i:s')
  3279. ]);
  3280. if (!$id) {
  3281. DB::rollBack();
  3282. Utils::throwError('20003:创建任务失败');
  3283. }
  3284. }catch (\Exception $e) {
  3285. DB::rollBack();
  3286. Utils::throwError('20003:'.$e->getMessage());
  3287. }
  3288. DB::commit();
  3289. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3290. // 根据ID通过API通知合成音频
  3291. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3292. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3293. $response = $result->getBody()->getContents();
  3294. $response_arr = json_decode($response, true);
  3295. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3296. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3297. Log::info('通知火山插入音效失败: '.$error_msg);
  3298. Utils::throwError('20003:通知火山插入音效失败');
  3299. }
  3300. return true;
  3301. }
  3302. public function insertBgm($data) {
  3303. $audio_id = getProp($data, 'audio_id');
  3304. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3305. $bid = getProp($chapter_audio, 'bid');
  3306. $version_id = getProp($chapter_audio, 'version_id');
  3307. $cid = getProp($chapter_audio, 'cid');
  3308. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3309. $bgm_json = getProp($data, 'bgm_json');
  3310. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3311. if (!$bgm_json) {
  3312. $bgm_json = getProp($data, 'audio_effect_json');
  3313. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3314. }
  3315. try {
  3316. DB::beginTransaction();
  3317. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3318. if (!$count) {
  3319. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3320. }else {
  3321. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3322. }
  3323. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3324. 'bgm_status' => '添加中',
  3325. 'bgm_json' => $bgm_json,
  3326. 'updated_at' => date('Y-m-d H:i:s')
  3327. ]);
  3328. if (!$boolen1) {
  3329. DB::rollBack();
  3330. Utils::throwError('20003:更新生成数据失败');
  3331. }
  3332. $id = DB::table('mp_audio_tasks')->insertGetId([
  3333. 'audio_id' => $audio_id,
  3334. 'generate_status' => '执行中',
  3335. 'generate_json' => json_encode([], 256),
  3336. 'bid' => $bid,
  3337. 'book_name' => getProp($chapter_audio, 'book_name'),
  3338. 'version_id' => $version_id,
  3339. 'version_name' => getProp($chapter_audio, 'version_name'),
  3340. 'cid' => $cid,
  3341. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3342. 'task_name' => $task_name,
  3343. 'created_at' => date('Y-m-d H:i:s'),
  3344. 'updated_at' => date('Y-m-d H:i:s')
  3345. ]);
  3346. if (!$id) {
  3347. DB::rollBack();
  3348. Utils::throwError('20003:创建任务失败');
  3349. }
  3350. }catch (\Exception $e) {
  3351. DB::rollBack();
  3352. Utils::throwError('20003:'.$e->getMessage());
  3353. }
  3354. DB::commit();
  3355. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3356. // 根据ID通过API通知合成音频
  3357. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3358. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3359. $response = $result->getBody()->getContents();
  3360. $response_arr = json_decode($response, true);
  3361. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3362. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3363. Log::info('通知火山插入bgm失败: '.$error_msg);
  3364. Utils::throwError('20003:通知火山插入bgm失败');
  3365. }
  3366. return true;
  3367. }
  3368. public function getParagraphAudios($data) {
  3369. $bid = getProp($data, 'bid');
  3370. $cid = getProp($data, 'cid');
  3371. $version_id = getProp($data, 'version_id');
  3372. $sequence = getProp($data, 'sequence');
  3373. // 获取已生成的音频
  3374. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  3375. if ($sequence) $query->where('sequence', $sequence);
  3376. $paragraph_audios = $query->orderBy('sequence')->get();
  3377. $result = [];
  3378. foreach($paragraph_audios as $item) {
  3379. $result[] = [
  3380. 'sequence' => getProp($item, 'sequence'),
  3381. 'role' => getProp($item, 'role'),
  3382. 'gender' => getProp($item, 'gender'),
  3383. 'text' => trim(getProp($item, 'text')),
  3384. 'emotion' => getProp($item, 'emotion'),
  3385. 'emotion_type' => getProp($item, 'emotion_type'),
  3386. 'voice_type' => getProp($item, 'voice_type'),
  3387. 'voice_name' => getProp($item, 'voice_name'),
  3388. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3389. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3390. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3391. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3392. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  3393. ];
  3394. }
  3395. return $result;
  3396. }
  3397. // 新增合成任务
  3398. public function addGenerateTask($data) {
  3399. $bid = getProp($data, 'bid');
  3400. $cid = getProp($data, 'cid');
  3401. $version_id = getProp($data, 'version_id');
  3402. $generate_json = getProp($data, 'generate_json');
  3403. // 获取已生成的音频
  3404. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  3405. $paragraph_list = [];
  3406. foreach($paragraph_audios as $item) {
  3407. $paragraph_list[getProp($item, 'sequence')] = [
  3408. 'role' => getProp($item, 'role'),
  3409. 'gender' => getProp($item, 'gender'),
  3410. 'text' => trim(getProp($item, 'text')),
  3411. 'emotion' => getProp($item, 'emotion'),
  3412. 'emotion_type' => getProp($item, 'emotion_type'),
  3413. 'voice_type' => getProp($item, 'voice_type'),
  3414. 'voice_name' => getProp($item, 'voice_name'),
  3415. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3416. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3417. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3418. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3419. ];
  3420. }
  3421. // 更新角色-音色信息
  3422. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  3423. $existed_role_info = json_decode($existed_role_info, true);
  3424. if (!$existed_role_info) $existed_role_info = [];
  3425. // 获取情感信息
  3426. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3427. $emotion_list = array_flip($emotion_list);
  3428. // 获取音色对应情感组
  3429. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  3430. $timbre_emotion_list = [];
  3431. foreach($timbre_emotions as $item) {
  3432. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  3433. }
  3434. // 构造生成音频的json
  3435. $words = json_decode($generate_json, true);
  3436. // 最终合成前的参数组
  3437. $mp_chapter_paragraph_audios = [];
  3438. $sequence = 1;
  3439. $complete_paragraph_sequences = [];
  3440. foreach($words as &$word) {
  3441. 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:参数格式有误');
  3442. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  3443. $role = getProp($word, 'role');
  3444. $word['gender'] = (int)$word['gender'];
  3445. // 判断音色对应情感是否支持,不支持则调整为中性
  3446. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  3447. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  3448. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  3449. if (isset($emotion_list[getProp($word, 'emotion')])) {
  3450. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  3451. }else {
  3452. $word['emotion'] = '中性';
  3453. $word['emotion_type'] = 'neutral';
  3454. }
  3455. $existed_role_info[$role] = [
  3456. 'timbre_type' => $word['voice_type'],
  3457. 'timbre_name' => $word['voice_name'],
  3458. 'emotion' => $word['emotion'],
  3459. 'emotion_type' => $word['emotion_type'],
  3460. 'speed_ratio' => $word['speed_ratio'],
  3461. 'loudness_ratio'=> $word['loudness_ratio'],
  3462. 'emotion_scale' => $word['emotion_scale'],
  3463. 'pitch' => $word['pitch']
  3464. ];
  3465. $word['paragraph_audio_url'] = '';
  3466. // 判断生成参数是否相同,相同则直接使用已生成的音频
  3467. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  3468. // 如果音频存在并且参数都未改变则使用已生成的音频
  3469. if (getProp($paragraph, 'paragraph_audio_url')) {
  3470. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  3471. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  3472. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  3473. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  3474. // {
  3475. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3476. // }
  3477. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3478. }
  3479. $tmp = $word;
  3480. // 组装章节分句音频数据
  3481. // $tmp['sequence'] = getProp($word, 'sequence');
  3482. // $tmp['text'] = getProp($word, 'text');
  3483. // $tmp['emotion'] = getProp($word, 'emotion');
  3484. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  3485. // $tmp['voice_name'] = getProp($word, 'voice_name');
  3486. // $tmp['voice_type'] = getProp($word, 'voice_type');
  3487. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  3488. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  3489. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  3490. $tmp['bid'] = $bid;
  3491. $tmp['version_id'] = $version_id;
  3492. $tmp['cid'] = $cid;
  3493. $tmp['sequence'] = $sequence;
  3494. $tmp['created_at'] = date('Y-m-d H:i:s');
  3495. $tmp['updated_at'] = date('Y-m-d H:i:s');
  3496. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  3497. $mp_chapter_paragraph_audios[] = $tmp;
  3498. $complete_paragraph_sequences[] = $sequence;
  3499. $sequence++;
  3500. }
  3501. $generate_json = json_encode($words, 256);
  3502. // 判断是否有未生成字幕的段落
  3503. $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();
  3504. if ($no_subtitle_sequences) {
  3505. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  3506. }
  3507. try {
  3508. DB::beginTransaction();
  3509. $role_info = json_encode($existed_role_info, 256);
  3510. $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')]);
  3511. if (!$boolen) {
  3512. DB::rollBack();
  3513. Utils::throwError('20003:更新角色信息失败');
  3514. }
  3515. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  3516. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  3517. if (!$count) {
  3518. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3519. }else {
  3520. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3521. }
  3522. $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')]);
  3523. if (!$boolen1) {
  3524. DB::rollBack();
  3525. Utils::throwError('20003:更新生成数据失败');
  3526. }
  3527. $id = DB::table('mp_audio_tasks')->insertGetId([
  3528. 'audio_id' => getProp($chapter_audio, 'id'),
  3529. 'generate_status' => '执行中',
  3530. 'generate_json' => $generate_json,
  3531. 'bid' => $bid,
  3532. 'book_name' => getProp($chapter_audio, 'book_name'),
  3533. 'version_id' => $version_id,
  3534. 'version_name' => getProp($chapter_audio, 'version_name'),
  3535. 'cid' => $cid,
  3536. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3537. 'task_name' => $task_name,
  3538. 'created_at' => date('Y-m-d H:i:s'),
  3539. 'updated_at' => date('Y-m-d H:i:s')
  3540. ]);
  3541. if (!$id) {
  3542. DB::rollBack();
  3543. Utils::throwError('20003:创建任务失败');
  3544. }
  3545. // 删除不在段落序号范围内的其他数据
  3546. if ($complete_paragraph_sequences) {
  3547. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  3548. }
  3549. // // 删除章节分句音频数据并重新插入
  3550. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  3551. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  3552. // if (!$boolen3) {
  3553. // DB::rollBack();
  3554. // Utils::throwError('20003:更新章节分句音频失败');
  3555. // }
  3556. } catch (\Exception $e) {
  3557. DB::rollBack();
  3558. Utils::throwError('20003:'.$e->getMessage());
  3559. }
  3560. DB::commit();
  3561. // 通知火山生成音频
  3562. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3563. // 根据ID通过API通知合成音频
  3564. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  3565. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  3566. $response = $result->getBody()->getContents();
  3567. $response_arr = json_decode($response, true);
  3568. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3569. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3570. Log::info('通知火山生成音频失败: '.$error_msg);
  3571. Utils::throwError('20003:通知火山生成音频失败');
  3572. }
  3573. return true;
  3574. }
  3575. public function timbreList($data) {
  3576. $gender = getProp($data, 'gender');
  3577. $timbre_name = getProp($data, 'voice_name');
  3578. $category_id = getProp($data, 'category_id');
  3579. $age_stage = getProp($data, 'age_stage');
  3580. $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');
  3581. if ($gender) {
  3582. $query->where('gender', $gender);
  3583. }
  3584. if ($timbre_name) {
  3585. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  3586. }
  3587. if ($category_id) {
  3588. $query->where(function ($query) use ($category_id) {
  3589. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  3590. });
  3591. }
  3592. if ($age_stage) {
  3593. $query->where('age_stage', $age_stage);
  3594. }
  3595. $list = $query->get()->map(function ($value) {
  3596. $value = (array)$value;
  3597. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  3598. return $value;
  3599. })->toArray();
  3600. return $list;
  3601. }
  3602. // 生成火山临时token
  3603. public function setStsToken() {
  3604. // ************* 配置参数 *************
  3605. $method = 'GET';
  3606. $service = 'sts';
  3607. $host = 'open.volcengineapi.com';
  3608. $region = env('VOLC_REGION');
  3609. $endpoint = 'https://open.volcengineapi.com';
  3610. // $endpoint = 'https://tos-cn-beijing.volces.com';
  3611. $access_key = env('VOLC_AK');
  3612. $secret_key = env('VOLC_SK');
  3613. // 获取缓存中的token,如果没有则请求接口
  3614. $token = Redis::get('volc_sts_token');
  3615. if (!$token) {
  3616. // 查询参数
  3617. $query_parameters = [
  3618. 'Action' => 'AssumeRole',
  3619. 'RoleSessionName' => 'user@zw',
  3620. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  3621. 'Version' => '2018-01-01'
  3622. ];
  3623. // 生成URL编码的查询字符串
  3624. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  3625. // 获取签名头信息
  3626. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  3627. // 构建完整URL
  3628. $request_url = $endpoint . '?' . $request_parameters;
  3629. $client = new Client(['verify' => false]);
  3630. $response = $client->get($request_url, ['headers' => $headers]);
  3631. $response_arr = json_decode($response->getBody()->getContents(), true);
  3632. $result = [
  3633. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  3634. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  3635. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  3636. 'Region' => env('VOLC_REGION'),
  3637. 'Endpoint' => env('VOLC_END_POINT'),
  3638. 'Bucket' => env('VOLC_BUCKET'),
  3639. ];
  3640. // 缓存token
  3641. Redis::setex('volc_sts_token', 3000, json_encode($result));
  3642. return $result;
  3643. } else {
  3644. return json_decode($token, true);
  3645. }
  3646. // $response = $response['Response'];
  3647. // $access_key = $response['Credentials']['AccessKeyId'];
  3648. // $secret_key = $response['Credentials']['AccessKeySecret'];
  3649. // $security_token = $response['Credentials']['SecurityToken'];
  3650. // $expiration = $response['Credentials']['Expiration'];
  3651. // dd($response_arr);
  3652. }
  3653. public function emotionGroups($data) {
  3654. $id = getProp($data, 'group_id');
  3655. $group_name = getProp($data, 'group_name');
  3656. $voice_type = getProp($data, 'voice_type');
  3657. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  3658. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  3659. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  3660. if ($group_name) {
  3661. $query->where('group_name', 'like', "%{$group_name}%");
  3662. }
  3663. if ($id) {
  3664. $query->where('id', $id);
  3665. }
  3666. if ($voice_type) {
  3667. $query->where('voice_type', $voice_type);
  3668. }
  3669. return $query->orderBy('id')->get()->map(function ($value) {
  3670. return (array)$value;
  3671. })->toArray();
  3672. }
  3673. private function sign($key, $msg) {
  3674. return hash_hmac('sha256', $msg, $key, true);
  3675. }
  3676. // 生成签名密钥
  3677. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  3678. $kDate = $this->sign($key, $dateStamp);
  3679. $kRegion = $this->sign($kDate, $regionName);
  3680. $kService = $this->sign($kRegion, $serviceName);
  3681. $kSigning = $this->sign($kService, 'request');
  3682. return $kSigning;
  3683. }
  3684. // 获取签名头信息
  3685. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  3686. $contenttype = 'application/x-www-form-urlencoded';
  3687. $accept = 'application/json';
  3688. // 获取当前UTC时间
  3689. $t = new DateTime('now', new DateTimeZone('UTC'));
  3690. $xdate = $t->format('Ymd\THis\Z');
  3691. $datestamp = $t->format('Ymd');
  3692. // 1. 拼接规范请求串
  3693. $canonical_uri = '/';
  3694. $canonical_querystring = $request_parameters;
  3695. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  3696. $signed_headers = 'content-type;host;x-date';
  3697. // 空请求体的SHA256哈希
  3698. $payload_hash = hash('sha256', '');
  3699. $canonical_request = implode("\n", [
  3700. $method,
  3701. $canonical_uri,
  3702. $canonical_querystring,
  3703. $canonical_headers,
  3704. $signed_headers,
  3705. $payload_hash
  3706. ]);
  3707. // 2. 拼接待签名字符串
  3708. $algorithm = 'HMAC-SHA256';
  3709. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  3710. $hashed_canonical_request = hash('sha256', $canonical_request);
  3711. $string_to_sign = implode("\n", [
  3712. $algorithm,
  3713. $xdate,
  3714. $credential_scope,
  3715. $hashed_canonical_request
  3716. ]);
  3717. // 3. 计算签名
  3718. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  3719. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  3720. // 4. 添加签名到请求头
  3721. $authorization_header = sprintf(
  3722. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  3723. $algorithm,
  3724. $access_key,
  3725. $credential_scope,
  3726. $signed_headers,
  3727. $signature
  3728. );
  3729. return [
  3730. 'Accept' => $accept,
  3731. 'Content-Type' => $contenttype,
  3732. 'X-Date' => $xdate,
  3733. 'Authorization' => $authorization_header
  3734. ];
  3735. }
  3736. // 文字合成语音(火山引擎)
  3737. public function tts($data) {
  3738. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  3739. $headers = [
  3740. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  3741. 'Content-Type' => 'application/json; charset=UTF-8'
  3742. ];
  3743. $post_data = [
  3744. 'app' => [
  3745. 'appid' => env('VOLC_APPID'),
  3746. 'token' => env('VOLC_TOKEN'),
  3747. 'cluster' => 'volcano_tts'
  3748. ],
  3749. 'user' => [
  3750. 'uid' => 'mp_audio'
  3751. ],
  3752. // 'audio' => [
  3753. // 'voice_type' =>
  3754. // ],
  3755. ];
  3756. }
  3757. public function scriptList($data) {
  3758. $uid = Site::getUid();
  3759. $script_id = getProp($data, 'script_id');
  3760. $script_name = getProp($data, 'script_name');
  3761. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  3762. if ($script_id) {
  3763. $query->where('id', $script_id);
  3764. }
  3765. if ($script_name) {
  3766. $query->where('script_name', 'like', "%{$script_name}%");
  3767. }
  3768. return $query->orderBy('created_at', 'desc')->paginate(12);
  3769. }
  3770. public function scripts($data) {
  3771. $uid = Site::getUid();
  3772. $script_id = getProp($data, 'script_id');
  3773. $script_name = getProp($data, 'script_name');
  3774. $is_products = getProp($data, 'is_products');
  3775. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  3776. if ($script_id) {
  3777. $query->where('id', $script_id);
  3778. }
  3779. if ($is_products !== '') {
  3780. $query->where('is_products', $is_products);
  3781. }
  3782. if ($script_name) {
  3783. $query->where('script_name', 'like', "%{$script_name}%");
  3784. }
  3785. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  3786. return (array)$value;
  3787. })->toArray();
  3788. }
  3789. public function scriptInfo($data) {
  3790. $uid = Site::getUid();
  3791. $script_id = getProp($data, 'script_id');
  3792. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  3793. // ->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();
  3794. ->selectRaw('id as script_id, script_name')->first();
  3795. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3796. $script = (array)$script;
  3797. // 获取分集组信息
  3798. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  3799. ->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')
  3800. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  3801. $value = (array)$value;
  3802. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  3803. return (array)$value;
  3804. })->toArray();
  3805. $script['group'] = $groups;
  3806. return $script;
  3807. }
  3808. public function createScript($data) {
  3809. $script_name = getProp($data, 'script_name');
  3810. $uid = Site::getUid(); // 获取当前用户ID
  3811. $cpid = Site::getCpid(); // 获取当前公司组ID
  3812. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  3813. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  3814. $script_name .= '_'.date('YmdHis');
  3815. }
  3816. return DB::table('mp_scripts')->insertGetId([
  3817. 'script_name' => $script_name,
  3818. 'user_id' => $uid,
  3819. 'cpid' => $cpid,
  3820. 'created_at' => date('Y-m-d H:i:s'),
  3821. 'updated_at' => date('Y-m-d H:i:s')
  3822. ]);
  3823. }
  3824. public function editScript($data) {
  3825. $script_id = getProp($data, 'script_id');
  3826. $script_name = getProp($data, 'script_name');
  3827. $uid = Site::getUid(); // 获取当前用户ID
  3828. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  3829. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  3830. if ($id && (int)$id !== (int)$script_id) {
  3831. $script_name .= '_'.date('YmdHis');
  3832. }
  3833. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3834. 'script_name' => $script_name,
  3835. 'updated_at' => date('Y-m-d H:i:s')
  3836. ]);
  3837. }
  3838. public function delScript($data) {
  3839. $script_id = getProp($data, 'script_id');
  3840. $uid = Site::getUid(); // 获取当前用户ID
  3841. if (!$script_id) Utils::throwError('20003:请选择剧本');
  3842. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3843. 'is_deleted' => 1,
  3844. 'updated_at' => date('Y-m-d H:i:s')
  3845. ]);
  3846. }
  3847. public function createEpisode($data) {
  3848. $script_id = getProp($data, 'script_id');
  3849. $group_name = getProp($data, 'group_name');
  3850. $remark = getProp($data, 'remark');
  3851. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  3852. $uid = Site::getUid(); // 获取当前用户ID
  3853. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  3854. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  3855. $group_name .= '_'.date('YmdHis');
  3856. }
  3857. return DB::table('mp_script_episode_group')->insertGetId([
  3858. 'script_id' => $script_id,
  3859. 'group_name' => $group_name,
  3860. 'user_id' => $uid,
  3861. 'remark' => $remark,
  3862. 'created_at' => date('Y-m-d H:i:s'),
  3863. 'updated_at' => date('Y-m-d H:i:s')
  3864. ]);
  3865. }
  3866. public function editEpisode($data) {
  3867. $group_id = getProp($data, 'group_id');
  3868. $start_episode_number = getProp($data, 'start_episode_number');
  3869. $end_episode_number = getProp($data, 'end_episode_number');
  3870. $group_name = getProp($data, 'group_name');
  3871. $uid = Site::getUid(); // 获取当前用户ID
  3872. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  3873. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  3874. if ($id && (int)$id !== (int)$group_id) {
  3875. $group_name .= '_'.date('YmdHis');
  3876. }
  3877. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3878. 'group_name' => $group_name,
  3879. 'start_episode_number' => $start_episode_number,
  3880. 'end_episode_number' => $end_episode_number,
  3881. 'updated_at' => date('Y-m-d H:i:s')
  3882. ]);
  3883. }
  3884. public function delEpisode($data) {
  3885. $group_id = getProp($data, 'group_id');
  3886. $uid = Site::getUid(); // 获取当前用户ID
  3887. if (!$group_id) Utils::throwError('20003:请选择分集');
  3888. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3889. 'is_deleted' => 1,
  3890. 'updated_at' => date('Y-m-d H:i:s')
  3891. ]);
  3892. }
  3893. /**
  3894. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3895. *
  3896. * @param array $data 包含以下参数:
  3897. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3898. * - question: 用户问题(可选)
  3899. * - model: 使用的模型(r1 或 v3,默认 v3)
  3900. * @return \Generator 返回生成器,用于流式输出
  3901. */
  3902. public function generateEpisodes($data) {
  3903. $script_id = getProp($data, 'script_id');
  3904. $group_id = getProp($data, 'group_id');
  3905. // $file = getProp($data, 'file');
  3906. $file = '';
  3907. $content = getProp($data, 'content', '');
  3908. // $bid = getProp($data, 'bid', 0);
  3909. $bid = 0;
  3910. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3911. if (!$group) {
  3912. Utils::throwError('20003:剧本分集不存在');
  3913. }
  3914. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  3915. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  3916. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  3917. $prompt = getProp($data, 'prompt');
  3918. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  3919. $model = getProp($data, 'model');
  3920. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3921. Utils::throwError('20003:该模型不存在!');
  3922. }
  3923. // 检查是否存在重叠的剧集序号范围
  3924. $exists_groups = DB::table('mp_script_episode_group')
  3925. ->where('script_id', $script_id)
  3926. ->where('id', '<>', $group_id) // 排除当前组
  3927. ->where('is_deleted', 0)
  3928. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3929. // 检查新范围是否与现有范围重叠
  3930. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3931. // 新范围的开始在现有范围内
  3932. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3933. ->where('end_episode_number', '>=', $start_episode_sequence);
  3934. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3935. // 新范围的结束在现有范围内
  3936. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3937. ->where('end_episode_number', '>=', $end_episode_sequence);
  3938. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3939. // 新范围完全包含现有范围
  3940. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3941. ->where('end_episode_number', '<=', $end_episode_sequence);
  3942. });
  3943. })
  3944. ->select('start_episode_number', 'end_episode_number')
  3945. ->get();
  3946. if ($exists_groups->isNotEmpty()) {
  3947. $conflict_ranges = [];
  3948. foreach ($exists_groups as $group) {
  3949. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3950. }
  3951. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3952. }
  3953. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3954. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3955. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3956. if ($model === 'deepseek-chat') {
  3957. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3958. $model = 'deepseek-v4-flash';
  3959. $thinkingMode = 'disabled';
  3960. } elseif ($model === 'deepseek-reasoner') {
  3961. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3962. $model = 'deepseek-v4-flash';
  3963. $thinkingMode = 'enabled';
  3964. }
  3965. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3966. if (!$script) {
  3967. Utils::throwError('20003:剧本不存在');
  3968. }
  3969. $content = getProp($group, 'content');
  3970. if (!$file && !$content && !$bid) {
  3971. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3972. }
  3973. // 提取文件内容
  3974. if ($file) {
  3975. $content = $this->extractFileContent($file);
  3976. if (!$content) {
  3977. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3978. }
  3979. } elseif ($bid) {
  3980. $content = $this->getContentByBid($bid);
  3981. if (!$content) {
  3982. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3983. }
  3984. } elseif ($content) {
  3985. $content = filterContent($content);
  3986. } elseif ($prompt) {
  3987. $content = filterContent($prompt);
  3988. } else {
  3989. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3990. }
  3991. // 构建消息
  3992. $messages = [
  3993. $this->sys_message,
  3994. [
  3995. 'role' => 'user',
  3996. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3997. ]
  3998. ];
  3999. $post_data = [
  4000. 'model' => $model,
  4001. 'messages' => $messages,
  4002. // 'max_tokens' => 8192,
  4003. 'temperature' => 0.7,
  4004. 'frequency_penalty' => 0,
  4005. 'presence_penalty' => 0,
  4006. 'thinking' => ['type' => $thinkingMode],
  4007. 'response_format' => ['type' => 'text'],
  4008. 'stream' => true
  4009. ];
  4010. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4011. // 根据模型类型选择调用方法
  4012. $fullContent = '';
  4013. $fullReasoningContent = '';
  4014. $usage = [];
  4015. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4016. // DeepSeek 官方模型使用 DeepSeek API
  4017. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4018. } else if (in_array($model, $this->gpt_text_models)) {
  4019. // GPT-5.4 模型使用 TokenRouter API
  4020. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4021. } else if (in_array($model, $this->gemini_text_models)) {
  4022. // Gemini 模型使用 Gemini API
  4023. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4024. } else {
  4025. // 其他模型使用火山引擎API
  4026. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4027. }
  4028. // 处理流式输出
  4029. foreach ($streamGenerator as $chunk) {
  4030. if (isset($chunk['type'])) {
  4031. if ($chunk['type'] === 'done') {
  4032. // 最终结果
  4033. $fullContent = $chunk['full_content'];
  4034. $fullReasoningContent = $chunk['full_reasoning'];
  4035. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4036. } else {
  4037. // 逐块yield数据
  4038. yield $chunk;
  4039. }
  4040. }
  4041. }
  4042. dLog('deepseek')->info('完整内容: '.$fullContent);
  4043. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4044. // 处理完整内容并返回最终结果
  4045. $script_arr = [];
  4046. if ($fullContent) {
  4047. $script_arr = extractScriptContent($fullContent);
  4048. }
  4049. logDB('deepseek', 'info', '解析内容', $script_arr);
  4050. if (!$script_arr['episodes']) {
  4051. Utils::throwError('20003:未生成剧本相关信息');
  4052. // yield [
  4053. // 'type' => 'done',
  4054. // 'script' => $script_arr,
  4055. // 'msg' => '未生成剧本相关信息',
  4056. // 'answer' => $fullContent,
  4057. // 'reasoning' => $fullReasoningContent,
  4058. // 'usage' => $usage
  4059. // ];
  4060. // return ;
  4061. }
  4062. try {
  4063. DB::beginTransaction();
  4064. // // 返回前保存剧本内容
  4065. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4066. // 'content' => $content,
  4067. // 'updated_at' => date('Y-m-d H:i:s')
  4068. // ]);
  4069. // if (!$boolen) {
  4070. // Utils::throwError('20003:保存剧本内容失败');
  4071. // }
  4072. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4073. // 'start_episode_number' => $start_episode_sequence,
  4074. // 'end_episode_number' => $end_episode_sequence,
  4075. // 'updated_at' => date('Y-m-d H:i:s')
  4076. // ]);
  4077. // if (!$boolen1) {
  4078. // Utils::throwError('20003:保存分集失败');
  4079. // }
  4080. $episode_content = '';
  4081. $episodes = [];
  4082. foreach ($script_arr['episodes'] as $item) {
  4083. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  4084. // $episodes[] = [
  4085. // 'script_id' => $script_id,
  4086. // 'episode_number' => $item['episode_number'],
  4087. // 'episode_name' => $item['episode_name'],
  4088. // 'episode_content' => $item['episode_content'],
  4089. // 'created_at' => date('Y-m-d H:i:s'),
  4090. // 'updated_at' => date('Y-m-d H:i:s'),
  4091. // ];
  4092. }
  4093. if ($episode_content) {
  4094. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4095. 'episode_content' => $episode_content,
  4096. 'updated_at' => date('Y-m-d H:i:s')
  4097. ]);
  4098. if (!$boolen2) {
  4099. Utils::throwError('20003:保存分集内容失败');
  4100. }
  4101. }else {
  4102. Utils::throwError('20003:分集剧本解析失败');
  4103. }
  4104. }catch (\Exception $e) {
  4105. DB::rollBack();
  4106. Utils::throwError('20003:'.$e->getMessage());
  4107. }
  4108. DB::commit();
  4109. // 仅记录 token 使用明细(不扣积分)
  4110. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  4111. 'model' => $model,
  4112. 'script_id' => $script_id,
  4113. 'group_id' => $group_id,
  4114. 'source' => 'generateEpisodes',
  4115. ], $model);
  4116. yield [
  4117. 'type' => 'done',
  4118. 'script' => $script_arr,
  4119. 'episode_content' => $episode_content,
  4120. 'answer' => $fullContent,
  4121. 'reasoning' => $fullReasoningContent,
  4122. 'usage' => $usage
  4123. ];
  4124. }
  4125. public function chatWithFileStream($data) {
  4126. $script_id = getProp($data, 'script_id');
  4127. $group_id = getProp($data, 'group_id');
  4128. $file = getProp($data, 'file');
  4129. $content = getProp($data, 'content', '');
  4130. $bid = getProp($data, 'bid', 0);
  4131. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4132. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4133. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  4134. $prompt = getProp($data, 'prompt');
  4135. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4136. if (!empty($prompt)) {
  4137. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4138. }
  4139. $question = getProp($data, 'question', $baseQuestion);
  4140. $model = getProp($data, 'model');
  4141. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4142. Utils::throwError('20003:该模型不存在!');
  4143. }
  4144. // 检查是否存在重叠的剧集序号范围
  4145. $exists_groups = DB::table('mp_script_episode_group')
  4146. ->where('script_id', $script_id)
  4147. ->where('id', '<>', $group_id)
  4148. ->where('is_deleted', 0)
  4149. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4150. // 检查新范围是否与现有范围重叠
  4151. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4152. // 新范围的开始在现有范围内
  4153. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4154. ->where('end_episode_number', '>=', $start_episode_sequence);
  4155. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4156. // 新范围的结束在现有范围内
  4157. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4158. ->where('end_episode_number', '>=', $end_episode_sequence);
  4159. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4160. // 新范围完全包含现有范围
  4161. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4162. ->where('end_episode_number', '<=', $end_episode_sequence);
  4163. });
  4164. })
  4165. ->select('start_episode_number', 'end_episode_number')
  4166. ->get();
  4167. if ($exists_groups->isNotEmpty()) {
  4168. $conflict_ranges = [];
  4169. foreach ($exists_groups as $group) {
  4170. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4171. }
  4172. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4173. }
  4174. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4175. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4176. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4177. if ($model === 'deepseek-chat') {
  4178. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4179. $model = 'deepseek-v4-flash';
  4180. $thinkingMode = 'disabled';
  4181. } elseif ($model === 'deepseek-reasoner') {
  4182. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4183. $model = 'deepseek-v4-flash';
  4184. $thinkingMode = 'enabled';
  4185. }
  4186. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4187. if (!$script) {
  4188. Utils::throwError('20003:剧本不存在');
  4189. }
  4190. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4191. if (!$group) {
  4192. Utils::throwError('20003:剧本分集不存在');
  4193. }
  4194. if (!$file && !$content && !$bid) {
  4195. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4196. }
  4197. // 提取文件内容
  4198. if ($file) {
  4199. $content = $this->extractFileContent($file);
  4200. if (!$content) {
  4201. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4202. }
  4203. } elseif ($bid) {
  4204. $content = $this->getContentByBid($bid);
  4205. if (!$content) {
  4206. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4207. }
  4208. } elseif ($content) {
  4209. $content = filterContent($content);
  4210. } elseif ($prompt) {
  4211. $content = filterContent($prompt);
  4212. } else {
  4213. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4214. }
  4215. // 构建消息
  4216. $messages = [
  4217. [
  4218. 'role' => 'system',
  4219. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4220. 强制要求:\n
  4221. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4222. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4223. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  4224. 普通要求:\n
  4225. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  4226. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  4227. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  4228. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  4229. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  4230. 示例如下:\n
  4231. ###剧本名:西昆仑
  4232. ###故事梗概
  4233. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4234. ###剧本亮点
  4235. 亮点1:绝境奇药,生死一线
  4236. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4237. 亮点2:结拜兄妹,化解尴尬
  4238. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4239. 亮点3:纤发夺命,情愫暗涌
  4240. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4241. ###人物关系
  4242. 阿雪与梁萧之间存在兄妹之情。
  4243. ###核心矛盾
  4244. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4245. ###主体列表
  4246. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  4247. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  4248. 阴阳球:天地异宝,能化生精气,救人于危难。
  4249. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  4250. ###美术风格
  4251. 基础画风风格词:厚涂古风
  4252. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4253. ###场景列表
  4254. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  4255. [
  4256. 'role' => 'user',
  4257. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4258. ]
  4259. ];
  4260. $post_data = [
  4261. 'model' => $model,
  4262. 'messages' => $messages,
  4263. // 'max_tokens' => 8192,
  4264. 'temperature' => 0.7,
  4265. 'frequency_penalty' => 0,
  4266. 'presence_penalty' => 0,
  4267. 'thinking' => ['type' => $thinkingMode],
  4268. 'response_format' => ['type' => 'text'],
  4269. 'stream' => true
  4270. ];
  4271. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4272. // 根据模型类型选择调用方法
  4273. $fullContent = '';
  4274. $fullReasoningContent = '';
  4275. $usage = [];
  4276. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4277. // DeepSeek 官方模型使用 DeepSeek API
  4278. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4279. } else if (in_array($model, $this->gpt_text_models)) {
  4280. // GPT-5.4 模型使用 TokenRouter API
  4281. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4282. } else if (in_array($model, $this->gemini_text_models)) {
  4283. // Gemini 模型使用 Gemini API
  4284. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4285. } else {
  4286. // 其他模型使用火山引擎API
  4287. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4288. }
  4289. // 处理流式输出
  4290. foreach ($streamGenerator as $chunk) {
  4291. if (isset($chunk['type'])) {
  4292. if ($chunk['type'] === 'done') {
  4293. // 最终结果
  4294. $fullContent = $chunk['full_content'];
  4295. $fullReasoningContent = $chunk['full_reasoning'];
  4296. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4297. } else {
  4298. // 逐块yield数据
  4299. yield $chunk;
  4300. }
  4301. }
  4302. }
  4303. dLog('deepseek')->info('完整内容: '.$fullContent);
  4304. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4305. // 处理完整内容并返回最终结果
  4306. $script_arr = [];
  4307. if ($fullContent) {
  4308. $script_arr = extractScriptContent($fullContent);
  4309. }
  4310. logDB('deepseek', 'info', '解析内容', $script_arr);
  4311. if (!$script_arr['roles']) {
  4312. Utils::throwError('20003:未生成剧本相关信息');
  4313. // yield [
  4314. // 'type' => 'done',
  4315. // 'script' => $script_arr,
  4316. // 'msg' => '未生成剧本相关信息',
  4317. // 'answer' => $fullContent,
  4318. // 'reasoning' => $fullReasoningContent,
  4319. // 'usage' => $usage
  4320. // ];
  4321. }
  4322. try {
  4323. DB::beginTransaction();
  4324. // // 返回前保存剧本内容
  4325. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4326. // 'content' => $content,
  4327. // 'status' => '解析完成',
  4328. // 'updated_at' => date('Y-m-d H:i:s')
  4329. // ]);
  4330. // if (!$boolen) {
  4331. // Utils::throwError('20003:保存剧本内容失败');
  4332. // }
  4333. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4334. 'start_episode_number' => $start_episode_sequence,
  4335. 'end_episode_number' => $end_episode_sequence,
  4336. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4337. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4338. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4339. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4340. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4341. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4342. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4343. 'status' => '解析完成',
  4344. 'content' => $content,
  4345. 'updated_at' => date('Y-m-d H:i:s')
  4346. ]);
  4347. if (!$boolen1) {
  4348. Utils::throwError('20003:保存分集失败');
  4349. }
  4350. // $episodes = [];
  4351. // foreach ($script_arr['episodes'] as $item) {
  4352. // $episodes[] = [
  4353. // 'script_id' => $script_id,
  4354. // 'episode_number' => $item['episode_number'],
  4355. // 'episode_name' => $item['episode_name'],
  4356. // 'episode_content' => $item['episode_content'],
  4357. // 'created_at' => date('Y-m-d H:i:s'),
  4358. // 'updated_at' => date('Y-m-d H:i:s'),
  4359. // ];
  4360. // }
  4361. // if ($episodes) {
  4362. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4363. // if (!$boolen2) {
  4364. // Utils::throwError('20003:保存分集内容失败');
  4365. // }
  4366. // }else {
  4367. // Utils::throwError('20003:分集剧本解析失败');
  4368. // }
  4369. }catch (\Exception $e) {
  4370. DB::rollBack();
  4371. Utils::throwError('20003:'.$e->getMessage());
  4372. }
  4373. DB::commit();
  4374. // 仅记录 token 使用明细(不扣积分)
  4375. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  4376. 'model' => $model,
  4377. 'script_id' => $script_id,
  4378. 'group_id' => $group_id,
  4379. 'source' => 'chatWithFileStream',
  4380. ], $model);
  4381. yield [
  4382. 'type' => 'done',
  4383. 'script' => $script_arr,
  4384. 'answer' => $fullContent,
  4385. 'reasoning' => $fullReasoningContent,
  4386. 'usage' => $usage
  4387. ];
  4388. }
  4389. /**
  4390. * 上传文件识别文字内容并与 DeepSeek 进行对话
  4391. *
  4392. * @param array $data 包含以下参数:
  4393. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4394. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  4395. * - model: 使用的模型(r1 或 v3,默认 v3)
  4396. * @return array
  4397. */
  4398. public function chatWithFile($data) {
  4399. $script_id = getProp($data, 'script_id');
  4400. $file = getProp($data, 'file');
  4401. $content = getProp($data, 'content', '');
  4402. $bid = getProp($data, 'bid', 0);
  4403. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4404. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4405. $prompt = getProp($data, 'prompt');
  4406. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4407. if (!empty($prompt)) {
  4408. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4409. }
  4410. $question = getProp($data, 'question', $baseQuestion);
  4411. // 处理文本模型
  4412. $model = getProp($data, 'model');
  4413. if (!$model) {
  4414. // 用户没有输入,使用默认值
  4415. $model = 'doubao-seed-2-0-mini-260215';
  4416. }
  4417. // 验证模型是否在可用模型表中
  4418. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4419. $model = 'doubao-seed-2-0-mini-260215';
  4420. }
  4421. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4422. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4423. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4424. if ($model === 'deepseek-chat') {
  4425. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4426. $model = 'deepseek-v4-flash';
  4427. $thinkingMode = 'disabled';
  4428. } elseif ($model === 'deepseek-reasoner') {
  4429. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4430. $model = 'deepseek-v4-flash';
  4431. $thinkingMode = 'enabled';
  4432. }
  4433. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4434. if (!$script) {
  4435. Utils::throwError('20003:剧本不存在');
  4436. }
  4437. if (!$file && !$content && !$bid) {
  4438. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4439. }
  4440. // 提取文件内容
  4441. if ($file) {
  4442. $content = $this->extractFileContent($file);
  4443. if (!$content) {
  4444. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4445. }
  4446. } elseif ($bid) {
  4447. $content = $this->getContentByBid($bid);
  4448. if (!$content) {
  4449. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4450. }
  4451. } elseif ($content) {
  4452. $content = filterContent($content);
  4453. } elseif ($prompt) {
  4454. $content = filterContent($prompt);
  4455. } else {
  4456. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4457. }
  4458. // 构建消息
  4459. $messages = [
  4460. $this->sys_message,
  4461. [
  4462. 'role' => 'user',
  4463. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4464. ]
  4465. ];
  4466. $post_data = [
  4467. 'model' => $model,
  4468. 'messages' => $messages,
  4469. // 'max_tokens' => 8192,
  4470. 'temperature' => 0.7,
  4471. 'frequency_penalty' => 0,
  4472. 'presence_penalty' => 0,
  4473. 'thinking' => ['type' => $thinkingMode],
  4474. 'response_format' => ['type' => 'text'],
  4475. 'stream' => false
  4476. ];
  4477. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4478. // 根据模型类型选择调用方法
  4479. $fullContent = '';
  4480. $usage = [];
  4481. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4482. // DeepSeek 官方模型使用 DeepSeek API
  4483. $chatResult = $this->chatOnly($post_data);
  4484. } else if (in_array($model, $this->gpt_text_models)) {
  4485. // GPT-5.4 模型使用 TokenRouter API
  4486. $chatResult = $this->gpt54ChatOnly($post_data);
  4487. } else {
  4488. // 其他模型使用火山引擎API
  4489. $chatResult = $this->volcEngineChatCompletion($post_data);
  4490. }
  4491. if (is_array($chatResult)) {
  4492. $fullContent = $chatResult['fullContent'];
  4493. $usage = $chatResult['usage'];
  4494. }
  4495. $script_arr = [];
  4496. // 处理结果
  4497. if ($fullContent) {
  4498. $script_arr = extractScriptContent($fullContent);
  4499. }
  4500. // 返回前保存剧本内容
  4501. DB::table('mp_scripts')->where('id', $script_id)->update([
  4502. 'content' => $content,
  4503. 'updated_at' => date('Y-m-d H:i:s')
  4504. ]);
  4505. // 仅记录 token 使用明细(不扣积分)
  4506. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  4507. 'model' => $model,
  4508. 'script_id' => $script_id,
  4509. 'source' => 'chatWithFile',
  4510. ], $model);
  4511. return [
  4512. 'script' => $script_arr,
  4513. 'answer' => $fullContent,
  4514. 'usage' => $usage
  4515. ];
  4516. }
  4517. public function getEpisodeContent($data) {
  4518. $group_id = getProp($data, 'group_id');
  4519. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  4520. }
  4521. public function saveEpisodeContent($data) {
  4522. $script_id = getProp($data, 'script_id');
  4523. $group_id = getProp($data, 'group_id');
  4524. $start_episode_sequence = getProp($data, 'start_episode_number');
  4525. $end_episode_sequence = getProp($data, 'end_episode_number');
  4526. // 检查是否存在重叠的剧集序号范围
  4527. $exists_groups = DB::table('mp_script_episode_group')
  4528. ->where('script_id', $script_id)
  4529. ->where('id', '<>', $group_id) // 排除当前组
  4530. ->where('is_deleted', 0)
  4531. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4532. // 检查新范围是否与现有范围重叠
  4533. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4534. // 新范围的开始在现有范围内
  4535. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4536. ->where('end_episode_number', '>=', $start_episode_sequence);
  4537. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4538. // 新范围的结束在现有范围内
  4539. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4540. ->where('end_episode_number', '>=', $end_episode_sequence);
  4541. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4542. // 新范围完全包含现有范围
  4543. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4544. ->where('end_episode_number', '<=', $end_episode_sequence);
  4545. });
  4546. })
  4547. ->select('start_episode_number', 'end_episode_number')
  4548. ->get();
  4549. if ($exists_groups->isNotEmpty()) {
  4550. $conflict_ranges = [];
  4551. foreach ($exists_groups as $group) {
  4552. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4553. }
  4554. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4555. }
  4556. $episode_content = getProp($data, 'episode_content');
  4557. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  4558. 'content' => $episode_content,
  4559. 'start_episode_number' => $start_episode_sequence,
  4560. 'end_episode_number' => $end_episode_sequence,
  4561. 'updated_at' => date('Y-m-d H:i:s')
  4562. ]);
  4563. $script_arr =getProp($data, 'script', []);
  4564. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  4565. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4566. $script_id = getProp($data, 'script_id');
  4567. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  4568. try {
  4569. DB::beginTransaction();
  4570. $update_data = [
  4571. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4572. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4573. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4574. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4575. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4576. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4577. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4578. 'status' => 3,
  4579. 'start_episode_sequence' => $start_episode_sequence,
  4580. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  4581. 'episode_num' => count($script_arr['episodes']),
  4582. 'updated_at' => date('Y-m-d H:i:s')
  4583. ];
  4584. // 保存剧本内容
  4585. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  4586. if (!$boolen) {
  4587. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  4588. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  4589. Utils::throwError('20003:剧本内容保存失败');
  4590. }
  4591. // 保存分集内容
  4592. // 删除历史分集内容
  4593. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  4594. $episodes = [];
  4595. $sequence = 1;
  4596. foreach ($script_arr['episodes'] as $episode) {
  4597. $segment_number = 1;
  4598. foreach($episode['segments'] as $segment) {
  4599. $episodes[] = [
  4600. 'script_id' => $script_id,
  4601. 'episode_number' => $episode['episode_number'],
  4602. 'title' => $episode['title'],
  4603. // 'content' => $episode['content'],
  4604. 'content' => '',
  4605. 'segment_number' => $segment_number,
  4606. 'segment_content' => $segment['segment_content'],
  4607. 'sequence' => $sequence,
  4608. 'created_at' => date('Y-m-d H:i:s'),
  4609. 'updated_at' => date('Y-m-d H:i:s')
  4610. ];
  4611. $sequence++;
  4612. $segment_number++;
  4613. }
  4614. }
  4615. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4616. if (!$boolen2) {
  4617. dLog('deepseek')->info('分集内容保存失败', $episodes);
  4618. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  4619. Utils::throwError('20003:分集内容保存失败');
  4620. }
  4621. } catch (\Exception $e) {
  4622. DB::rollBack();
  4623. Utils::throwError('20003:'.$e->getMessage());
  4624. }
  4625. DB::commit();
  4626. return true;
  4627. }
  4628. public function getBookContent($data) {
  4629. $bid = getProp($data, 'bid');
  4630. $start_sequence = getProp($data, 'start_sequence');
  4631. $end_sequence = getProp($data, 'end_sequence');
  4632. $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])
  4633. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  4634. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  4635. return $return_content;
  4636. }
  4637. public function exportScript($data) {
  4638. $filename = getProp($data, 'filename');
  4639. $script_id = getProp($data, 'script_id');
  4640. $group_id = getProp($data, 'group_id');
  4641. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  4642. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  4643. if (!$script) Utils::throwError('20003:该剧本不存在!');
  4644. $script = (array)$script;
  4645. // 获取分集组信息
  4646. if ($group_id) {
  4647. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4648. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4649. ->get()->map(function($value) {
  4650. return (array)$value;
  4651. })->toArray();
  4652. }else {
  4653. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4654. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4655. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  4656. return (array)$value;
  4657. })->toArray();
  4658. }
  4659. if (!$groups) Utils::throwError('20003:分集不存在');
  4660. $script['group'] = $groups;
  4661. $export_type = getProp($data, 'export_type', 'txt');
  4662. // 生成文件名
  4663. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  4664. // 根据导出类型生成不同格式的文件
  4665. switch ($export_type) {
  4666. case 'txt':
  4667. return $this->exportScriptAsTxt($script, $filename);
  4668. case 'pdf':
  4669. return $this->exportScriptAsPdf($script, $filename);
  4670. default:
  4671. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  4672. }
  4673. }
  4674. /**
  4675. * 导出剧本为TXT格式
  4676. */
  4677. private function exportScriptAsTxt($script, $filename) {
  4678. // 构建TXT内容
  4679. $content = $this->buildScriptContent($script);
  4680. // 设置响应头,直接下载
  4681. header('Content-Type: text/plain; charset=utf-8');
  4682. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  4683. header('Content-Length: ' . strlen($content));
  4684. // 输出内容并结束
  4685. echo $content;
  4686. exit();
  4687. }
  4688. /**
  4689. * 导出剧本为PDF格式
  4690. */
  4691. private function exportScriptAsPdf($script, $filename) {
  4692. // 使用HTML转PDF的方式来更好地支持中文
  4693. $htmlContent = $this->buildScriptHtmlForPdf($script);
  4694. // 创建PDF实例
  4695. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  4696. // 设置文档信息
  4697. $pdf->SetCreator('剧本导出系统');
  4698. $pdf->SetAuthor('系统');
  4699. $pdf->SetTitle($script['script_name']);
  4700. $pdf->SetSubject('剧本导出');
  4701. // 设置边距
  4702. $pdf->SetMargins(15, 15, 15);
  4703. $pdf->SetAutoPageBreak(TRUE, 15);
  4704. // 添加页面
  4705. $pdf->AddPage();
  4706. // 注册并使用 simsun.ttf 字体
  4707. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  4708. // 使用HTML内容生成PDF
  4709. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  4710. // 直接输出PDF文件供下载
  4711. header('Content-Type: application/pdf');
  4712. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  4713. // 直接输出PDF内容
  4714. $pdf->Output($filename . '.pdf', 'D');
  4715. exit();
  4716. }
  4717. /**
  4718. * 构建用于PDF的HTML内容
  4719. */
  4720. private function buildScriptHtmlForPdf($script) {
  4721. $html = '<style>
  4722. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  4723. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  4724. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  4725. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  4726. .info { margin-bottom: 8px; }
  4727. .group { margin-bottom: 30px; page-break-inside: avoid; }
  4728. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  4729. .segment { margin-bottom: 10px; margin-left: 20px; }
  4730. .episode-content { white-space: pre-wrap; }
  4731. </style>';
  4732. // 标题
  4733. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  4734. // 处理分组数据
  4735. if (!empty($script['group']) && is_array($script['group'])) {
  4736. $groups = (array)$script['group'];
  4737. foreach ($groups as $group) {
  4738. $html .= '<div class="group">';
  4739. // 分组标题
  4740. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  4741. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  4742. // 故事梗概
  4743. if (!empty($group['intro'])) {
  4744. $html .= '<h3>故事梗概</h3>';
  4745. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  4746. }
  4747. // 剧本亮点
  4748. if (!empty($group['highlights'])) {
  4749. $html .= '<h3>剧本亮点</h3>';
  4750. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  4751. }
  4752. // 人物关系
  4753. if (!empty($group['role_relationship'])) {
  4754. $html .= '<h3>人物关系</h3>';
  4755. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  4756. }
  4757. // 核心矛盾
  4758. if (!empty($group['core_contradiction'])) {
  4759. $html .= '<h3>核心矛盾</h3>';
  4760. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  4761. }
  4762. // 主体列表
  4763. if (!empty($group['roles']) && is_array($group['roles'])) {
  4764. $html .= '<h3>主体列表</h3>';
  4765. $html .= '<ul>';
  4766. foreach ($group['roles'] as $role) {
  4767. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  4768. }
  4769. $html .= '</ul>';
  4770. }
  4771. // 美术风格
  4772. if (!empty($group['art_style'])) {
  4773. $html .= '<h3>美术风格</h3>';
  4774. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  4775. }
  4776. // 场景列表
  4777. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4778. $html .= '<h3>场景列表</h3>';
  4779. $html .= '<ul>';
  4780. foreach ($group['scenes'] as $scene) {
  4781. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  4782. }
  4783. $html .= '</ul>';
  4784. }
  4785. // 分集剧本
  4786. if (!empty($group['episode_content'])) {
  4787. $html .= '<h3>分集剧本</h3>';
  4788. // 去除零宽字符和其他不可见字符
  4789. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  4790. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  4791. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  4792. }
  4793. $html .= '</div>';
  4794. }
  4795. }
  4796. return $html;
  4797. }
  4798. /**
  4799. * 构建PDF内容
  4800. */
  4801. private function buildPdfContent($pdf, $script) {
  4802. // 标题
  4803. $pdf->SetFont('dejavusans', 'B', 18);
  4804. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  4805. $pdf->Ln(5);
  4806. // 基本信息
  4807. $pdf->SetFont('dejavusans', '', 12);
  4808. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  4809. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  4810. $pdf->Ln(5);
  4811. // 剧本简介
  4812. if (!empty($script['intro'])) {
  4813. $pdf->SetFont('dejavusans', 'B', 14);
  4814. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  4815. $pdf->SetFont('dejavusans', '', 12);
  4816. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  4817. $pdf->Ln(3);
  4818. }
  4819. // 亮点
  4820. if (!empty($script['highlights'])) {
  4821. $pdf->SetFont('dejavusans', 'B', 14);
  4822. $pdf->Cell(0, 10, '亮点', 0, 1);
  4823. $pdf->SetFont('dejavusans', '', 12);
  4824. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  4825. $pdf->Ln(3);
  4826. }
  4827. // 核心矛盾
  4828. if (!empty($script['core_contradiction'])) {
  4829. $pdf->SetFont('dejavusans', 'B', 14);
  4830. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  4831. $pdf->SetFont('dejavusans', '', 12);
  4832. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  4833. $pdf->Ln(3);
  4834. }
  4835. // 艺术风格
  4836. if (!empty($script['art_style'])) {
  4837. $pdf->SetFont('dejavusans', 'B', 14);
  4838. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  4839. $pdf->SetFont('dejavusans', '', 12);
  4840. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  4841. $pdf->Ln(3);
  4842. }
  4843. // 备注
  4844. if (!empty($script['remark'])) {
  4845. $pdf->SetFont('dejavusans', 'B', 14);
  4846. $pdf->Cell(0, 10, '备注', 0, 1);
  4847. $pdf->SetFont('dejavusans', '', 12);
  4848. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  4849. $pdf->Ln(3);
  4850. }
  4851. // 角色列表
  4852. if (!empty($script['roles']) && is_array($script['roles'])) {
  4853. $pdf->SetFont('dejavusans', 'B', 14);
  4854. $pdf->Cell(0, 10, '角色列表', 0, 1);
  4855. $pdf->SetFont('dejavusans', '', 12);
  4856. foreach ($script['roles'] as $index => $role) {
  4857. if (is_array($role) || is_object($role)) {
  4858. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  4859. } else {
  4860. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  4861. }
  4862. }
  4863. $pdf->Ln(3);
  4864. }
  4865. // 角色关系
  4866. if (!empty($script['role_relationship'])) {
  4867. $pdf->SetFont('dejavusans', 'B', 14);
  4868. $pdf->Cell(0, 10, '角色关系', 0, 1);
  4869. $pdf->SetFont('dejavusans', '', 12);
  4870. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  4871. $pdf->Ln(3);
  4872. }
  4873. // 场景列表
  4874. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  4875. $pdf->SetFont('dejavusans', 'B', 14);
  4876. $pdf->Cell(0, 10, '场景列表', 0, 1);
  4877. $pdf->SetFont('dejavusans', '', 12);
  4878. foreach ($script['scenes'] as $index => $scene) {
  4879. if (is_array($scene) || is_object($scene)) {
  4880. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  4881. } else {
  4882. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  4883. }
  4884. }
  4885. $pdf->Ln(5);
  4886. }
  4887. // 分集内容
  4888. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  4889. $pdf->SetFont('dejavusans', 'B', 16);
  4890. $pdf->Cell(0, 12, '分集内容', 0, 1);
  4891. $pdf->Ln(3);
  4892. foreach ($script['episodes'] as $episode) {
  4893. // 检查是否需要新页面
  4894. if ($pdf->GetY() > 250) {
  4895. $pdf->AddPage();
  4896. }
  4897. $pdf->SetFont('dejavusans', 'B', 14);
  4898. $episodeTitle = '第' . $episode['episode_number'] . '集';
  4899. if (!empty($episode['title'])) {
  4900. $episodeTitle .= ':' . $episode['title'];
  4901. }
  4902. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  4903. // 处理分段内容
  4904. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  4905. $pdf->SetFont('dejavusans', '', 12);
  4906. foreach ($episode['segments'] as $segment) {
  4907. if (!empty($segment['segment_content'])) {
  4908. // 如果有分段编号,显示分段标题
  4909. if (!empty($segment['segment_number'])) {
  4910. $pdf->SetFont('dejavusans', 'B', 12);
  4911. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  4912. $pdf->SetFont('dejavusans', '', 12);
  4913. }
  4914. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  4915. $pdf->Ln(2);
  4916. }
  4917. }
  4918. }
  4919. $pdf->Ln(5);
  4920. }
  4921. }
  4922. }
  4923. /**
  4924. * 构建剧本文本内容
  4925. */
  4926. private function buildScriptContent($script) {
  4927. $content = '';
  4928. $groups = $script['group'];
  4929. $groups = (array)$groups;
  4930. foreach ($groups as $group) {
  4931. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  4932. // 剧本基本信息
  4933. if (!empty($group['intro'])) {
  4934. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  4935. }
  4936. if (!empty($group['highlights'])) {
  4937. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  4938. }
  4939. if (!empty($group['role_relationship'])) {
  4940. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  4941. }
  4942. if (!empty($group['core_contradiction'])) {
  4943. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  4944. }
  4945. if (!empty($group['roles']) && is_array($group['roles'])) {
  4946. $content .= "###主体列表\n";
  4947. foreach ($group['roles'] as $role) {
  4948. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  4949. }
  4950. $content .= "\n\n";
  4951. }
  4952. if (!empty($group['art_style'])) {
  4953. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  4954. }
  4955. // 场景信息
  4956. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4957. $content .= "###场景列表\n";
  4958. foreach ($group['scenes'] as $scene) {
  4959. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  4960. }
  4961. $content .= "\n\n";
  4962. }
  4963. // 分集内容
  4964. if (!empty($group['episode_content'])) {
  4965. $content .= "###分集剧本\n";
  4966. $content .= $group['episode_content'];
  4967. // foreach ($script['episodes'] as $episode) {
  4968. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  4969. // // if (!empty($episode['episode_name'])) {
  4970. // // $content .= ":" . $episode['episode_name'];
  4971. // // }
  4972. // // $content .= "\n";
  4973. // $content .= $episode['episode_content'] . "\n\n";
  4974. // }
  4975. }
  4976. }
  4977. return $content;
  4978. }
  4979. /**
  4980. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4981. *
  4982. * @param array $data 包含以下参数:
  4983. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4984. * - question: 用户问题(可选)
  4985. * - model: 使用的模型(r1 或 v3,默认 v3)
  4986. * @return \Generator 返回生成器,用于流式输出
  4987. */
  4988. public function addChat($data) {
  4989. $uid = Site::getUid();
  4990. $anime_id = getProp($data, 'anime_id');
  4991. if (!$anime_id) Utils::throwError('20003:请选择对话');
  4992. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4993. if (!$anime) Utils::throwError('20003:对话不存在');
  4994. $file = getProp($data, 'file');
  4995. $content = getProp($data, 'content', '');
  4996. $bid = getProp($data, 'bid', 0);
  4997. $script_id = getProp($data, 'script_id', 0);
  4998. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  4999. $prompt = getProp($data, 'prompt');
  5000. $user_anime_name = getProp($anime, 'anime_name');
  5001. // 处理文本模型
  5002. $model = getProp($data, 'model');
  5003. if (!$model) {
  5004. // 用户没有输入,从anime表获取
  5005. $model = getProp($anime, 'model');
  5006. if (!$model) {
  5007. // anime表也没有,使用默认值
  5008. $model = 'doubao-seed-2-0-mini-260215';
  5009. }
  5010. }
  5011. // 验证模型是否在可用模型表中
  5012. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5013. $model = 'doubao-seed-2-0-mini-260215';
  5014. }
  5015. $is_multi = getProp($anime, 'is_multi');
  5016. $is_single = (int)$is_multi !== 1;
  5017. // 积分余额预检(仅单剧集模式收费)
  5018. if ($is_single) {
  5019. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5020. }
  5021. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5022. if ($prompt) {
  5023. $question .= "本次修改要求如下:\n{$prompt}";
  5024. }
  5025. // if (!$file && !$content && !$bid) {
  5026. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5027. // }
  5028. // 提取文件内容
  5029. if ($file) {
  5030. $content = $this->extractFileContent($file);
  5031. if (!$content) {
  5032. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5033. }
  5034. } elseif ($script_id) {
  5035. $content = $this->getContentByScriptId($script_id);
  5036. if (!$content) {
  5037. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5038. }
  5039. } elseif ($bid) {
  5040. $content = $this->getContentByBid($bid);
  5041. if (!$content) {
  5042. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5043. }
  5044. } elseif ($content) {
  5045. $content = filterContent($content);
  5046. } else {
  5047. $content = getProp($anime, 'content');
  5048. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5049. $need_generate_content = true;
  5050. }
  5051. }
  5052. // 美术风格
  5053. $input_art_style = getProp($data, 'art_style');
  5054. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5055. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5056. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5057. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5058. 中年女:邻居阿姨
  5059. 老年男:幽默大爷
  5060. 老年女:婆婆
  5061. 萌娃:奶气萌娃";
  5062. // 判断是否需要生成原文内容
  5063. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5064. // 如果需要生成原文内容,添加额外的要求
  5065. $content_generation_requirement = $need_generate_content
  5066. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5067. : "";
  5068. // 美术风格
  5069. if (!$mappedArtStyle) {
  5070. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5071. }else {
  5072. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5073. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5074. }else {
  5075. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5076. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5077. }
  5078. }
  5079. $systemPrompt = $is_single
  5080. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5081. 强制要求:
  5082. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5083. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5084. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5085. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5086. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5087. 普通要求:
  5088. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5089. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5090. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  5091. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5092. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5093. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5094. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5095. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5096. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5097. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5098. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5099. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5100. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5101. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5102. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5103. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5104. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5105. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5106. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5107. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5108. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5109. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5110. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5111. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5112. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5113. 5.{$mappedArtStyle_prompt}\n\n
  5114. 示例如下:\n
  5115. ###剧本名:西昆仑
  5116. ###故事梗概
  5117. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5118. ###剧本亮点
  5119. 亮点1:绝境奇药,生死一线
  5120. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5121. 亮点2:结拜兄妹,化解尴尬
  5122. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5123. 亮点3:纤发夺命,情愫暗涌
  5124. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5125. ###人物关系
  5126. 阿雪与梁萧之间存在兄妹之情。
  5127. ###核心矛盾
  5128. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5129. ###主体列表
  5130. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5131. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5132. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5133. 姿态:站立。}{{甜心小美}}
  5134. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5135. 全景,正面拍摄,青年女性,亚洲人。
  5136. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5137. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5138. 姿态:站立。}{{阳光青年}}
  5139. ###美术风格
  5140. 基础画风风格词:厚涂古风
  5141. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5142. ###场景列表
  5143. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5144. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5145. 无人物。}
  5146. ###分镜剧本
  5147. ##第1幕:徐家老旧厨房 白天 室内
  5148. 分镜1
  5149. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5150. 场景:徐家老旧厨房
  5151. 构图设计:全景,低角度仰视
  5152. 运镜调度:手持拍摄
  5153. 配音角色:旁白
  5154. 出镜角色:许芸-校服装、徐母
  5155. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5156. 画面类型:普通画面
  5157. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5158. 分镜2
  5159. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5160. 场景:徐家老旧厨房
  5161. 构图设计:近景,徐母面部特写
  5162. 运镜调度:固定镜头
  5163. 配音角色:徐母
  5164. 出镜角色:徐母
  5165. 台词内容:问我夜不归宿死哪儿去了。
  5166. 画面类型:对口型
  5167. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5168. ##第2幕:徐家简陋客厅 黄昏 室内
  5169. 分镜3
  5170. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5171. 场景:徐家简陋客厅
  5172. 构图设计:全景,景深虚化
  5173. 运镜调度:固定镜头
  5174. 配音角色:旁白
  5175. 出镜角色:无
  5176. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5177. 画面类型:普通画面
  5178. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5179. 分镜4
  5180. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5181. 场景:徐家简陋客厅
  5182. 构图设计:特写,火车票
  5183. 运镜调度:固定镜头
  5184. 配音角色:旁白
  5185. 出镜角色:无
  5186. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5187. 画面类型:普通画面
  5188. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5189. "
  5190. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5191. 强制要求:\n
  5192. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5193. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5194. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5195. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5196. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5197. 普通要求:\n
  5198. 1.剧本名(必须生成)必须与文档内容高度相关
  5199. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5200. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5201. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5202. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5203. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5204. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5205. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5206. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5207. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5208. 4.{$mappedArtStyle_prompt}\n\n
  5209. 示例如下:\n
  5210. ###剧本名:西昆仑
  5211. ###故事梗概
  5212. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5213. ###剧本亮点
  5214. 亮点1:绝境奇药,生死一线
  5215. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5216. 亮点2:结拜兄妹,化解尴尬
  5217. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5218. 亮点3:纤发夺命,情愫暗涌
  5219. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5220. ###人物关系
  5221. 阿雪与梁萧之间存在兄妹之情。
  5222. ###核心矛盾
  5223. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5224. ###主体列表
  5225. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5226. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5227. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5228. 姿态:站立。}{{甜心小美}}
  5229. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5230. 全景,正面拍摄,青年女性,亚洲人。
  5231. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5232. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5233. 姿态:站立。}{{阳光青年}}
  5234. ###美术风格
  5235. 基础画风风格词:厚涂古风
  5236. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5237. ###场景列表
  5238. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5239. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5240. 无人物。}";
  5241. // 构建消息
  5242. $messages = [
  5243. [
  5244. 'role' => 'system',
  5245. 'content' => $systemPrompt
  5246. ],
  5247. [
  5248. 'role' => 'user',
  5249. 'content' => "以下是文档内容:
  5250. {$content}
  5251. 用户问题:
  5252. {$question}"
  5253. ]
  5254. ];
  5255. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5256. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5257. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5258. if ($model === 'deepseek-chat') {
  5259. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5260. $model = 'deepseek-v4-flash';
  5261. $thinkingMode = 'disabled';
  5262. } elseif ($model === 'deepseek-reasoner') {
  5263. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5264. $model = 'deepseek-v4-flash';
  5265. $thinkingMode = 'enabled';
  5266. }
  5267. $post_data = [
  5268. 'model' => $model,
  5269. 'messages' => $messages,
  5270. // 'max_tokens' => 8192,
  5271. 'temperature' => 0.7,
  5272. 'frequency_penalty' => 0,
  5273. 'presence_penalty' => 0,
  5274. 'response_format' => ['type' => 'text'],
  5275. 'thinking' => ['type'=>$thinkingMode],
  5276. 'stream' => true // 启用流式输出
  5277. ];
  5278. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5279. // 根据模型类型选择调用方法
  5280. $fullContent = '';
  5281. $fullReasoningContent = '';
  5282. $usage = [];
  5283. try {
  5284. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5285. // DeepSeek 官方模型使用 DeepSeek API
  5286. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5287. } else if (in_array($model, $this->gpt_text_models)) {
  5288. // GPT-5.4 模型使用 TokenRouter API
  5289. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5290. } else if (in_array($model, $this->gemini_text_models)) {
  5291. // Gemini 模型使用 Gemini API
  5292. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  5293. } else {
  5294. // 其他模型使用火山引擎API
  5295. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5296. }
  5297. // 验证返回值类型
  5298. if (!is_iterable($streamGenerator)) {
  5299. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5300. dLog('deepseek')->error('addChat流式生成器无效', [
  5301. 'generator_type' => $errorType,
  5302. 'model' => $model,
  5303. 'anime_id' => $anime_id
  5304. ]);
  5305. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5306. 'type' => $errorType,
  5307. 'model' => $model
  5308. ]);
  5309. yield [
  5310. 'type' => 'error',
  5311. 'script' => [],
  5312. 'episode' => [],
  5313. 'answer' => '',
  5314. 'reasoning' => '',
  5315. 'usage' => [],
  5316. 'error' => '接口返回数据异常,请重新请求'
  5317. ];
  5318. return;
  5319. }
  5320. // 处理流式输出
  5321. foreach ($streamGenerator as $chunk) {
  5322. if (isset($chunk['type'])) {
  5323. if ($chunk['type'] === 'done') {
  5324. // 最终结果
  5325. $fullContent = $chunk['full_content'];
  5326. $fullReasoningContent = $chunk['full_reasoning'];
  5327. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5328. } else {
  5329. // 逐块yield数据
  5330. yield $chunk;
  5331. }
  5332. }
  5333. }
  5334. } catch (\Exception $e) {
  5335. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5336. 'model' => $model,
  5337. 'anime_id' => $anime_id,
  5338. 'trace' => $e->getTraceAsString()
  5339. ]);
  5340. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5341. 'error' => $e->getMessage(),
  5342. 'model' => $model
  5343. ]);
  5344. yield [
  5345. 'type' => 'error',
  5346. 'script' => [],
  5347. 'episode' => [],
  5348. 'answer' => '',
  5349. 'reasoning' => '',
  5350. 'usage' => [],
  5351. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5352. ];
  5353. return;
  5354. }
  5355. dLog('deepseek')->info('完整内容: '.$fullContent);
  5356. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5357. // 处理完整内容并返回最终结果
  5358. $script_arr = [];
  5359. if ($fullContent) {
  5360. $script_arr = handleScriptContent($fullContent);
  5361. dLog('deepseek')->info('解析内容', $script_arr);
  5362. logDB('deepseek', 'info', '解析内容', $script_arr);
  5363. }
  5364. if (empty($script_arr['roles'])) {
  5365. // 未生成剧本相关内容,保存对话记录并返回提示
  5366. dLog('deepseek')->info('未生成剧本相关的内容');
  5367. try {
  5368. DB::beginTransaction();
  5369. $now = date('Y-m-d H:i:s');
  5370. // 保存对话记录
  5371. $records = [
  5372. [
  5373. 'uid' => $uid,
  5374. 'anime_id' => $anime_id,
  5375. 'sequence' => 0,
  5376. 'role' => 'user',
  5377. 'content' => $prompt,
  5378. 'created_at' => $now,
  5379. 'updated_at' => $now
  5380. ],
  5381. [
  5382. 'uid' => $uid,
  5383. 'anime_id' => $anime_id,
  5384. 'sequence' => 0,
  5385. 'role' => 'assistant',
  5386. // 'content' => $fullContent,
  5387. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5388. 'created_at' => $now,
  5389. 'updated_at' => $now
  5390. ]
  5391. ];
  5392. DB::table('mp_anime_records')->insert($records);
  5393. DB::commit();
  5394. } catch (\Exception $e) {
  5395. DB::rollBack();
  5396. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5397. }
  5398. yield [
  5399. 'type' => 'done',
  5400. 'script' => [],
  5401. 'episode' => [],
  5402. 'answer' => $fullContent,
  5403. 'reasoning' => $fullReasoningContent,
  5404. 'usage' => $usage,
  5405. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5406. ];
  5407. return;
  5408. }
  5409. // 如果需要生成原文内容,从script_arr中提取
  5410. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5411. $content = $script_arr['content'];
  5412. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5413. if (!$content) {
  5414. yield [
  5415. 'type' => 'done',
  5416. 'script' => [],
  5417. 'episode' => [],
  5418. 'answer' => $fullContent,
  5419. 'reasoning' => $fullReasoningContent,
  5420. 'usage' => $usage,
  5421. 'error' => '未生成剧本内容,请调整提示词再试'
  5422. ];
  5423. return;
  5424. }
  5425. }
  5426. // 替换美术风格
  5427. if ($mappedArtStyle !== '') {
  5428. $script_arr['art_style'] = $mappedArtStyle;
  5429. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5430. }
  5431. // 新建动漫
  5432. if ($user_anime_name == '新剧本策划') {
  5433. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5434. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5435. // if (!$anime_name) {
  5436. // // 未识别到剧本名,保存对话记录并返回提示
  5437. // dLog('deepseek')->info('未能识别到剧本名称');
  5438. // try {
  5439. // DB::beginTransaction();
  5440. // $now = date('Y-m-d H:i:s');
  5441. // // 保存对话记录
  5442. // $records = [
  5443. // [
  5444. // 'uid' => $uid,
  5445. // 'anime_id' => $anime_id,
  5446. // 'sequence' => 0,
  5447. // 'role' => 'user',
  5448. // 'content' => $prompt,
  5449. // 'created_at' => $now,
  5450. // 'updated_at' => $now
  5451. // ],
  5452. // [
  5453. // 'uid' => $uid,
  5454. // 'anime_id' => $anime_id,
  5455. // 'sequence' => 0,
  5456. // 'role' => 'assistant',
  5457. // 'content' => '未能生成剧本名称,请重试',
  5458. // 'created_at' => $now,
  5459. // 'updated_at' => $now
  5460. // ]
  5461. // ];
  5462. // DB::table('mp_anime_records')->insert($records);
  5463. // DB::commit();
  5464. // } catch (\Exception $e) {
  5465. // DB::rollBack();
  5466. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5467. // }
  5468. // yield [
  5469. // 'type' => 'done',
  5470. // 'script' => [],
  5471. // 'episode' => [],
  5472. // 'answer' => $fullContent,
  5473. // 'reasoning' => $fullReasoningContent,
  5474. // 'usage' => $usage,
  5475. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  5476. // ];
  5477. // return;
  5478. // }
  5479. // 确认对话名称唯一性
  5480. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5481. $anime_name = $anime_name . '_' . date('YmdHis');
  5482. }
  5483. }else {
  5484. $anime_name = $user_anime_name;
  5485. }
  5486. $table_data = [
  5487. 'user_id' => $uid,
  5488. 'anime_name' => $anime_name,
  5489. 'model' => $model,
  5490. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5491. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5492. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5493. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5494. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5495. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5496. 'art_style_type' => $input_art_style,
  5497. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5498. 'status' => '解析完成',
  5499. 'content' => $content,
  5500. 'is_multi' => $is_multi,
  5501. 'ace_mode' => $ace_mode,
  5502. 'generate_status' => '待执行',
  5503. 'updated_at' => date('Y-m-d H:i:s')
  5504. ];
  5505. if ($table_data['content']) {
  5506. $chapters = splitContent($table_data['content']);
  5507. $chapter_count = count($chapters);
  5508. if ($chapter_count > 0) {
  5509. $table_data['start_episode_sequence'] = 1;
  5510. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5511. }
  5512. }
  5513. // 如果有剧本ID则进行绑定
  5514. if ($script_id) {
  5515. $table_data['script_id'] = $script_id;
  5516. }
  5517. $single_episode = [];
  5518. try {
  5519. DB::beginTransaction();
  5520. $now = date('Y-m-d H:i:s');
  5521. // 更新动漫大纲
  5522. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5523. if (!$boolen) {
  5524. dLog('deepseek')->info('动漫保存失败', $table_data);
  5525. Utils::throwError('20003:动漫保存失败');
  5526. }
  5527. // 保存对话记录
  5528. $records = [
  5529. [
  5530. 'uid' => $uid,
  5531. 'anime_id' => $anime_id,
  5532. 'sequence' => 0,
  5533. 'role' => 'user',
  5534. 'content' => $prompt,
  5535. 'created_at' => date('Y-m-d H:i:s'),
  5536. 'updated_at' => date('Y-m-d H:i:s')
  5537. ],
  5538. [
  5539. 'uid' => $uid,
  5540. 'anime_id' => $anime_id,
  5541. 'sequence' => 0,
  5542. 'role' => 'assistant',
  5543. 'content' => $fullContent,
  5544. 'created_at' => date('Y-m-d H:i:s'),
  5545. 'updated_at' => date('Y-m-d H:i:s')
  5546. ]
  5547. ];
  5548. // 保存对话记录
  5549. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5550. if (!$boolen3) {
  5551. Utils::throwError('20003:对话记录保存失败');
  5552. }
  5553. if ($is_single) {
  5554. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5555. if (empty($episode_arr['acts'])) {
  5556. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5557. }
  5558. $saveResult = $this->saveEpisodeVersionData(
  5559. $anime_id,
  5560. 1,
  5561. $episode_arr,
  5562. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5563. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5564. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5565. null,
  5566. null,
  5567. false,
  5568. $content,
  5569. $now
  5570. );
  5571. $single_episode = $saveResult['episode'];
  5572. $episode_id = $saveResult['episode_id'];
  5573. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5574. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5575. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5576. 'props' => json_encode($saveResult['merged_props'], 256),
  5577. 'updated_at' => $now
  5578. ]);
  5579. if ($boolen5 === false) {
  5580. Utils::throwError('20003:单剧集主表资源同步失败');
  5581. }
  5582. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5583. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5584. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5585. $episode_record_content = '确认分镜大纲';
  5586. if ($content !== '') {
  5587. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5588. }
  5589. $episode_records = [
  5590. [
  5591. 'uid' => $uid,
  5592. 'anime_id' => $anime_id,
  5593. 'role' => 'user',
  5594. 'content' => $episode_record_content,
  5595. 'sequence' => 1,
  5596. 'episode_id' => $episode_id,
  5597. 'created_at' => $now,
  5598. 'updated_at' => $now
  5599. ],
  5600. [
  5601. 'uid' => $uid,
  5602. 'anime_id' => $anime_id,
  5603. 'role' => 'assistant',
  5604. 'content' => $fullContent,
  5605. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5606. 'sequence' => 1,
  5607. 'episode_id' => $episode_id,
  5608. 'created_at' => $now,
  5609. 'updated_at' => $now
  5610. ]
  5611. ];
  5612. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5613. if (!$boolen4) {
  5614. Utils::throwError('20003:单剧集分镜记录保存失败');
  5615. }
  5616. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  5617. if ($is_single && !empty($single_episode)) {
  5618. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5619. 'anime_id' => $anime_id,
  5620. 'episode_id' => $episode_id ?? 0,
  5621. 'model' => $model,
  5622. 'source' => 'addChat',
  5623. ]);
  5624. }
  5625. }
  5626. }catch (\Exception $e) {
  5627. DB::rollBack();
  5628. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5629. yield [
  5630. 'type' => 'done',
  5631. 'answer' => $fullContent,
  5632. 'reasoning' => $fullReasoningContent,
  5633. 'usage' => $usage,
  5634. 'error' => $e->getMessage(),
  5635. ];
  5636. return;
  5637. }
  5638. DB::commit();
  5639. dLog('deepseek')->info('保存完毕');
  5640. if ($is_single && !empty($single_episode)) {
  5641. // $this->batchSetGlobalRoleImg([
  5642. // 'anime_id' => $anime_id,
  5643. // ]);
  5644. // $this->batchSetGlobalSceneImg([
  5645. // 'anime_id' => $anime_id,
  5646. // ]);
  5647. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5648. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5649. }
  5650. $table_data['anime_id'] = $anime_id;
  5651. $table_data['roles'] = json_decode($table_data['roles'], true);
  5652. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5653. // $table_data['episodes'] = $script_arr['episodes'];
  5654. unset($table_data['created_at']);
  5655. unset($table_data['updated_at']);
  5656. unset($table_data['status']);
  5657. dLog('deepseek')->info('开始返回');
  5658. yield [
  5659. 'type' => 'done',
  5660. 'script' => $table_data,
  5661. 'episode' => $single_episode,
  5662. 'answer' => $fullContent,
  5663. 'reasoning' => $fullReasoningContent,
  5664. 'usage' => $usage
  5665. ];
  5666. }
  5667. public function reGenerateAnime($data) {
  5668. $uid = Site::getUid();
  5669. $file = getProp($data, 'file');
  5670. $content = getProp($data, 'content', '');
  5671. $bid = getProp($data, 'bid', 0);
  5672. $script_id = getProp($data, 'script_id', 0);
  5673. $anime_id = getProp($data, 'anime_id');
  5674. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5675. if (!$anime) {
  5676. Utils::throwError('20003:该对话不存在');
  5677. }
  5678. $user_anime_name = getProp($anime, 'anime_name');
  5679. $prompt = getProp($data, 'prompt');
  5680. // 处理文本模型
  5681. $model = getProp($data, 'model');
  5682. if (!$model) {
  5683. // 用户没有输入,从anime表获取
  5684. $model = getProp($anime, 'model');
  5685. if (!$model) {
  5686. // anime表也没有,使用默认值
  5687. $model = 'doubao-seed-2-0-mini-260215';
  5688. }
  5689. }
  5690. // 验证模型是否在可用模型表中
  5691. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5692. $model = 'doubao-seed-2-0-mini-260215';
  5693. }
  5694. $is_multi = getProp($anime, 'is_multi', 1);
  5695. $is_single = (int)$is_multi !== 1;
  5696. // 积分余额预检(仅单剧集模式收费)
  5697. if ($is_single) {
  5698. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5699. }
  5700. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  5701. if ($is_single) {
  5702. $episode_exists = DB::table('mp_anime_episodes')
  5703. ->where('anime_id', $anime_id)
  5704. ->where('sequence', 1)
  5705. ->exists();
  5706. if ($episode_exists) {
  5707. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  5708. }
  5709. }
  5710. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5711. if ($prompt) {
  5712. $question .= "本次修改要求如下:\n{$prompt}";
  5713. }
  5714. // 提取文件内容
  5715. if ($file) {
  5716. $content = $this->extractFileContent($file);
  5717. if (!$content) {
  5718. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5719. }
  5720. } elseif ($script_id) {
  5721. $content = $this->getContentByScriptId($script_id);
  5722. if (!$content) {
  5723. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5724. }
  5725. } elseif ($bid) {
  5726. $content = $this->getContentByBid($bid);
  5727. if (!$content) {
  5728. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5729. }
  5730. } elseif ($content) {
  5731. $content = filterContent($content);
  5732. }else {
  5733. $content = filterContent(getProp($anime, 'content'));
  5734. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5735. $need_generate_content = true;
  5736. }
  5737. }
  5738. // 判断是否需要生成原文内容
  5739. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5740. // 如果需要生成原文内容,添加额外的要求
  5741. $content_generation_requirement = $need_generate_content
  5742. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5743. : "";
  5744. // 美术风格
  5745. $input_art_style = getProp($anime, 'art_style');
  5746. if (!$input_art_style) {
  5747. $input_art_style = getProp($data, 'art_style');
  5748. }
  5749. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5750. // 美术风格
  5751. if (!$mappedArtStyle) {
  5752. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5753. }else {
  5754. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5755. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5756. }else {
  5757. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5758. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5759. }
  5760. }
  5761. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5762. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5763. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5764. 中年女:邻居阿姨
  5765. 老年男:幽默大爷
  5766. 老年女:婆婆
  5767. 萌娃:奶气萌娃";
  5768. $system_message = ['role'=>'system', 'content'=>$is_single
  5769. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5770. 强制要求:
  5771. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5772. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5773. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5774. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5775. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5776. 普通要求:
  5777. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5778. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5779. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5780. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5781. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5782. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5783. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5784. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5785. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5786. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5787. 3.$mappedArtStyle_prompt\n\n
  5788. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5789. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5790. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5791. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5792. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5793. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5794. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5795. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5796. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5797. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5798. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5799. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5800. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5801. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5802. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5803. 示例如下:\n
  5804. ###剧本名:西昆仑
  5805. ###故事梗概
  5806. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5807. ###剧本亮点
  5808. 亮点1:绝境奇药,生死一线
  5809. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5810. 亮点2:结拜兄妹,化解尴尬
  5811. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5812. 亮点3:纤发夺命,情愫暗涌
  5813. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5814. ###人物关系
  5815. 阿雪与梁萧之间存在兄妹之情。
  5816. ###核心矛盾
  5817. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5818. ###主体列表
  5819. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5820. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5821. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5822. 姿态:站立。}{{甜心小美}}
  5823. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5824. 全景,正面拍摄,青年女性,亚洲人。
  5825. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5826. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5827. 姿态:站立。}{{阳光青年}}
  5828. ###美术风格
  5829. 基础画风风格词:厚涂古风
  5830. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5831. ###场景列表
  5832. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5833. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5834. 无人物。}
  5835. ###分镜剧本
  5836. ##第1幕:徐家老旧厨房 白天 室内
  5837. 分镜1
  5838. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5839. 场景:徐家老旧厨房
  5840. 构图设计:全景,低角度仰视
  5841. 运镜调度:手持拍摄
  5842. 配音角色:旁白
  5843. 出镜角色:许芸-校服装、徐母
  5844. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5845. 画面类型:普通画面
  5846. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5847. 分镜2
  5848. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5849. 场景:徐家老旧厨房
  5850. 构图设计:近景,徐母面部特写
  5851. 运镜调度:固定镜头
  5852. 配音角色:徐母
  5853. 出镜角色:徐母
  5854. 台词内容:问我夜不归宿死哪儿去了。
  5855. 画面类型:对口型
  5856. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5857. ##第2幕:徐家简陋客厅 黄昏 室内
  5858. 分镜3
  5859. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5860. 场景:徐家简陋客厅
  5861. 构图设计:全景,景深虚化
  5862. 运镜调度:固定镜头
  5863. 配音角色:旁白
  5864. 出镜角色:无
  5865. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5866. 画面类型:普通画面
  5867. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5868. 分镜4
  5869. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5870. 场景:徐家简陋客厅
  5871. 构图设计:特写,火车票
  5872. 运镜调度:固定镜头
  5873. 配音角色:旁白
  5874. 出镜角色:无
  5875. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5876. 画面类型:普通画面
  5877. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5878. "
  5879. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5880. 强制要求:\n
  5881. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5882. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5883. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5884. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5885. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5886. 普通要求:\n
  5887. 1.剧本名(必须生成)必须与文档内容高度相关
  5888. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5889. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5890. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5891. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5892. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5893. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5894. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5895. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5896. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5897. 4.$mappedArtStyle_prompt\n\n
  5898. 示例如下:\n
  5899. ###剧本名:西昆仑
  5900. ###故事梗概
  5901. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5902. ###剧本亮点
  5903. 亮点1:绝境奇药,生死一线
  5904. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5905. 亮点2:结拜兄妹,化解尴尬
  5906. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5907. 亮点3:纤发夺命,情愫暗涌
  5908. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5909. ###人物关系
  5910. 阿雪与梁萧之间存在兄妹之情。
  5911. ###核心矛盾
  5912. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5913. ###主体列表
  5914. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5915. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5916. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5917. 姿态:站立。}{{甜心小美}}
  5918. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5919. 全景,正面拍摄,青年女性,亚洲人。
  5920. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5921. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5922. 姿态:站立。}{{阳光青年}}
  5923. ###美术风格
  5924. 基础画风风格词:厚涂古风
  5925. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5926. ###场景列表
  5927. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5928. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5929. 无人物。}"];
  5930. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  5931. $episode_count = $this->extractEpisodeNumber($prompt);
  5932. if ((int)getProp($anime, 'is_multi') !== 1) {
  5933. yield [
  5934. 'type' => 'done',
  5935. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  5936. 'reasoning' => '',
  5937. 'usage' => []
  5938. ];
  5939. return;
  5940. }
  5941. if ($episode_count) {
  5942. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  5943. $system_message = [
  5944. 'role' => 'system',
  5945. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5946. 强制要求:\n
  5947. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5948. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5949. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5950. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5951. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5952. 普通要求:\n
  5953. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5954. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5955. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5956. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5957. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5958. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5959. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5960. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5961. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5962. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  5963. 示例如下:\n
  5964. ###剧本名:西昆仑
  5965. ###故事梗概
  5966. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5967. ###剧本亮点
  5968. 亮点1:绝境奇药,生死一线
  5969. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5970. 亮点2:结拜兄妹,化解尴尬
  5971. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5972. 亮点3:纤发夺命,情愫暗涌
  5973. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5974. ###人物关系
  5975. 阿雪与梁萧之间存在兄妹之情。
  5976. ###核心矛盾
  5977. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5978. ###主体列表
  5979. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5980. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5981. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5982. 姿态:站立。}{{甜心小美}}
  5983. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5984. 全景,正面拍摄,青年女性,亚洲人。
  5985. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5986. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5987. 姿态:站立。}{{阳光青年}}
  5988. ###美术风格
  5989. 基础画风风格词:厚涂古风
  5990. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5991. ###场景列表
  5992. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5993. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5994. 无人物。}
  5995. ###分集详细内容
  5996. ##第1章 重生
  5997. 我重生了。
  5998. 源于一个男人偏执的暗恋。
  5999. ##第2章 相救
  6000. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6001. 我眼睛扫向站在锅炉后的卞大伟。"
  6002. ];
  6003. // 构建消息
  6004. $messages = [
  6005. $system_message,
  6006. [
  6007. 'role' => 'user',
  6008. 'content' => "以下是文档内容:
  6009. {$content}
  6010. 用户问题:
  6011. {$question}"
  6012. ]
  6013. ];
  6014. }else {
  6015. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6016. // 构建消息
  6017. $messages = [
  6018. $system_message,
  6019. [
  6020. 'role' => 'user',
  6021. 'content' => "以下是文档内容:
  6022. {$content}
  6023. 用户问题:
  6024. {$question}"
  6025. ]
  6026. ];
  6027. }else {
  6028. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6029. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6030. return (array)$value;
  6031. })->toArray();
  6032. array_unshift($messages, $system_message);
  6033. $messages[] = [
  6034. 'role' => 'user',
  6035. 'content' => $prompt
  6036. ];
  6037. }
  6038. }
  6039. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6040. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6041. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6042. if ($model === 'deepseek-chat') {
  6043. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6044. $model = 'deepseek-v4-flash';
  6045. $thinkingMode = 'disabled';
  6046. } elseif ($model === 'deepseek-reasoner') {
  6047. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6048. $model = 'deepseek-v4-flash';
  6049. $thinkingMode = 'enabled';
  6050. }
  6051. $post_data = [
  6052. 'model' => $model,
  6053. 'messages' => $messages,
  6054. // 'max_tokens' => 8192,
  6055. 'temperature' => 0.7,
  6056. 'frequency_penalty' => 0,
  6057. 'presence_penalty' => 0,
  6058. 'response_format' => ['type' => 'text'],
  6059. 'thinking' => ['type' => $thinkingMode],
  6060. 'stream' => true // 启用流式输出
  6061. ];
  6062. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6063. // 根据模型类型选择调用方法
  6064. $fullContent = '';
  6065. $fullReasoningContent = '';
  6066. $usage = [];
  6067. // dd($post_data);
  6068. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6069. try {
  6070. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6071. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6072. } else if (in_array($model, $this->gpt_text_models)) {
  6073. // GPT-5.4 模型使用 TokenRouter API
  6074. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6075. } else if (in_array($model, $this->gemini_text_models)) {
  6076. // Gemini 模型使用 Gemini API
  6077. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6078. } else {
  6079. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6080. }
  6081. // 验证返回值类型
  6082. if (!is_iterable($streamGenerator)) {
  6083. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6084. dLog('deepseek')->error('方法名流式生成器无效', [
  6085. 'generator_type' => $errorType,
  6086. 'model' => $model,
  6087. // 添加其他上下文信息
  6088. ]);
  6089. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6090. 'type' => $errorType,
  6091. 'model' => $model
  6092. ]);
  6093. yield [
  6094. 'type' => 'error',
  6095. // 根据方法返回相应的空数据结构
  6096. 'answer' => '',
  6097. 'reasoning' => '',
  6098. 'usage' => [],
  6099. 'error' => '接口返回数据异常,请重新请求'
  6100. ];
  6101. return;
  6102. }
  6103. // 处理流式输出
  6104. foreach ($streamGenerator as $chunk) {
  6105. if (isset($chunk['type'])) {
  6106. if ($chunk['type'] === 'done') {
  6107. $fullContent = $chunk['full_content'];
  6108. $fullReasoningContent = $chunk['full_reasoning'];
  6109. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6110. } else {
  6111. yield $chunk;
  6112. }
  6113. }
  6114. }
  6115. } catch (\Exception $e) {
  6116. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6117. 'model' => $model,
  6118. 'trace' => $e->getTraceAsString()
  6119. ]);
  6120. logDB('deepseek', 'error', '方法名流式处理失败', [
  6121. 'error' => $e->getMessage(),
  6122. 'model' => $model
  6123. ]);
  6124. yield [
  6125. 'type' => 'error',
  6126. // 根据方法返回相应的空数据结构
  6127. 'answer' => '',
  6128. 'reasoning' => '',
  6129. 'usage' => [],
  6130. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6131. ];
  6132. return;
  6133. }
  6134. dLog('deepseek')->info('完整内容: '.$fullContent);
  6135. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6136. // 处理完整内容并返回最终结果
  6137. $script_arr = [];
  6138. if ($fullContent) {
  6139. $script_arr = handleScriptContent($fullContent);
  6140. dLog('deepseek')->info('解析内容', $script_arr);
  6141. logDB('deepseek', 'info', '解析内容', $script_arr);
  6142. }
  6143. if (empty($script_arr['roles'])) {
  6144. // 未生成剧本相关内容,保存对话记录并返回提示
  6145. dLog('deepseek')->info('未生成剧本相关的内容');
  6146. try {
  6147. $now = date('Y-m-d H:i:s');
  6148. // 保存对话记录
  6149. $records = [
  6150. [
  6151. 'uid' => $uid,
  6152. 'anime_id' => $anime_id,
  6153. 'sequence' => 0,
  6154. 'role' => 'user',
  6155. 'content' => $prompt,
  6156. 'created_at' => $now,
  6157. 'updated_at' => $now
  6158. ],
  6159. [
  6160. 'uid' => $uid,
  6161. 'anime_id' => $anime_id,
  6162. 'sequence' => 0,
  6163. 'role' => 'assistant',
  6164. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6165. 'created_at' => $now,
  6166. 'updated_at' => $now
  6167. ]
  6168. ];
  6169. DB::table('mp_anime_records')->insert($records);
  6170. } catch (\Exception $e) {
  6171. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6172. }
  6173. yield [
  6174. 'type' => 'done',
  6175. 'script' => [],
  6176. 'episode' => [],
  6177. 'answer' => $fullContent,
  6178. 'reasoning' => $fullReasoningContent,
  6179. 'usage' => $usage,
  6180. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6181. ];
  6182. return;
  6183. }
  6184. // 替换美术风格
  6185. if ($mappedArtStyle !== '') {
  6186. $script_arr['art_style'] = $mappedArtStyle;
  6187. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6188. }
  6189. if ($user_anime_name != '新剧本策划') {
  6190. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6191. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6192. // 确认对话名称唯一性
  6193. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6194. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6195. }
  6196. }else {
  6197. $anime_name = $user_anime_name;
  6198. }
  6199. $table_data = [
  6200. 'user_id' => $uid,
  6201. 'model' => $model,
  6202. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6203. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6204. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6205. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6206. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6207. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6208. 'art_style_type' => $input_art_style,
  6209. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6210. 'status' => '解析完成',
  6211. 'generate_status' => '待执行',
  6212. 'updated_at' => date('Y-m-d H:i:s')
  6213. ];
  6214. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6215. // 如果是修改集数,则将content内容更新(会改变原文)
  6216. if (isset($episode_count) && $episode_count > 0) {
  6217. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6218. $table_data['start_episode_sequence'] = 1;
  6219. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6220. }else {
  6221. // 如果需要生成原文内容,从script_arr中提取
  6222. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6223. $table_data['content'] = $script_arr['content'];
  6224. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6225. if (!$table_data['content']) {
  6226. yield [
  6227. 'type' => 'done',
  6228. 'script' => [],
  6229. 'episode' => [],
  6230. 'answer' => $fullContent,
  6231. 'reasoning' => $fullReasoningContent,
  6232. 'usage' => $usage,
  6233. 'error' => '未生成剧本内容,请调整提示词再试'
  6234. ];
  6235. return;
  6236. }
  6237. }
  6238. if (isset($table_data['content']) && $table_data['content']) {
  6239. $chapters = splitContent($table_data['content']);
  6240. $chapter_count = count($chapters);
  6241. if ($chapter_count > 0) {
  6242. $table_data['start_episode_sequence'] = 1;
  6243. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6244. }
  6245. }
  6246. }
  6247. $single_episode = [];
  6248. try {
  6249. DB::beginTransaction();
  6250. $now = date('Y-m-d H:i:s');
  6251. // 更新动漫大纲
  6252. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6253. if (!$boolen) {
  6254. dLog('deepseek')->info('对话修改失败', $table_data);
  6255. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6256. Utils::throwError('20003:对话修改失败');
  6257. }
  6258. // 保存对话记录
  6259. $records = [
  6260. [
  6261. 'uid' => $uid,
  6262. 'anime_id' => $anime_id,
  6263. 'sequence' => 0,
  6264. 'role' => 'user',
  6265. 'content' => $prompt,
  6266. 'created_at' => $now,
  6267. 'updated_at' => $now
  6268. ],
  6269. [
  6270. 'uid' => $uid,
  6271. 'anime_id' => $anime_id,
  6272. 'sequence' => 0,
  6273. 'role' => 'assistant',
  6274. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6275. 'content' => $fullContent,
  6276. 'created_at' => $now,
  6277. 'updated_at' => $now
  6278. ]
  6279. ];
  6280. // 保存对话记录
  6281. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6282. if (!$boolen3) {
  6283. Utils::throwError('20003:对话记录保存失败');
  6284. }
  6285. // 单剧集模式:生成并保存剧集信息
  6286. if ($is_single) {
  6287. $anime_name = getProp($anime, 'anime_name', '未命名');
  6288. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6289. if (empty($episode_arr['acts'])) {
  6290. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6291. }
  6292. $saveResult = $this->saveEpisodeVersionData(
  6293. $anime_id,
  6294. 1,
  6295. $episode_arr,
  6296. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6297. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6298. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6299. null,
  6300. null,
  6301. false,
  6302. $content,
  6303. $now
  6304. );
  6305. $single_episode = $saveResult['episode'];
  6306. $episode_id = $saveResult['episode_id'];
  6307. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6308. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6309. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6310. 'props' => json_encode($saveResult['merged_props'], 256),
  6311. 'updated_at' => $now
  6312. ]);
  6313. if ($boolen5 === false) {
  6314. Utils::throwError('20003:单剧集主表资源同步失败');
  6315. }
  6316. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6317. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6318. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6319. $episode_record_content = '确认分镜大纲';
  6320. if ($content !== '') {
  6321. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6322. }
  6323. $episode_records = [
  6324. [
  6325. 'uid' => $uid,
  6326. 'anime_id' => $anime_id,
  6327. 'role' => 'user',
  6328. 'content' => $episode_record_content,
  6329. 'sequence' => 1,
  6330. 'episode_id' => $episode_id,
  6331. 'created_at' => $now,
  6332. 'updated_at' => $now
  6333. ],
  6334. [
  6335. 'uid' => $uid,
  6336. 'anime_id' => $anime_id,
  6337. 'role' => 'assistant',
  6338. 'content' => $fullContent,
  6339. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6340. 'sequence' => 1,
  6341. 'episode_id' => $episode_id,
  6342. 'created_at' => $now,
  6343. 'updated_at' => $now
  6344. ]
  6345. ];
  6346. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6347. if (!$boolen4) {
  6348. Utils::throwError('20003:单剧集分镜记录保存失败');
  6349. }
  6350. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6351. if ($is_single && !empty($single_episode)) {
  6352. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6353. 'anime_id' => $anime_id,
  6354. 'episode_id' => $episode_id ?? 0,
  6355. 'model' => $model,
  6356. 'source' => 'reGenerateAnime',
  6357. ]);
  6358. }
  6359. }
  6360. }catch (\Exception $e) {
  6361. DB::rollBack();
  6362. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  6363. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  6364. yield [
  6365. 'type' => 'done',
  6366. 'answer' => $fullContent,
  6367. 'reasoning' => $fullReasoningContent,
  6368. 'usage' => $usage,
  6369. 'error' => $e->getMessage(),
  6370. ];
  6371. return;
  6372. }
  6373. DB::commit();
  6374. dLog('deepseek')->info('保存完毕');
  6375. if ($is_single && !empty($single_episode)) {
  6376. // $this->batchSetGlobalRoleImg([
  6377. // 'anime_id' => $anime_id,
  6378. // ]);
  6379. // $this->batchSetGlobalSceneImg([
  6380. // 'anime_id' => $anime_id,
  6381. // ]);
  6382. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6383. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6384. }
  6385. $table_data['anime_id'] = $anime_id;
  6386. $table_data['roles'] = json_decode($table_data['roles'], true);
  6387. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6388. unset($table_data['updated_at']);
  6389. unset($table_data['status']);
  6390. yield [
  6391. 'type' => 'done',
  6392. 'script' => $table_data,
  6393. 'episode' => $single_episode,
  6394. 'answer' => $fullContent,
  6395. 'reasoning' => $fullReasoningContent,
  6396. 'usage' => $usage
  6397. ];
  6398. }
  6399. public function chat($data) {
  6400. $uid = Site::getUid();
  6401. // 积分余额预检(不足直接报错)
  6402. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  6403. $anime_id = getProp($data, 'anime_id');
  6404. $file = getProp($data, 'file');
  6405. $content = getProp($data, 'content', '');
  6406. $bid = getProp($data, 'bid', 0);
  6407. $script_id = getProp($data, 'script_id', 0);
  6408. $episode_number = getProp($data, 'episode_number', 1);
  6409. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6410. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6411. if (!$anime) Utils::throwError('20003:该对话不存在!');
  6412. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  6413. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  6414. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  6415. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  6416. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  6417. $roles = is_array($roles) ? $roles : [];
  6418. $scenes = is_array($scenes) ? $scenes : [];
  6419. // 获取最后一集序号
  6420. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  6421. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  6422. // 转换主体列表和场景列表的格式
  6423. // 获取参考主体或场景
  6424. if ((int)$episode_number === 1) {
  6425. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  6426. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  6427. }else {
  6428. $prev_episode_number = $episode_number - 1;
  6429. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  6430. }
  6431. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  6432. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  6433. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  6434. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  6435. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  6436. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  6437. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  6438. 中年女:邻居阿姨
  6439. 老年男:幽默大爷
  6440. 老年女:婆婆
  6441. 萌娃:奶气萌娃";
  6442. if ($roles_content) {
  6443. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  6444. 主体范围:\n {$roles_content}\n
  6445. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  6446. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6447. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6448. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6449. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6450. }else {
  6451. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6452. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6453. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6454. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6455. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6456. }
  6457. if ($scenes_content) {
  6458. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  6459. 场景范围:\n {$scenes_content}\n
  6460. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  6461. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6462. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6463. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  6464. }else {
  6465. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6466. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6467. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6468. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  6469. }
  6470. // 提取文件内容
  6471. if ($file) {
  6472. $uploaded_content = $this->extractFileContent($file);
  6473. if (!$uploaded_content) {
  6474. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6475. }
  6476. } elseif ($script_id) {
  6477. $uploaded_content = $this->getContentByScriptId($script_id);
  6478. if (!$uploaded_content) {
  6479. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6480. }
  6481. } elseif ($bid) {
  6482. $uploaded_content = $this->getContentByBid($bid);
  6483. if (!$uploaded_content) {
  6484. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6485. }
  6486. } elseif ($content) {
  6487. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  6488. }
  6489. // elseif ($prompt) {
  6490. // $uploaded_content = filterContent($prompt);
  6491. // }
  6492. else {
  6493. $uploaded_content = '';
  6494. }
  6495. $input_art_style = getProp($anime, 'art_style');
  6496. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6497. // 美术风格
  6498. if (!$mappedArtStyle) {
  6499. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6500. }else {
  6501. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6502. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6503. }else {
  6504. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6505. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6506. }
  6507. }
  6508. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6509. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6510. // 强制要求:
  6511. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6512. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6513. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6514. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  6515. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  6516. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  6517. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  6518. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  6519. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  6520. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  6521. // - 分镜要和场景列表、人物主体保持一致\n
  6522. // 普通要求:
  6523. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6524. // {$role_demo}
  6525. // {$scene_demo}
  6526. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6527. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6528. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6529. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  6530. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6531. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6532. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6533. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6534. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6535. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6536. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6537. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6538. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6539. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6540. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6541. // 5.$mappedArtStyle_prompt\n\n
  6542. // 示例格式:\n
  6543. // 第1集:隐形的守护者
  6544. // ###故事梗概
  6545. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6546. // ###美术风格
  6547. // 基础画风风格词:韩漫二次元
  6548. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6549. // ###主体列表
  6550. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6551. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6552. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6553. // ###场景列表
  6554. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6555. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6556. // 无人物。}
  6557. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6558. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6559. // 无人物。}
  6560. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6561. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6562. // 无人物。}
  6563. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6564. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6565. // 无人物。}
  6566. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6567. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6568. // 无人物。}
  6569. // ###分镜剧本
  6570. // ##第1幕:徐家老旧厨房 白天 室内
  6571. // 分镜1
  6572. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6573. // 场景:徐家老旧厨房
  6574. // 构图设计:全景,低角度仰视
  6575. // 运镜调度:手持拍摄
  6576. // 配音角色:旁白
  6577. // 出镜角色:许芸-校服装、徐母
  6578. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6579. // 画面类型:普通画面
  6580. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6581. // 分镜2
  6582. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6583. // 场景:徐家老旧厨房
  6584. // 构图设计:近景,徐母面部特写
  6585. // 运镜调度:固定镜头
  6586. // 配音角色:徐母
  6587. // 出镜角色:徐母
  6588. // 台词内容:问我夜不归宿死哪儿去了。
  6589. // 画面类型:对口型
  6590. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6591. // ##第2幕:徐家简陋客厅 黄昏 室内
  6592. // 分镜3
  6593. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6594. // 场景:徐家简陋客厅
  6595. // 构图设计:全景,景深虚化
  6596. // 运镜调度:固定镜头
  6597. // 配音角色:旁白
  6598. // 出镜角色:无
  6599. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6600. // 画面类型:普通画面
  6601. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6602. // 分镜4
  6603. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6604. // 场景:徐家简陋客厅
  6605. // 构图设计:特写,火车票
  6606. // 运镜调度:固定镜头
  6607. // 配音角色:旁白
  6608. // 出镜角色:无
  6609. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6610. // 画面类型:普通画面
  6611. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6612. // \n\n";
  6613. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  6614. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  6615. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  6616. 普通要求:
  6617. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6618. {$role_demo}
  6619. {$scene_demo}
  6620. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6621. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6622. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6623. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6624. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6625. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6626. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6627. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6628. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6629. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6630. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6631. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6632. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6633. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6634. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6635. 5.$mappedArtStyle_prompt
  6636. 6.《情绪-视听语言映射表》:
  6637. 6.1 场景空间与时间心理学 (Scene & Temporality)
  6638. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6639. -----|---------|------------|----------------
  6640. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  6641. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  6642. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  6643. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  6644. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  6645. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6646. -----|---------|------------|----------------
  6647. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  6648. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  6649. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  6650. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  6651. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  6652. --------|---------|--------------|-------------
  6653. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  6654. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  6655. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  6656. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  6657. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  6658. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  6659. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  6660. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  6661. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  6662. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  6663. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  6664. -----|---------|------------|------------
  6665. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  6666. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  6667. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  6668. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  6669. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  6670. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  6671. --------|---------|--------------|----------
  6672. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  6673. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  6674. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  6675. 6.6 声音设计与潜意识影响 (Soundscape)
  6676. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  6677. -----|---------|------------|------------------
  6678. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  6679. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  6680. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  6681. 理论基石:
  6682. - The Five C's of Cinematography by Joseph V. Mascelli
  6683. - Film Art: An Introduction by David Bordwell
  6684. - Sight, Sound, Motion by Herbert Zettl
  6685. - Notes on the Cinematograph by Robert Bresson
  6686. \n\n
  6687. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  6688. 示例格式:\n
  6689. 第1集:隐形的守护者
  6690. ###故事梗概
  6691. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6692. ###美术风格
  6693. 基础画风风格词:韩漫二次元
  6694. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6695. ###主体列表
  6696. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6697. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6698. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6699. ###场景列表
  6700. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6701. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6702. 无人物。}
  6703. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6704. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6705. 无人物。}
  6706. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6707. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6708. 无人物。}
  6709. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6710. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6711. 无人物。}
  6712. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6713. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6714. 无人物。}
  6715. ###分镜剧本
  6716. ##第1幕:徐家老旧厨房 白天 室内
  6717. 分镜1
  6718. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6719. 场景:徐家老旧厨房
  6720. 构图设计:全景,低角度仰视
  6721. 运镜调度:手持拍摄
  6722. 配音角色:旁白
  6723. 出镜角色:许芸-校服装、徐母
  6724. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6725. 画面类型:普通画面
  6726. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6727. 分镜2
  6728. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6729. 场景:徐家老旧厨房
  6730. 构图设计:近景,徐母面部特写
  6731. 运镜调度:固定镜头
  6732. 配音角色:徐母
  6733. 出镜角色:徐母
  6734. 台词内容:问我夜不归宿死哪儿去了。
  6735. 画面类型:对口型
  6736. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6737. ##第2幕:徐家简陋客厅 黄昏 室内
  6738. 分镜3
  6739. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6740. 场景:徐家简陋客厅
  6741. 构图设计:全景,景深虚化
  6742. 运镜调度:固定镜头
  6743. 配音角色:旁白
  6744. 出镜角色:无
  6745. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6746. 画面类型:普通画面
  6747. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6748. 分镜4
  6749. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6750. 场景:徐家简陋客厅
  6751. 构图设计:特写,火车票
  6752. 运镜调度:固定镜头
  6753. 配音角色:旁白
  6754. 出镜角色:无
  6755. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6756. 画面类型:普通画面
  6757. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6758. \n\n";
  6759. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6760. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  6761. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  6762. $prompt = $origin_prompt;
  6763. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  6764. // 获取章节内容
  6765. $full_content = getProp($anime, 'content');
  6766. if ($uploaded_content) {
  6767. $full_content = $uploaded_content;
  6768. }
  6769. // 根据章节内容拆分章节
  6770. $chapters = splitContent($full_content);
  6771. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  6772. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  6773. $messages = [];
  6774. if ($prompt == '确认分镜大纲') {
  6775. // 暂时保留
  6776. $content = $chapter_content;
  6777. if ($is_single) $content = $full_content; // 单剧集使用全文
  6778. if (!$content) {
  6779. Utils::throwError('20003:章节内容无法获取,请确认');
  6780. }
  6781. $question = $is_single
  6782. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  6783. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  6784. // 构建消息
  6785. $messages[] =
  6786. [
  6787. 'role' => 'user',
  6788. 'content' => $question
  6789. ];
  6790. }else if ($prompt == '继续策划下一集') {
  6791. if ($is_single) {
  6792. Utils::throwError('20003:单剧集不支持继续策划下一集');
  6793. }
  6794. $content = $chapter_content;
  6795. if (!$content) {
  6796. Utils::throwError('20003:章节内容无法获取,请确认');
  6797. }
  6798. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  6799. // 获取上一集最后记录
  6800. $prev_sequence = $episode_number - 1;
  6801. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  6802. // 构建消息
  6803. $messages[] =
  6804. [
  6805. 'role' => 'user',
  6806. 'content' => $question
  6807. ];
  6808. }else {
  6809. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  6810. if (!$content) {
  6811. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  6812. }
  6813. if (!$content) {
  6814. Utils::throwError('20003:章节内容无法获取,请确认');
  6815. }
  6816. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  6817. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  6818. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  6819. if ($origin_prompt) {
  6820. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  6821. }
  6822. $messages[] =
  6823. [
  6824. 'role' => 'user',
  6825. 'content' => $question
  6826. ];
  6827. }
  6828. // 处理文本模型
  6829. $model = getProp($data, 'model');
  6830. if (!$model) {
  6831. // 用户没有输入,从anime表获取
  6832. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6833. $model = getProp($anime, 'model');
  6834. if (!$model) {
  6835. // anime表也没有,使用默认值
  6836. $model = 'doubao-seed-2-0-mini-260215';
  6837. }
  6838. }
  6839. // 验证模型是否在可用模型表中
  6840. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6841. $model = 'doubao-seed-2-0-mini-260215';
  6842. }
  6843. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6844. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6845. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6846. if ($model === 'deepseek-chat') {
  6847. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6848. $model = 'deepseek-v4-flash';
  6849. $thinkingMode = 'disabled';
  6850. } elseif ($model === 'deepseek-reasoner') {
  6851. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6852. $model = 'deepseek-v4-flash';
  6853. $thinkingMode = 'enabled';
  6854. }
  6855. $post_data = [
  6856. 'model' => $model,
  6857. 'messages' => $messages,
  6858. // 'max_tokens' => 8192,
  6859. 'temperature' => 0.2,
  6860. 'frequency_penalty' => 0,
  6861. 'presence_penalty' => 0,
  6862. 'response_format' => ['type' => 'text'],
  6863. 'thinking' => ['type' => $thinkingMode],
  6864. 'stream' => true // 启用流式输出
  6865. ];
  6866. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6867. // 根据模型类型选择调用方法
  6868. $fullContent = '';
  6869. $fullReasoningContent = '';
  6870. $usage = [];
  6871. try {
  6872. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6873. // DeepSeek 官方模型使用 DeepSeek API
  6874. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6875. } else if (in_array($model, $this->gpt_text_models)) {
  6876. // GPT-5.4 模型使用 TokenRouter API
  6877. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6878. } else if (in_array($model, $this->gemini_text_models)) {
  6879. // Gemini 模型使用 Gemini API
  6880. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6881. } else {
  6882. // 其他模型使用火山引擎API
  6883. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6884. }
  6885. // 验证返回值类型
  6886. if (!is_iterable($streamGenerator)) {
  6887. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6888. dLog('deepseek')->error('chat流式生成器无效', [
  6889. 'generator_type' => $errorType,
  6890. 'model' => $model,
  6891. 'anime_id' => $anime_id,
  6892. 'episode_number' => $episode_number
  6893. ]);
  6894. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  6895. 'type' => $errorType,
  6896. 'model' => $model
  6897. ]);
  6898. yield [
  6899. 'type' => 'error',
  6900. 'episode' => [],
  6901. 'answer' => '',
  6902. 'reasoning' => '',
  6903. 'usage' => [],
  6904. 'error' => '接口返回数据异常,请重新请求'
  6905. ];
  6906. return;
  6907. }
  6908. // 处理流式输出
  6909. foreach ($streamGenerator as $chunk) {
  6910. if (isset($chunk['type'])) {
  6911. if ($chunk['type'] === 'done') {
  6912. // 最终结果
  6913. $fullContent = $chunk['full_content'];
  6914. $fullReasoningContent = $chunk['full_reasoning'];
  6915. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6916. } else {
  6917. // 逐块yield数据
  6918. yield $chunk;
  6919. }
  6920. }
  6921. }
  6922. } catch (\Exception $e) {
  6923. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  6924. 'model' => $model,
  6925. 'anime_id' => $anime_id,
  6926. 'episode_number' => $episode_number,
  6927. 'trace' => $e->getTraceAsString()
  6928. ]);
  6929. logDB('deepseek', 'error', 'chat流式处理失败', [
  6930. 'error' => $e->getMessage(),
  6931. 'model' => $model
  6932. ]);
  6933. yield [
  6934. 'type' => 'error',
  6935. 'episode' => [],
  6936. 'answer' => '',
  6937. 'reasoning' => '',
  6938. 'usage' => [],
  6939. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6940. ];
  6941. return;
  6942. }
  6943. dLog('deepseek')->info('完整内容: '.$fullContent);
  6944. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6945. // 处理完整内容并返回最终结果
  6946. $episode_arr = handleEpisodeContent($fullContent);
  6947. logDB('deepseek', 'info', '解析内容', $episode_arr);
  6948. if (empty($episode_arr['acts'])) {
  6949. // 未生成剧本相关内容,保存对话记录并返回提示
  6950. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  6951. try {
  6952. $now = date('Y-m-d H:i:s');
  6953. // 保存对话记录
  6954. $records = [
  6955. [
  6956. 'uid' => $uid,
  6957. 'anime_id' => $anime_id,
  6958. 'sequence' => $episode_number,
  6959. 'role' => 'user',
  6960. 'content' => $prompt,
  6961. 'created_at' => $now,
  6962. 'updated_at' => $now
  6963. ],
  6964. [
  6965. 'uid' => $uid,
  6966. 'anime_id' => $anime_id,
  6967. 'sequence' => $episode_number,
  6968. 'role' => 'assistant',
  6969. 'content' => $fullContent,
  6970. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6971. 'created_at' => $now,
  6972. 'updated_at' => $now
  6973. ]
  6974. ];
  6975. DB::table('mp_anime_records')->insert($records);
  6976. } catch (\Exception $e) {
  6977. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6978. }
  6979. yield [
  6980. 'type' => 'done',
  6981. 'episode' => [],
  6982. 'answer' => $fullContent,
  6983. 'reasoning' => $fullReasoningContent,
  6984. 'usage' => $usage,
  6985. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  6986. ];
  6987. return;
  6988. }
  6989. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  6990. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  6991. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  6992. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  6993. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  6994. $existing_props = is_array($existing_props) ? $existing_props : [];
  6995. $now = date('Y-m-d H:i:s');
  6996. try {
  6997. DB::beginTransaction();
  6998. $saveResult = $this->saveEpisodeVersionData(
  6999. $anime_id,
  7000. $episode_number,
  7001. $episode_arr,
  7002. $existing_roles,
  7003. $existing_scenes,
  7004. $existing_props,
  7005. $current_episode,
  7006. $base_episode,
  7007. $is_regenerate_version,
  7008. $content,
  7009. $now
  7010. );
  7011. $episode = $saveResult['episode'];
  7012. $episode_id = $saveResult['episode_id'];
  7013. $merged_roles = $saveResult['merged_roles'];
  7014. $merged_scenes = $saveResult['merged_scenes'];
  7015. $merged_props = $saveResult['merged_props'];
  7016. $record_content = $origin_prompt;
  7017. if ($uploaded_content !== '') {
  7018. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  7019. }
  7020. $records = [
  7021. [
  7022. 'uid' => $uid,
  7023. 'anime_id' => $anime_id,
  7024. 'role' => 'user',
  7025. 'content' => $record_content,
  7026. 'sequence' => $episode_number,
  7027. 'episode_id' => $episode_id,
  7028. 'created_at' => $now,
  7029. 'updated_at' => $now
  7030. ],
  7031. [
  7032. 'uid' => $uid,
  7033. 'anime_id' => $anime_id,
  7034. 'role' => 'assistant',
  7035. 'content' => $fullContent,
  7036. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7037. 'sequence' => $episode_number,
  7038. 'episode_id' => $episode_id,
  7039. 'created_at' => $now,
  7040. 'updated_at' => $now
  7041. ]
  7042. ];
  7043. $boolen4 = DB::table('mp_anime_records')->insert($records);
  7044. if (!$boolen4) {
  7045. Utils::throwError('20003:对话记录保存失败');
  7046. }
  7047. // 保存模型和内容到anime表
  7048. $update_anime_data = [
  7049. 'model' => $model,
  7050. 'updated_at' => $now
  7051. ];
  7052. if ($uploaded_content) {
  7053. $update_anime_data['content'] = $uploaded_content;
  7054. }
  7055. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  7056. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7057. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7058. 'anime_id' => $anime_id,
  7059. 'episode_number' => $episode_number,
  7060. 'model' => $model,
  7061. 'source' => 'chat',
  7062. ]);
  7063. }catch (\Exception $e) {
  7064. DB::rollBack();
  7065. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7066. yield [
  7067. 'type' => 'done',
  7068. 'answer' => $fullContent,
  7069. 'reasoning' => $fullReasoningContent,
  7070. 'usage' => $usage,
  7071. 'error' => $e->getMessage(),
  7072. ];
  7073. return;
  7074. }
  7075. DB::commit();
  7076. if ($is_global_generate_pics) {
  7077. // // 批量生成全局角色图片
  7078. // $this->batchSetGlobalRoleImg([
  7079. // 'anime_id' => $anime_id,
  7080. // ], true);
  7081. // // 批量生成全局场景图片
  7082. // $this->batchSetGlobalSceneImg([
  7083. // 'anime_id' => $anime_id,
  7084. // ], true);
  7085. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7086. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7087. }
  7088. $episode['episode_id'] = $episode_id;
  7089. $episode['roles'] = $merged_roles;
  7090. $episode['scenes'] = $merged_scenes;
  7091. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  7092. yield [
  7093. 'type' => 'done',
  7094. 'episode' => $episode,
  7095. 'answer' => $fullContent,
  7096. 'reasoning' => $fullReasoningContent,
  7097. 'usage' => $usage
  7098. ];
  7099. }
  7100. public function addChatForAce($data) {
  7101. $uid = Site::getUid();
  7102. $anime_id = getProp($data, 'anime_id');
  7103. if (!$anime_id) Utils::throwError('20003:请选择对话');
  7104. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  7105. if (!$anime) Utils::throwError('20003:对话不存在');
  7106. $file = getProp($data, 'file');
  7107. $content = getProp($data, 'content', '');
  7108. $bid = getProp($data, 'bid', 0);
  7109. $script_id = getProp($data, 'script_id', 0);
  7110. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  7111. $prompt = getProp($data, 'prompt');
  7112. $is_multi = getProp($anime, 'is_multi');
  7113. $is_single = (int)$is_multi !== 1;
  7114. // 积分余额预检(仅单剧集模式收费)
  7115. if ($is_single) {
  7116. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  7117. }
  7118. $extra_products = getProp($data, 'products', []);
  7119. if (!$extra_products) {
  7120. $extra_products = getProp($anime, 'extra_products');
  7121. if ($extra_products) {
  7122. $extra_products = json_decode($extra_products, true);
  7123. }else {
  7124. $extra_products = [];
  7125. }
  7126. }else {
  7127. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7128. }
  7129. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7130. $anime_script_id = getProp($anime, 'script_id');
  7131. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  7132. $cpid = Site::getCpid();
  7133. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7134. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7135. ->where('mapping.script_id', $anime_script_id)
  7136. ->where('product.cpid', $cpid)
  7137. ->where('product.is_deleted', 0);
  7138. $mappings = $script_products_mappings->select(
  7139. 'mapping.product_id',
  7140. 'mapping.episode_number',
  7141. 'product.product_name',
  7142. 'product.type',
  7143. 'product.product',
  7144. 'product.pic_prompt',
  7145. 'product.url',
  7146. 'product.pic_task_id',
  7147. 'product.pic_task_status',
  7148. 'product.three_view_image_url'
  7149. )
  7150. ->get();
  7151. // 按 product_id 分组,合并 episode_number
  7152. $productMap = [];
  7153. foreach ($mappings as $item) {
  7154. $product_id = $item->product_id;
  7155. $product_name = $item->product_name;
  7156. // 处理product_name两边的符号
  7157. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7158. if (!isset($productMap[$product_id])) {
  7159. $productMap[$product_id] = [
  7160. 'product_id' => $product_id,
  7161. 'product_name' => $product_name,
  7162. 'type' => (int)$item->type,
  7163. 'product' => (int)$item->product,
  7164. 'pic_prompt' => $item->pic_prompt,
  7165. 'url' => $item->url,
  7166. 'pic_task_id' => $item->pic_task_id,
  7167. 'pic_task_status' => $item->pic_task_status,
  7168. 'episode_numbers' => [],
  7169. ];
  7170. }
  7171. // 添加 episode_number(去重)
  7172. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7173. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7174. }
  7175. }
  7176. // 将查询到的剧本资产合并到extra_products中
  7177. // 先构建extra_products的索引(以product_id为key,用于去重)
  7178. $extraProductsMap = [];
  7179. foreach ($extra_products as $item) {
  7180. $key = getProp($item, 'product_id');
  7181. if ($key) {
  7182. $extraProductsMap[$key] = $item;
  7183. }
  7184. }
  7185. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7186. foreach ($productMap as $product) {
  7187. $product_id = $product['product_id'];
  7188. // 如果不存在则添加(不带episode_number信息)
  7189. if (!isset($extraProductsMap[$product_id])) {
  7190. $extraProductsMap[$product_id] = [
  7191. 'product_id' => $product['product_id'],
  7192. 'product_name' => $product['product_name'],
  7193. 'type' => $product['type'],
  7194. 'product' => $product['product'],
  7195. 'pic_prompt' => $product['pic_prompt'],
  7196. 'url' => $product['url'],
  7197. 'pic_task_id' => $product['pic_task_id'],
  7198. 'pic_task_status' => $product['pic_task_status'],
  7199. ];
  7200. }
  7201. }
  7202. // 重新赋值给extra_products
  7203. $extra_products = array_values($extraProductsMap);
  7204. }
  7205. $user_anime_name = getProp($anime, 'anime_name');
  7206. // 处理提示词
  7207. if ($prompt && $extra_products) {
  7208. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7209. foreach($extra_products as $item) {
  7210. $product_name = getProp($item, 'product_name');
  7211. if ($product_name) {
  7212. // 替换 {product_name} 为 product_name
  7213. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7214. }
  7215. }
  7216. }
  7217. // 处理文本模型
  7218. $model = getProp($data, 'model');
  7219. if (!$model) {
  7220. // 用户没有输入,从anime表获取
  7221. $model = getProp($anime, 'model');
  7222. if (!$model) {
  7223. // anime表也没有,使用默认值
  7224. $model = 'deepseek-v4-pro';
  7225. }
  7226. }
  7227. // 验证模型是否在可用模型表中
  7228. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7229. $model = 'deepseek-v4-pro';
  7230. }
  7231. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7232. if ($prompt) {
  7233. $question .= "本次修改要求如下:\n{$prompt}";
  7234. }
  7235. // if (!$file && !$content && !$bid) {
  7236. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  7237. // }
  7238. // 提取文件内容
  7239. if ($file) {
  7240. $content = $this->extractFileContent($file);
  7241. if (!$content) {
  7242. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7243. }
  7244. } elseif ($script_id) {
  7245. $content = $this->getContentByScriptId($script_id);
  7246. if (!$content) {
  7247. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7248. }
  7249. } elseif ($bid) {
  7250. $content = $this->getContentByBid($bid);
  7251. if (!$content) {
  7252. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7253. }
  7254. } elseif ($content) {
  7255. $content = filterContent($content);
  7256. } else {
  7257. $content = getProp($anime, 'content');
  7258. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7259. $need_generate_content = true;
  7260. }
  7261. }
  7262. // 美术风格
  7263. $input_art_style = getProp($data, 'art_style');
  7264. if (!$input_art_style) {
  7265. $mappedArtStyle = getProp($anime, 'art_style');
  7266. }else {
  7267. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7268. }
  7269. // 判断是否需要生成原文内容
  7270. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7271. // 如果需要生成原文内容,添加额外的要求
  7272. $content_generation_requirement = $need_generate_content
  7273. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7274. : "";
  7275. // 美术风格
  7276. if (!$mappedArtStyle) {
  7277. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7278. }else {
  7279. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7280. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7281. }else {
  7282. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7283. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7284. }
  7285. }
  7286. // 构建主体、场景和道具提示词
  7287. $extra_role_prompt = "\n";
  7288. $extra_scene_prompt = "\n";
  7289. $extra_prop_prompt = "\n";
  7290. $ref_products = []; // 参考资产
  7291. if ($extra_products) {
  7292. foreach($extra_products as $item) {
  7293. $product = getProp($item, 'product');
  7294. $product_name = getProp($item, 'product_name');
  7295. if ($product_name == '旁白') continue;
  7296. $ref_products[$product_name] = $item;
  7297. $pic_prompt = getProp($item, 'pic_prompt');
  7298. if ((int)$product === 1) {
  7299. // 拼接角色信息
  7300. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7301. } elseif ((int)$product === 2) {
  7302. // 拼接场景信息
  7303. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7304. } elseif ((int)$product === 3) {
  7305. // 拼接道具信息
  7306. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7307. }
  7308. }
  7309. // 优化提示词,融入剧本
  7310. if (!empty(trim($extra_role_prompt))) {
  7311. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7312. }
  7313. if (!empty(trim($extra_scene_prompt))) {
  7314. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7315. }
  7316. if (!empty(trim($extra_prop_prompt))) {
  7317. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7318. }
  7319. }
  7320. if ($anime_script_id && $is_single) {
  7321. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7322. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7323. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7324. }else {
  7325. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7326. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7327. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7328. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7329. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7330. {$extra_role_prompt}";
  7331. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7332. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7333. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7334. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7335. {$extra_scene_prompt}";
  7336. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7337. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7338. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7339. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7340. {$extra_prop_prompt}";
  7341. }
  7342. $systemPrompt = $is_single
  7343. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7344. 强制要求:
  7345. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7346. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7347. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7348. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7349. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7350. 普通要求:
  7351. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7352. $role_demo
  7353. $scene_demo
  7354. $prop_demo
  7355. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7356. 5.1片段分割逻辑(优先级从高到低):
  7357. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7358. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7359. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7360. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7361. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7362. - 片段数量格式为: 片段数量:8
  7363. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7364. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7365. 5.3分镜结构:每个分镜包含以下字段:
  7366. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7367. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7368. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7369. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7370. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7371. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7372. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7373. - 运镜:场景+画面描述+运镜
  7374. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7375. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7376. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7377. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7378. 6.{$mappedArtStyle_prompt}\n\n
  7379. 示例如下:\n
  7380. ###剧本名:西昆仑
  7381. ###故事梗概
  7382. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7383. ###剧本亮点
  7384. 亮点1:绝境奇药,生死一线
  7385. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7386. 亮点2:结拜兄妹,化解尴尬
  7387. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7388. 亮点3:纤发夺命,情愫暗涌
  7389. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7390. ###人物关系
  7391. 阿雪与梁萧之间存在兄妹之情。
  7392. ###核心矛盾
  7393. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7394. ###主体列表
  7395. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7396. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7397. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7398. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7399. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7400. 全景,正面拍摄,青年女性,亚洲人。
  7401. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7402. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7403. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7404. ###美术风格
  7405. 基础画风风格词:厚涂古风
  7406. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7407. ###场景列表
  7408. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7409. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7410. 无人物。}
  7411. ###分段剧本
  7412. 片段数量:8
  7413. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7414. ##片段1
  7415. 时长:12s
  7416. 分镜1
  7417. 出场角色:刀疤脸
  7418. 场景:边境小镇街道
  7419. 出场道具:酒杯-高脚杯
  7420. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7421. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7422. 配音台词:
  7423. 背景音效:
  7424. 分镜2
  7425. 出场角色:刀疤脸
  7426. 场景:悦来酒馆
  7427. 出场道具:酒杯-高脚杯
  7428. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7429. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7430. 配音台词:
  7431. 背景音效:
  7432. 分镜3
  7433. 出场角色:刀疤脸
  7434. 场景:悦来酒馆
  7435. 出场道具:酒杯-高脚杯
  7436. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7437. 运镜:从中景推向令牌特写。
  7438. 配音台词:
  7439. 背景音效:
  7440. 分镜4
  7441. 出场角色:刀疤脸
  7442. 场景:悦来酒馆
  7443. 出场道具:酒杯-高脚杯
  7444. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7445. 运镜:极速推向酒水溅起的瞬间。
  7446. 配音台词:
  7447. 背景音效:
  7448. 分镜5
  7449. 出场角色:刀疤脸
  7450. 场景:悦来酒馆
  7451. 出场道具:酒杯-高脚杯
  7452. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7453. 运镜:固定机位,利用倾斜构图制造压迫感。
  7454. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7455. 背景音效:
  7456. \n\n"
  7457. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7458. 强制要求:\n
  7459. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7460. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7461. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7462. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7463. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7464. 普通要求:\n
  7465. 1.剧本名(必须生成)必须与文档内容高度相关
  7466. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7467. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7468. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7469. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7470. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7471. {$extra_role_prompt}
  7472. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7473. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7474. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7475. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7476. {$extra_scene_prompt}
  7477. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7478. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7479. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7480. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7481. {$extra_prop_prompt}
  7482. 5.{$mappedArtStyle_prompt}\n\n
  7483. 示例如下:\n
  7484. ###剧本名:西昆仑
  7485. ###故事梗概
  7486. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7487. ###剧本亮点
  7488. 亮点1:绝境奇药,生死一线
  7489. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7490. 亮点2:结拜兄妹,化解尴尬
  7491. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7492. 亮点3:纤发夺命,情愫暗涌
  7493. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7494. ###人物关系
  7495. 阿雪与梁萧之间存在兄妹之情。
  7496. ###核心矛盾
  7497. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7498. ###主体列表
  7499. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7500. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7501. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7502. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7503. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7504. 全景,正面拍摄,青年女性,亚洲人。
  7505. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7506. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7507. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7508. ###美术风格
  7509. 基础画风风格词:厚涂古风
  7510. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7511. ###场景列表
  7512. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7513. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7514. 无人物。}
  7515. ###道具列表
  7516. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  7517. // 构建消息
  7518. $messages = [
  7519. [
  7520. 'role' => 'system',
  7521. 'content' => $systemPrompt
  7522. ],
  7523. [
  7524. 'role' => 'user',
  7525. 'content' => "以下是文档内容:
  7526. {$content}
  7527. 用户问题:
  7528. {$question}"
  7529. ]
  7530. ];
  7531. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7532. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7533. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7534. if ($model === 'deepseek-chat') {
  7535. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7536. $model = 'deepseek-v4-flash';
  7537. $thinkingMode = 'disabled';
  7538. } elseif ($model === 'deepseek-reasoner') {
  7539. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7540. $model = 'deepseek-v4-flash';
  7541. $thinkingMode = 'enabled';
  7542. }
  7543. $post_data = [
  7544. 'model' => $model,
  7545. 'messages' => $messages,
  7546. // 'max_tokens' => 8192,
  7547. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7548. 'frequency_penalty' => 0,
  7549. 'presence_penalty' => 0,
  7550. 'response_format' => ['type' => 'text'],
  7551. 'thinking' => ['type'=>$thinkingMode],
  7552. 'stream' => true // 启用流式输出
  7553. ];
  7554. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7555. // 根据模型类型选择调用方法
  7556. $fullContent = '';
  7557. $fullReasoningContent = '';
  7558. $usage = [];
  7559. try {
  7560. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7561. // DeepSeek 官方模型使用 DeepSeek API
  7562. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7563. } else if (in_array($model, $this->gpt_text_models)) {
  7564. // GPT-5.4 模型使用 TokenRouter API
  7565. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7566. } else if (in_array($model, $this->gemini_text_models)) {
  7567. // Gemini 模型使用 Gemini API
  7568. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  7569. } else {
  7570. // 其他模型使用火山引擎API
  7571. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7572. }
  7573. // 验证返回值类型
  7574. if (!is_iterable($streamGenerator)) {
  7575. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7576. dLog('deepseek')->error('addChat流式生成器无效', [
  7577. 'generator_type' => $errorType,
  7578. 'model' => $model,
  7579. 'anime_id' => $anime_id
  7580. ]);
  7581. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  7582. 'type' => $errorType,
  7583. 'model' => $model
  7584. ]);
  7585. yield [
  7586. 'type' => 'error',
  7587. 'script' => [],
  7588. 'episode' => [],
  7589. 'answer' => '',
  7590. 'reasoning' => '',
  7591. 'usage' => [],
  7592. 'error' => '接口返回数据异常,请重新请求'
  7593. ];
  7594. return;
  7595. }
  7596. // 处理流式输出
  7597. foreach ($streamGenerator as $chunk) {
  7598. if (isset($chunk['type'])) {
  7599. if ($chunk['type'] === 'done') {
  7600. // 最终结果
  7601. $fullContent = $chunk['full_content'];
  7602. $fullReasoningContent = $chunk['full_reasoning'];
  7603. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7604. } else {
  7605. // 逐块yield数据
  7606. yield $chunk;
  7607. }
  7608. }
  7609. }
  7610. } catch (\Exception $e) {
  7611. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  7612. 'model' => $model,
  7613. 'anime_id' => $anime_id,
  7614. 'trace' => $e->getTraceAsString()
  7615. ]);
  7616. logDB('deepseek', 'error', 'addChat流式处理失败', [
  7617. 'error' => $e->getMessage(),
  7618. 'model' => $model
  7619. ]);
  7620. yield [
  7621. 'type' => 'error',
  7622. 'script' => [],
  7623. 'episode' => [],
  7624. 'answer' => '',
  7625. 'reasoning' => '',
  7626. 'usage' => [],
  7627. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7628. ];
  7629. return;
  7630. }
  7631. dLog('deepseek')->info('完整内容: '.$fullContent);
  7632. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7633. // 处理完整内容并返回最终结果
  7634. $script_arr = [];
  7635. if ($fullContent) {
  7636. $script_arr = handleScriptContentForAce($fullContent);
  7637. dLog('deepseek')->info('解析内容', $script_arr);
  7638. logDB('deepseek', 'info', '解析内容', $script_arr);
  7639. }
  7640. if (empty($script_arr['roles'])) {
  7641. // 未生成剧本相关内容,保存对话记录并返回提示
  7642. dLog('deepseek')->info('未生成剧本相关的内容');
  7643. try {
  7644. DB::beginTransaction();
  7645. $now = date('Y-m-d H:i:s');
  7646. // 保存对话记录
  7647. $records = [
  7648. [
  7649. 'uid' => $uid,
  7650. 'anime_id' => $anime_id,
  7651. 'sequence' => 0,
  7652. 'role' => 'user',
  7653. 'content' => $prompt,
  7654. 'created_at' => $now,
  7655. 'updated_at' => $now
  7656. ],
  7657. [
  7658. 'uid' => $uid,
  7659. 'anime_id' => $anime_id,
  7660. 'sequence' => 0,
  7661. 'role' => 'assistant',
  7662. // 'content' => $fullContent,
  7663. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  7664. 'created_at' => $now,
  7665. 'updated_at' => $now
  7666. ]
  7667. ];
  7668. DB::table('mp_anime_records')->insert($records);
  7669. DB::commit();
  7670. } catch (\Exception $e) {
  7671. DB::rollBack();
  7672. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7673. }
  7674. yield [
  7675. 'type' => 'done',
  7676. 'script' => [],
  7677. 'episode' => [],
  7678. 'answer' => $fullContent,
  7679. 'reasoning' => $fullReasoningContent,
  7680. 'usage' => $usage,
  7681. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  7682. ];
  7683. return;
  7684. }
  7685. // 如果需要生成原文内容,从script_arr中提取
  7686. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  7687. $content = $script_arr['content'];
  7688. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  7689. if (!$content) {
  7690. yield [
  7691. 'type' => 'done',
  7692. 'script' => [],
  7693. 'episode' => [],
  7694. 'answer' => $fullContent,
  7695. 'reasoning' => $fullReasoningContent,
  7696. 'usage' => $usage,
  7697. 'error' => '未生成剧本内容,请调整提示词再试'
  7698. ];
  7699. return;
  7700. }
  7701. }
  7702. // 替换美术风格
  7703. if ($mappedArtStyle !== '') {
  7704. $script_arr['art_style'] = $mappedArtStyle;
  7705. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  7706. }
  7707. // 新建动漫
  7708. if ($user_anime_name == '新剧本策划') {
  7709. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  7710. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  7711. // if (!$anime_name) {
  7712. // // 未识别到剧本名,保存对话记录并返回提示
  7713. // dLog('deepseek')->info('未能识别到剧本名称');
  7714. // try {
  7715. // DB::beginTransaction();
  7716. // $now = date('Y-m-d H:i:s');
  7717. // // 保存对话记录
  7718. // $records = [
  7719. // [
  7720. // 'uid' => $uid,
  7721. // 'anime_id' => $anime_id,
  7722. // 'sequence' => 0,
  7723. // 'role' => 'user',
  7724. // 'content' => $prompt,
  7725. // 'created_at' => $now,
  7726. // 'updated_at' => $now
  7727. // ],
  7728. // [
  7729. // 'uid' => $uid,
  7730. // 'anime_id' => $anime_id,
  7731. // 'sequence' => 0,
  7732. // 'role' => 'assistant',
  7733. // 'content' => '未能生成剧本名称,请重试',
  7734. // 'created_at' => $now,
  7735. // 'updated_at' => $now
  7736. // ]
  7737. // ];
  7738. // DB::table('mp_anime_records')->insert($records);
  7739. // DB::commit();
  7740. // } catch (\Exception $e) {
  7741. // DB::rollBack();
  7742. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7743. // }
  7744. // yield [
  7745. // 'type' => 'done',
  7746. // 'script' => [],
  7747. // 'episode' => [],
  7748. // 'answer' => $fullContent,
  7749. // 'reasoning' => $fullReasoningContent,
  7750. // 'usage' => $usage,
  7751. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  7752. // ];
  7753. // return;
  7754. // }
  7755. // 确认对话名称唯一性
  7756. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  7757. $anime_name = $anime_name . '_' . date('YmdHis');
  7758. }
  7759. }else {
  7760. $anime_name = $user_anime_name;
  7761. }
  7762. $table_data = [
  7763. 'user_id' => $uid,
  7764. 'anime_name' => $anime_name,
  7765. 'model' => $model,
  7766. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  7767. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  7768. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  7769. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  7770. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  7771. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  7772. 'art_style_type' => $input_art_style,
  7773. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  7774. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  7775. 'status' => '解析完成',
  7776. 'content' => $content,
  7777. 'is_multi' => $is_multi,
  7778. 'ace_mode' => $ace_mode,
  7779. 'generate_status' => '待执行',
  7780. 'updated_at' => date('Y-m-d H:i:s')
  7781. ];
  7782. if ($table_data['content']) {
  7783. $chapters = splitContent($table_data['content']);
  7784. $chapter_count = count($chapters);
  7785. if ($chapter_count > 0) {
  7786. $table_data['start_episode_sequence'] = 1;
  7787. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  7788. }
  7789. }
  7790. if ($extra_products) {
  7791. $table_data['extra_products'] = json_encode($extra_products, 256);
  7792. }
  7793. // 如果有剧本ID则进行绑定
  7794. if ($script_id) {
  7795. $table_data['script_id'] = $script_id;
  7796. }
  7797. $single_episode = [];
  7798. try {
  7799. DB::beginTransaction();
  7800. $now = date('Y-m-d H:i:s');
  7801. // 更新动漫大纲
  7802. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7803. if (!$boolen) {
  7804. dLog('deepseek')->info('动漫保存失败', $table_data);
  7805. Utils::throwError('20003:动漫保存失败');
  7806. }
  7807. // 保存对话记录
  7808. $records = [
  7809. [
  7810. 'uid' => $uid,
  7811. 'anime_id' => $anime_id,
  7812. 'sequence' => 0,
  7813. 'role' => 'user',
  7814. 'content' => $prompt,
  7815. 'created_at' => date('Y-m-d H:i:s'),
  7816. 'updated_at' => date('Y-m-d H:i:s')
  7817. ],
  7818. [
  7819. 'uid' => $uid,
  7820. 'anime_id' => $anime_id,
  7821. 'sequence' => 0,
  7822. 'role' => 'assistant',
  7823. 'content' => $fullContent,
  7824. 'created_at' => date('Y-m-d H:i:s'),
  7825. 'updated_at' => date('Y-m-d H:i:s')
  7826. ]
  7827. ];
  7828. // 保存对话记录
  7829. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7830. if (!$boolen3) {
  7831. Utils::throwError('20003:对话记录保存失败');
  7832. }
  7833. if ($is_single) {
  7834. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7835. if (empty($episode_arr['acts'])) {
  7836. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7837. }
  7838. $saveResult = $this->saveEpisodeVersionData(
  7839. $anime_id,
  7840. 1,
  7841. $episode_arr,
  7842. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7843. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7844. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7845. null,
  7846. null,
  7847. false,
  7848. $content,
  7849. $now,
  7850. $ref_products
  7851. );
  7852. $single_episode = $saveResult['episode'];
  7853. $episode_id = $saveResult['episode_id'];
  7854. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7855. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7856. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7857. 'props' => json_encode($saveResult['merged_props'], 256),
  7858. 'updated_at' => $now
  7859. ]);
  7860. if ($boolen5 === false) {
  7861. Utils::throwError('20003:单剧集主表资源同步失败');
  7862. }
  7863. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7864. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7865. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7866. $episode_record_content = '确认分镜大纲';
  7867. if ($content !== '') {
  7868. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7869. }
  7870. $episode_records = [
  7871. [
  7872. 'uid' => $uid,
  7873. 'anime_id' => $anime_id,
  7874. 'role' => 'user',
  7875. 'content' => $episode_record_content,
  7876. 'sequence' => 1,
  7877. 'episode_id' => $episode_id,
  7878. 'created_at' => $now,
  7879. 'updated_at' => $now
  7880. ],
  7881. [
  7882. 'uid' => $uid,
  7883. 'anime_id' => $anime_id,
  7884. 'role' => 'assistant',
  7885. 'content' => $fullContent,
  7886. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7887. 'sequence' => 1,
  7888. 'episode_id' => $episode_id,
  7889. 'created_at' => $now,
  7890. 'updated_at' => $now
  7891. ]
  7892. ];
  7893. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7894. if (!$boolen4) {
  7895. Utils::throwError('20003:单剧集分镜记录保存失败');
  7896. }
  7897. }
  7898. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7899. if ($is_single && !empty($single_episode)) {
  7900. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7901. 'anime_id' => $anime_id,
  7902. 'episode_id' => $episode_id ?? 0,
  7903. 'model' => $model,
  7904. 'source' => 'addChatForAce',
  7905. ]);
  7906. }
  7907. }catch (\Exception $e) {
  7908. DB::rollBack();
  7909. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7910. yield [
  7911. 'type' => 'done',
  7912. 'answer' => $fullContent,
  7913. 'reasoning' => $fullReasoningContent,
  7914. 'usage' => $usage,
  7915. 'error' => $e->getMessage(),
  7916. ];
  7917. return;
  7918. }
  7919. DB::commit();
  7920. dLog('deepseek')->info('保存完毕');
  7921. if ($is_single && !empty($single_episode)) {
  7922. // $this->batchSetGlobalRoleImg([
  7923. // 'anime_id' => $anime_id,
  7924. // ]);
  7925. // $this->batchSetGlobalSceneImg([
  7926. // 'anime_id' => $anime_id,
  7927. // ]);
  7928. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7929. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7930. }
  7931. $table_data['anime_id'] = $anime_id;
  7932. $table_data['roles'] = json_decode($table_data['roles'], true);
  7933. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7934. // $table_data['episodes'] = $script_arr['episodes'];
  7935. unset($table_data['created_at']);
  7936. unset($table_data['updated_at']);
  7937. unset($table_data['status']);
  7938. dLog('deepseek')->info('开始返回');
  7939. yield [
  7940. 'type' => 'done',
  7941. 'script' => $table_data,
  7942. 'episode' => $single_episode,
  7943. 'answer' => $fullContent,
  7944. 'reasoning' => $fullReasoningContent,
  7945. 'usage' => $usage
  7946. ];
  7947. }
  7948. public function reGenerateAnimeForAce($data) {
  7949. $uid = Site::getUid();
  7950. $file = getProp($data, 'file');
  7951. $content = getProp($data, 'content', '');
  7952. $bid = getProp($data, 'bid', 0);
  7953. $script_id = getProp($data, 'script_id', 0);
  7954. $anime_id = getProp($data, 'anime_id');
  7955. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7956. if (!$anime) {
  7957. Utils::throwError('20003:该对话不存在');
  7958. }
  7959. $is_multi = getProp($anime, 'is_multi', 1);
  7960. $is_single = (int)$is_multi !== 1;
  7961. // 积分余额预检(仅单剧集模式收费)
  7962. if ($is_single) {
  7963. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  7964. }
  7965. $extra_products = getProp($data, 'products', []);
  7966. if (!$extra_products) {
  7967. $extra_products = getProp($anime, 'extra_products');
  7968. if ($extra_products) {
  7969. $extra_products = json_decode($extra_products, true);
  7970. }else {
  7971. $extra_products = [];
  7972. }
  7973. }else {
  7974. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7975. }
  7976. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7977. $anime_script_id = getProp($anime, 'script_id');
  7978. if ($anime_script_id && $is_single) {
  7979. $cpid = Site::getCpid();
  7980. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7981. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7982. ->where('mapping.script_id', $anime_script_id)
  7983. ->where('product.cpid', $cpid)
  7984. ->where('product.is_deleted', 0);
  7985. $mappings = $script_products_mappings->select(
  7986. 'mapping.product_id',
  7987. 'mapping.episode_number',
  7988. 'product.product_name',
  7989. 'product.type',
  7990. 'product.product',
  7991. 'product.pic_prompt',
  7992. 'product.url',
  7993. 'product.pic_task_id',
  7994. 'product.pic_task_status',
  7995. 'product.three_view_image_url'
  7996. )
  7997. ->get();
  7998. // 按 product_id 分组,合并 episode_number
  7999. $productMap = [];
  8000. foreach ($mappings as $item) {
  8001. $product_id = $item->product_id;
  8002. $product_name = $item->product_name;
  8003. // 处理product_name两边的符号
  8004. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8005. if (!isset($productMap[$product_id])) {
  8006. $productMap[$product_id] = [
  8007. 'product_id' => $product_id,
  8008. 'product_name' => $product_name,
  8009. 'type' => (int)$item->type,
  8010. 'product' => (int)$item->product,
  8011. 'pic_prompt' => $item->pic_prompt,
  8012. 'url' => $item->url,
  8013. 'pic_task_id' => $item->pic_task_id,
  8014. 'pic_task_status' => $item->pic_task_status,
  8015. 'episode_numbers' => [],
  8016. ];
  8017. }
  8018. // 添加 episode_number(去重)
  8019. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8020. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8021. }
  8022. }
  8023. // 将查询到的剧本资产合并到extra_products中
  8024. // 先构建extra_products的索引(以product_id为key,用于去重)
  8025. $extraProductsMap = [];
  8026. foreach ($extra_products as $item) {
  8027. $key = getProp($item, 'product_id');
  8028. if ($key) {
  8029. $extraProductsMap[$key] = $item;
  8030. }
  8031. }
  8032. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  8033. foreach ($productMap as $product) {
  8034. $product_id = $product['product_id'];
  8035. // 如果不存在则添加(不带episode_number信息)
  8036. if (!isset($extraProductsMap[$product_id])) {
  8037. $extraProductsMap[$product_id] = [
  8038. 'product_id' => $product['product_id'],
  8039. 'product_name' => $product['product_name'],
  8040. 'type' => $product['type'],
  8041. 'product' => $product['product'],
  8042. 'pic_prompt' => $product['pic_prompt'],
  8043. 'url' => $product['url'],
  8044. 'pic_task_id' => $product['pic_task_id'],
  8045. 'pic_task_status' => $product['pic_task_status'],
  8046. ];
  8047. }
  8048. }
  8049. // 重新赋值给extra_products
  8050. $extra_products = array_values($extraProductsMap);
  8051. }
  8052. $user_anime_name = getProp($anime, 'anime_name');
  8053. $prompt = getProp($data, 'prompt');
  8054. // 处理提示词
  8055. if ($prompt && $extra_products) {
  8056. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8057. foreach($extra_products as $item) {
  8058. $product_name = getProp($item, 'product_name');
  8059. if ($product_name) {
  8060. // 替换 {product_name} 为 product_name
  8061. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8062. }
  8063. }
  8064. }
  8065. // 处理文本模型
  8066. $model = getProp($data, 'model');
  8067. if (!$model) {
  8068. // 用户没有输入,从anime表获取
  8069. $model = getProp($anime, 'model');
  8070. if (!$model) {
  8071. // anime表也没有,使用默认值
  8072. $model = 'deepseek-v4-pro';
  8073. }
  8074. }
  8075. // 验证模型是否在可用模型表中
  8076. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8077. $model = 'deepseek-v4-pro';
  8078. }
  8079. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  8080. if ($is_single) {
  8081. $episode_exists = DB::table('mp_anime_episodes')
  8082. ->where('anime_id', $anime_id)
  8083. ->where('sequence', 1)
  8084. ->exists();
  8085. if ($episode_exists) {
  8086. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  8087. }
  8088. }
  8089. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  8090. if ($prompt) {
  8091. $question .= "本次修改要求如下:\n{$prompt}";
  8092. }
  8093. // 提取文件内容
  8094. if ($file) {
  8095. $content = $this->extractFileContent($file);
  8096. if (!$content) {
  8097. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8098. }
  8099. } elseif ($script_id) {
  8100. $content = $this->getContentByScriptId($script_id);
  8101. if (!$content) {
  8102. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  8103. }
  8104. } elseif ($bid) {
  8105. $content = $this->getContentByBid($bid);
  8106. if (!$content) {
  8107. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  8108. }
  8109. } elseif ($content) {
  8110. $content = filterContent($content);
  8111. }else {
  8112. $content = filterContent(getProp($anime, 'content'));
  8113. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  8114. $need_generate_content = true;
  8115. }
  8116. }
  8117. // 判断是否需要生成原文内容
  8118. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  8119. // 如果需要生成原文内容,添加额外的要求
  8120. $content_generation_requirement = $need_generate_content
  8121. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  8122. : "";
  8123. // 美术风格
  8124. $input_art_style = getProp($data, 'art_style');
  8125. if (!$input_art_style) {
  8126. $mappedArtStyle = getProp($anime, 'art_style');
  8127. }else {
  8128. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  8129. }
  8130. if (!$mappedArtStyle) {
  8131. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  8132. }else {
  8133. if (strstr($mappedArtStyle, '基础画风风格词')) {
  8134. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  8135. }else {
  8136. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  8137. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  8138. }
  8139. }
  8140. // 构建主体、场景和道具提示词
  8141. $extra_role_prompt = "\n";
  8142. $extra_scene_prompt = "\n";
  8143. $extra_prop_prompt = "\n";
  8144. $ref_products = []; // 参考资产
  8145. if ($extra_products) {
  8146. foreach($extra_products as $item) {
  8147. $product = getProp($item, 'product');
  8148. $product_name = getProp($item, 'product_name');
  8149. if ($product_name == '旁白') continue;
  8150. $ref_products[$product_name] = $item;
  8151. $pic_prompt = getProp($item, 'pic_prompt');
  8152. if ((int)$product === 1) {
  8153. // 拼接角色信息
  8154. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8155. } elseif ((int)$product === 2) {
  8156. // 拼接场景信息
  8157. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8158. } elseif ((int)$product === 3) {
  8159. // 拼接道具信息
  8160. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8161. }
  8162. }
  8163. // 优化提示词,融入剧本
  8164. if (!empty(trim($extra_role_prompt))) {
  8165. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  8166. }
  8167. if (!empty(trim($extra_scene_prompt))) {
  8168. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  8169. }
  8170. if (!empty(trim($extra_prop_prompt))) {
  8171. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  8172. }
  8173. }
  8174. if ($anime_script_id && $is_single) {
  8175. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  8176. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  8177. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  8178. }else {
  8179. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8180. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8181. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8182. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8183. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8184. {$extra_role_prompt}";
  8185. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8186. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  8187. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8188. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8189. {$extra_scene_prompt}";
  8190. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8191. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  8192. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8193. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  8194. {$extra_prop_prompt}";
  8195. }
  8196. $system_message = ['role'=>'system', 'content'=>$is_single
  8197. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  8198. 强制要求:
  8199. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8200. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8201. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8202. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8203. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8204. 普通要求:
  8205. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  8206. $role_demo
  8207. $scene_demo
  8208. $prop_demo
  8209. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8210. 5.1片段分割逻辑(优先级从高到低):
  8211. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8212. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8213. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8214. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8215. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8216. - 片段数量格式为: 片段数量:8
  8217. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8218. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8219. 5.3分镜结构:每个分镜包含以下字段:
  8220. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8221. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8222. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8223. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8224. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8225. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8226. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8227. - 运镜:场景+画面描述+运镜
  8228. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8229. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8230. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8231. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  8232. 6.{$mappedArtStyle_prompt}\n\n
  8233. 示例如下:\n
  8234. ###剧本名:西昆仑
  8235. ###故事梗概
  8236. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8237. ###剧本亮点
  8238. 亮点1:绝境奇药,生死一线
  8239. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8240. 亮点2:结拜兄妹,化解尴尬
  8241. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8242. 亮点3:纤发夺命,情愫暗涌
  8243. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8244. ###人物关系
  8245. 阿雪与梁萧之间存在兄妹之情。
  8246. ###核心矛盾
  8247. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8248. ###主体列表
  8249. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8250. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8251. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8252. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8253. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8254. 全景,正面拍摄,青年女性,亚洲人。
  8255. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8256. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8257. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8258. ###美术风格
  8259. 基础画风风格词:厚涂古风
  8260. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8261. ###场景列表
  8262. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8263. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8264. 无人物。}
  8265. ###分段剧本
  8266. 片段数量:8
  8267. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8268. ##片段1
  8269. 时长:12s
  8270. 分镜1
  8271. 出场角色:刀疤脸
  8272. 场景:边境小镇街道
  8273. 出场道具:酒杯-高脚杯
  8274. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8275. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8276. 配音台词:
  8277. 背景音效:
  8278. 分镜2
  8279. 出场角色:刀疤脸
  8280. 场景:悦来酒馆
  8281. 出场道具:酒杯-高脚杯
  8282. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8283. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8284. 配音台词:
  8285. 背景音效:
  8286. 分镜3
  8287. 出场角色:刀疤脸
  8288. 场景:悦来酒馆
  8289. 出场道具:酒杯-高脚杯
  8290. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8291. 运镜:从中景推向令牌特写。
  8292. 配音台词:
  8293. 背景音效:
  8294. 分镜4
  8295. 出场角色:刀疤脸
  8296. 场景:悦来酒馆
  8297. 出场道具:酒杯-高脚杯
  8298. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8299. 运镜:极速推向酒水溅起的瞬间。
  8300. 配音台词:
  8301. 背景音效:
  8302. 分镜5
  8303. 出场角色:刀疤脸
  8304. 场景:悦来酒馆
  8305. 出场道具:酒杯-高脚杯
  8306. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8307. 运镜:固定机位,利用倾斜构图制造压迫感。
  8308. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8309. 背景音效:
  8310. \n\n"
  8311. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8312. 强制要求:\n
  8313. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8314. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8315. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8316. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8317. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8318. 普通要求:\n
  8319. 1.剧本名(必须生成)必须与文档内容高度相关
  8320. $role_demo
  8321. $scene_demo
  8322. $prop_demo
  8323. 5.{$mappedArtStyle_prompt}\n\n
  8324. 示例如下:\n
  8325. ###剧本名:西昆仑
  8326. ###故事梗概
  8327. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8328. ###剧本亮点
  8329. 亮点1:绝境奇药,生死一线
  8330. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8331. 亮点2:结拜兄妹,化解尴尬
  8332. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8333. 亮点3:纤发夺命,情愫暗涌
  8334. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8335. ###人物关系
  8336. 阿雪与梁萧之间存在兄妹之情。
  8337. ###核心矛盾
  8338. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8339. ###主体列表
  8340. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8341. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8342. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8343. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8344. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8345. 全景,正面拍摄,青年女性,亚洲人。
  8346. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8347. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8348. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8349. ###美术风格
  8350. 基础画风风格词:厚涂古风
  8351. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8352. ###场景列表
  8353. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8354. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8355. 无人物。}
  8356. ###道具列表
  8357. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  8358. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  8359. $episode_count = $this->extractEpisodeNumber($prompt);
  8360. if ((int)getProp($anime, 'is_multi') !== 1) {
  8361. yield [
  8362. 'type' => 'done',
  8363. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  8364. 'reasoning' => '',
  8365. 'usage' => []
  8366. ];
  8367. return;
  8368. }
  8369. if ($episode_count) {
  8370. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  8371. $system_message = [
  8372. 'role' => 'system',
  8373. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8374. 强制要求:\n
  8375. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8376. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8377. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8378. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8379. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8380. 普通要求:\n
  8381. 1.<故事梗概>控制在200-300字左右
  8382. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8383. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8384. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8385. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8386. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8387. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8388. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8389. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8390. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8391. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  8392. 示例如下:\n
  8393. ###剧本名:西昆仑
  8394. ###故事梗概
  8395. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8396. ###剧本亮点
  8397. 亮点1:绝境奇药,生死一线
  8398. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8399. 亮点2:结拜兄妹,化解尴尬
  8400. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8401. 亮点3:纤发夺命,情愫暗涌
  8402. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8403. ###人物关系
  8404. 阿雪与梁萧之间存在兄妹之情。
  8405. ###核心矛盾
  8406. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8407. ###主体列表
  8408. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8409. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8410. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8411. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8412. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8413. 全景,正面拍摄,青年女性,亚洲人。
  8414. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8415. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8416. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8417. ###美术风格
  8418. 基础画风风格词:厚涂古风
  8419. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8420. ###场景列表
  8421. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8422. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8423. 无人物。}
  8424. ###分集详细内容
  8425. ##第1章 重生
  8426. 我重生了。
  8427. 源于一个男人偏执的暗恋。
  8428. ##第2章 相救
  8429. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  8430. 我眼睛扫向站在锅炉后的卞大伟。"
  8431. ];
  8432. // 构建消息
  8433. $messages = [
  8434. $system_message,
  8435. [
  8436. 'role' => 'user',
  8437. 'content' => "以下是文档内容:
  8438. {$content}
  8439. 用户问题:
  8440. {$question}"
  8441. ]
  8442. ];
  8443. }else {
  8444. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  8445. // 构建消息
  8446. $messages = [
  8447. $system_message,
  8448. [
  8449. 'role' => 'user',
  8450. 'content' => "以下是文档内容:
  8451. {$content}
  8452. 用户问题:
  8453. {$question}"
  8454. ]
  8455. ];
  8456. }else {
  8457. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  8458. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  8459. return (array)$value;
  8460. })->toArray();
  8461. array_unshift($messages, $system_message);
  8462. $messages[] = [
  8463. 'role' => 'user',
  8464. 'content' => $prompt
  8465. ];
  8466. }
  8467. }
  8468. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8469. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  8470. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8471. if ($model === 'deepseek-chat') {
  8472. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8473. $model = 'deepseek-v4-flash';
  8474. $thinkingMode = 'disabled';
  8475. } elseif ($model === 'deepseek-reasoner') {
  8476. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8477. $model = 'deepseek-v4-flash';
  8478. $thinkingMode = 'enabled';
  8479. }
  8480. $post_data = [
  8481. 'model' => $model,
  8482. 'messages' => $messages,
  8483. // 'max_tokens' => 8192,
  8484. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8485. 'frequency_penalty' => 0,
  8486. 'presence_penalty' => 0,
  8487. 'response_format' => ['type' => 'text'],
  8488. 'thinking' => ['type' => $thinkingMode],
  8489. 'stream' => true // 启用流式输出
  8490. ];
  8491. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8492. // 根据模型类型选择调用方法
  8493. $fullContent = '';
  8494. $fullReasoningContent = '';
  8495. $usage = [];
  8496. // dd($post_data);
  8497. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  8498. try {
  8499. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8500. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8501. } else if (in_array($model, $this->gpt_text_models)) {
  8502. // GPT-5.4 模型使用 TokenRouter API
  8503. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8504. } else if (in_array($model, $this->gemini_text_models)) {
  8505. // Gemini 模型使用 Gemini API
  8506. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8507. } else {
  8508. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8509. }
  8510. // 验证返回值类型
  8511. if (!is_iterable($streamGenerator)) {
  8512. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8513. dLog('deepseek')->error('方法名流式生成器无效', [
  8514. 'generator_type' => $errorType,
  8515. 'model' => $model,
  8516. // 添加其他上下文信息
  8517. ]);
  8518. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  8519. 'type' => $errorType,
  8520. 'model' => $model
  8521. ]);
  8522. yield [
  8523. 'type' => 'error',
  8524. // 根据方法返回相应的空数据结构
  8525. 'answer' => '',
  8526. 'reasoning' => '',
  8527. 'usage' => [],
  8528. 'error' => '接口返回数据异常,请重新请求'
  8529. ];
  8530. return;
  8531. }
  8532. // 处理流式输出
  8533. foreach ($streamGenerator as $chunk) {
  8534. if (isset($chunk['type'])) {
  8535. if ($chunk['type'] === 'done') {
  8536. $fullContent = $chunk['full_content'];
  8537. $fullReasoningContent = $chunk['full_reasoning'];
  8538. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8539. } else {
  8540. yield $chunk;
  8541. }
  8542. }
  8543. }
  8544. } catch (\Exception $e) {
  8545. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  8546. 'model' => $model,
  8547. 'trace' => $e->getTraceAsString()
  8548. ]);
  8549. logDB('deepseek', 'error', '方法名流式处理失败', [
  8550. 'error' => $e->getMessage(),
  8551. 'model' => $model
  8552. ]);
  8553. yield [
  8554. 'type' => 'error',
  8555. // 根据方法返回相应的空数据结构
  8556. 'answer' => '',
  8557. 'reasoning' => '',
  8558. 'usage' => [],
  8559. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8560. ];
  8561. return;
  8562. }
  8563. dLog('deepseek')->info('完整内容: '.$fullContent);
  8564. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8565. // 处理完整内容并返回最终结果
  8566. $script_arr = [];
  8567. if ($fullContent) {
  8568. $script_arr = handleScriptContentForAce($fullContent);
  8569. dLog('deepseek')->info('解析内容', $script_arr);
  8570. logDB('deepseek', 'info', '解析内容', $script_arr);
  8571. }
  8572. if (empty($script_arr['roles'])) {
  8573. // 未生成剧本相关内容,保存对话记录并返回提示
  8574. dLog('deepseek')->info('未生成剧本相关的内容');
  8575. try {
  8576. $now = date('Y-m-d H:i:s');
  8577. // 保存对话记录
  8578. $records = [
  8579. [
  8580. 'uid' => $uid,
  8581. 'anime_id' => $anime_id,
  8582. 'sequence' => 0,
  8583. 'role' => 'user',
  8584. 'content' => $prompt,
  8585. 'created_at' => $now,
  8586. 'updated_at' => $now
  8587. ],
  8588. [
  8589. 'uid' => $uid,
  8590. 'anime_id' => $anime_id,
  8591. 'sequence' => 0,
  8592. 'role' => 'assistant',
  8593. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  8594. 'created_at' => $now,
  8595. 'updated_at' => $now
  8596. ]
  8597. ];
  8598. DB::table('mp_anime_records')->insert($records);
  8599. } catch (\Exception $e) {
  8600. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8601. }
  8602. yield [
  8603. 'type' => 'done',
  8604. 'script' => [],
  8605. 'episode' => [],
  8606. 'answer' => $fullContent,
  8607. 'reasoning' => $fullReasoningContent,
  8608. 'usage' => $usage,
  8609. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  8610. ];
  8611. return;
  8612. }
  8613. // 替换美术风格
  8614. if ($mappedArtStyle !== '') {
  8615. $script_arr['art_style'] = $mappedArtStyle;
  8616. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8617. }
  8618. if ($user_anime_name != '新剧本策划') {
  8619. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  8620. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  8621. // 确认对话名称唯一性
  8622. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  8623. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  8624. }
  8625. }else {
  8626. $anime_name = $user_anime_name;
  8627. }
  8628. $table_data = [
  8629. 'user_id' => $uid,
  8630. 'model' => $model,
  8631. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  8632. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  8633. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  8634. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  8635. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  8636. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  8637. 'art_style_type' => $input_art_style,
  8638. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  8639. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  8640. 'status' => '解析完成',
  8641. 'generate_status' => '待执行',
  8642. 'updated_at' => date('Y-m-d H:i:s')
  8643. ];
  8644. if ($anime_name) $table_data['anime_name'] = $anime_name;
  8645. // 如果是修改集数,则将content内容更新(会改变原文)
  8646. if (isset($episode_count) && $episode_count > 0) {
  8647. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  8648. $table_data['start_episode_sequence'] = 1;
  8649. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  8650. }else {
  8651. // 如果需要生成原文内容,从script_arr中提取
  8652. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  8653. $table_data['content'] = $script_arr['content'];
  8654. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  8655. if (!$table_data['content']) {
  8656. yield [
  8657. 'type' => 'done',
  8658. 'script' => [],
  8659. 'episode' => [],
  8660. 'answer' => $fullContent,
  8661. 'reasoning' => $fullReasoningContent,
  8662. 'usage' => $usage,
  8663. 'error' => '未生成剧本内容,请调整提示词再试'
  8664. ];
  8665. return;
  8666. }
  8667. }
  8668. if (isset($table_data['content']) && $table_data['content']) {
  8669. $chapters = splitContent($table_data['content']);
  8670. $chapter_count = count($chapters);
  8671. if ($chapter_count > 0) {
  8672. $table_data['start_episode_sequence'] = 1;
  8673. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  8674. }
  8675. }
  8676. }
  8677. if ($extra_products) {
  8678. $table_data['extra_products'] = json_encode($extra_products, 256);
  8679. }
  8680. $single_episode = [];
  8681. try {
  8682. DB::beginTransaction();
  8683. $now = date('Y-m-d H:i:s');
  8684. // 更新动漫大纲
  8685. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  8686. if (!$boolen) {
  8687. dLog('deepseek')->info('对话修改失败', $table_data);
  8688. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  8689. Utils::throwError('20003:对话修改失败');
  8690. }
  8691. // 保存对话记录
  8692. $records = [
  8693. [
  8694. 'uid' => $uid,
  8695. 'anime_id' => $anime_id,
  8696. 'sequence' => 0,
  8697. 'role' => 'user',
  8698. 'content' => $prompt,
  8699. 'created_at' => $now,
  8700. 'updated_at' => $now
  8701. ],
  8702. [
  8703. 'uid' => $uid,
  8704. 'anime_id' => $anime_id,
  8705. 'sequence' => 0,
  8706. 'role' => 'assistant',
  8707. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8708. 'content' => $fullContent,
  8709. 'created_at' => $now,
  8710. 'updated_at' => $now
  8711. ]
  8712. ];
  8713. // 保存对话记录
  8714. $boolen3 = DB::table('mp_anime_records')->insert($records);
  8715. if (!$boolen3) {
  8716. Utils::throwError('20003:对话记录保存失败');
  8717. }
  8718. // 单剧集模式:生成并保存剧集信息
  8719. if ($is_single) {
  8720. $anime_name = getProp($anime, 'anime_name', '未命名');
  8721. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8722. if (empty($episode_arr['acts'])) {
  8723. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  8724. }
  8725. $saveResult = $this->saveEpisodeVersionData(
  8726. $anime_id,
  8727. 1,
  8728. $episode_arr,
  8729. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8730. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8731. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  8732. null,
  8733. null,
  8734. false,
  8735. $content,
  8736. $now,
  8737. $ref_products
  8738. );
  8739. $single_episode = $saveResult['episode'];
  8740. $episode_id = $saveResult['episode_id'];
  8741. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  8742. 'roles' => json_encode($saveResult['merged_roles'], 256),
  8743. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  8744. 'props' => json_encode($saveResult['merged_props'], 256),
  8745. 'updated_at' => $now
  8746. ]);
  8747. if ($boolen5 === false) {
  8748. Utils::throwError('20003:单剧集主表资源同步失败');
  8749. }
  8750. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  8751. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  8752. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  8753. $episode_record_content = '确认分镜大纲';
  8754. if ($content !== '') {
  8755. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  8756. }
  8757. $episode_records = [
  8758. [
  8759. 'uid' => $uid,
  8760. 'anime_id' => $anime_id,
  8761. 'role' => 'user',
  8762. 'content' => $episode_record_content,
  8763. 'sequence' => 1,
  8764. 'episode_id' => $episode_id,
  8765. 'created_at' => $now,
  8766. 'updated_at' => $now
  8767. ],
  8768. [
  8769. 'uid' => $uid,
  8770. 'anime_id' => $anime_id,
  8771. 'role' => 'assistant',
  8772. 'content' => $fullContent,
  8773. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8774. 'sequence' => 1,
  8775. 'episode_id' => $episode_id,
  8776. 'created_at' => $now,
  8777. 'updated_at' => $now
  8778. ]
  8779. ];
  8780. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  8781. if (!$boolen4) {
  8782. Utils::throwError('20003:单剧集分镜记录保存失败');
  8783. }
  8784. }
  8785. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8786. if ($is_single && !empty($single_episode)) {
  8787. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8788. 'anime_id' => $anime_id,
  8789. 'episode_id' => $episode_id ?? 0,
  8790. 'model' => $model,
  8791. 'source' => 'reGenerateAnimeForAce',
  8792. ]);
  8793. }
  8794. }catch (\Exception $e) {
  8795. DB::rollBack();
  8796. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  8797. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  8798. yield [
  8799. 'type' => 'done',
  8800. 'answer' => $fullContent,
  8801. 'reasoning' => $fullReasoningContent,
  8802. 'usage' => $usage,
  8803. 'error' => $e->getMessage(),
  8804. ];
  8805. return;
  8806. }
  8807. DB::commit();
  8808. dLog('deepseek')->info('保存完毕');
  8809. if ($is_single && !empty($single_episode)) {
  8810. // $this->batchSetGlobalRoleImg([
  8811. // 'anime_id' => $anime_id,
  8812. // ]);
  8813. // $this->batchSetGlobalSceneImg([
  8814. // 'anime_id' => $anime_id,
  8815. // ]);
  8816. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8817. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8818. }
  8819. $table_data['anime_id'] = $anime_id;
  8820. $table_data['roles'] = json_decode($table_data['roles'], true);
  8821. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8822. $table_data['props'] = json_decode($table_data['props'], true);
  8823. unset($table_data['updated_at']);
  8824. unset($table_data['status']);
  8825. yield [
  8826. 'type' => 'done',
  8827. 'script' => $table_data,
  8828. 'episode' => $single_episode,
  8829. 'answer' => $fullContent,
  8830. 'reasoning' => $fullReasoningContent,
  8831. 'usage' => $usage
  8832. ];
  8833. }
  8834. public function chatForAce($data) {
  8835. $uid = Site::getUid();
  8836. // 积分余额预检(不足直接报错)
  8837. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  8838. $anime_id = getProp($data, 'anime_id');
  8839. $file = getProp($data, 'file');
  8840. $content = getProp($data, 'content', '');
  8841. $bid = getProp($data, 'bid', 0);
  8842. $script_id = getProp($data, 'script_id', 0);
  8843. $episode_number = getProp($data, 'episode_number', 1);
  8844. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8845. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8846. if (!$anime) Utils::throwError('20003:该对话不存在!');
  8847. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  8848. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  8849. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  8850. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  8851. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  8852. $roles = is_array($roles) ? $roles : [];
  8853. $scenes = is_array($scenes) ? $scenes : [];
  8854. $extra_products = getProp($data, 'products', []);
  8855. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  8856. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  8857. $anime_script_id = getProp($anime, 'script_id');
  8858. if ($anime_script_id) {
  8859. $cpid = Site::getCpid();
  8860. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  8861. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8862. ->where('mapping.script_id', $anime_script_id)
  8863. ->where('product.cpid', $cpid)
  8864. ->where('product.is_deleted', 0);
  8865. // 如果提供了 episode_number,则过滤指定集数
  8866. if ($episode_number !== null && $episode_number !== '') {
  8867. $script_products_mappings->where('mapping.episode_number', $episode_number);
  8868. }
  8869. $mappings = $script_products_mappings->select(
  8870. 'mapping.product_id',
  8871. 'mapping.episode_number',
  8872. 'product.product_name',
  8873. 'product.type',
  8874. 'product.product',
  8875. 'product.pic_prompt',
  8876. 'product.url',
  8877. 'product.pic_task_id',
  8878. 'product.pic_task_status',
  8879. 'product.three_view_image_url'
  8880. )
  8881. ->get();
  8882. // 按 product_id 分组,合并 episode_number
  8883. $productMap = [];
  8884. foreach ($mappings as $item) {
  8885. $product_id = $item->product_id;
  8886. $product_name = $item->product_name;
  8887. // 处理product_name两边的符号
  8888. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8889. if (!isset($productMap[$product_id])) {
  8890. $productMap[$product_id] = [
  8891. 'product_id' => $product_id,
  8892. 'product_name' => $product_name,
  8893. 'type' => (int)$item->type,
  8894. 'product' => (int)$item->product,
  8895. 'pic_prompt' => $item->pic_prompt,
  8896. 'url' => $item->url,
  8897. 'pic_task_id' => $item->pic_task_id,
  8898. 'pic_task_status' => $item->pic_task_status,
  8899. 'episode_numbers' => [],
  8900. ];
  8901. }
  8902. // 添加 episode_number(去重)
  8903. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8904. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8905. }
  8906. }
  8907. // 将查询到的剧本资产合并到extra_products中
  8908. // 先构建extra_products的索引(以product_id+episode_number为key)
  8909. $extraProductsMap = [];
  8910. foreach ($extra_products as $item) {
  8911. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  8912. $extraProductsMap[$key] = $item;
  8913. }
  8914. // 合并剧本资产(去重:product_id+episode_number)
  8915. foreach ($productMap as $product) {
  8916. foreach ($product['episode_numbers'] as $ep_num) {
  8917. $key = $product['product_id'] . '_' . $ep_num;
  8918. // 如果不存在则添加
  8919. if (!isset($extraProductsMap[$key])) {
  8920. $extraProductsMap[$key] = [
  8921. 'product_id' => $product['product_id'],
  8922. 'product_name' => $product['product_name'],
  8923. 'type' => $product['type'],
  8924. 'product' => $product['product'],
  8925. 'pic_prompt' => $product['pic_prompt'],
  8926. 'url' => $product['url'],
  8927. 'pic_task_id' => $product['pic_task_id'],
  8928. 'pic_task_status' => $product['pic_task_status'],
  8929. 'episode_number' => $ep_num,
  8930. ];
  8931. }
  8932. }
  8933. }
  8934. // 重新赋值给extra_products
  8935. $extra_products = array_values($extraProductsMap);
  8936. }
  8937. // 处理提示词
  8938. if ($prompt && $extra_products) {
  8939. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8940. foreach($extra_products as $item) {
  8941. $product_name = getProp($item, 'product_name');
  8942. if ($product_name) {
  8943. // 替换 {product_name} 为 product_name
  8944. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8945. }
  8946. }
  8947. }
  8948. // 获取最后一集序号
  8949. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  8950. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  8951. // 转换主体列表和场景列表的格式
  8952. // 获取参考主体或场景
  8953. if ((int)$episode_number === 1) {
  8954. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  8955. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  8956. }else {
  8957. $prev_episode_number = $episode_number - 1;
  8958. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  8959. }
  8960. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  8961. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  8962. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  8963. // 合并anime_products和extra_products(extra_products优先,去重)
  8964. $anime_products = getProp($anime, 'extra_products');
  8965. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  8966. $ref_products = [];
  8967. foreach($anime_products as $item) {
  8968. $product_name = getProp($item, 'product_name');
  8969. $ref_products[$product_name] = $item;
  8970. }
  8971. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  8972. $extra_roles = []; // 从extra_products中提取的角色
  8973. $extra_scenes = []; // 从extra_products中提取的场景
  8974. $extra_props = []; // 从extra_products中提取的道具
  8975. if ($extra_products && is_array($extra_products)) {
  8976. foreach($extra_products as $item) {
  8977. $product = (int)getProp($item, 'product');
  8978. $product_name = getProp($item, 'product_name');
  8979. if ($product_name == '旁白') continue;
  8980. $pic_prompt = getProp($item, 'pic_prompt');
  8981. $ref_products[$product_name] = $item;
  8982. if ($product === 1) {
  8983. // 角色
  8984. $extra_roles[$product_name] = [
  8985. 'role' => $product_name,
  8986. 'pic_prompt' => $pic_prompt,
  8987. 'url' => getProp($item, 'url', ''),
  8988. ];
  8989. } elseif ($product === 2) {
  8990. // 场景
  8991. $extra_scenes[$product_name] = [
  8992. 'scene' => $product_name,
  8993. 'pic_prompt' => $pic_prompt,
  8994. 'url' => getProp($item, 'url', ''),
  8995. ];
  8996. } elseif ($product === 3) {
  8997. // 道具
  8998. $extra_props[$product_name] = [
  8999. 'prop' => $product_name,
  9000. 'pic_prompt' => $pic_prompt,
  9001. 'url' => getProp($item, 'url', ''),
  9002. ];
  9003. }
  9004. }
  9005. }
  9006. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  9007. $merged_roles = [];
  9008. foreach($ref_roles as $role) {
  9009. $role_name = getProp($role, 'role');
  9010. if (!isset($extra_roles[$role_name])) {
  9011. $merged_roles[$role_name] = $role;
  9012. }
  9013. }
  9014. // 添加extra_roles
  9015. foreach($extra_roles as $role_name => $role) {
  9016. $merged_roles[$role_name] = $role;
  9017. }
  9018. $ref_roles = array_values($merged_roles);
  9019. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  9020. $merged_scenes = [];
  9021. foreach($ref_scenes as $scene) {
  9022. $scene_name = getProp($scene, 'scene');
  9023. if (!isset($extra_scenes[$scene_name])) {
  9024. $merged_scenes[$scene_name] = $scene;
  9025. }
  9026. }
  9027. // 添加extra_scenes
  9028. foreach($extra_scenes as $scene_name => $scene) {
  9029. $merged_scenes[$scene_name] = $scene;
  9030. }
  9031. $ref_scenes = array_values($merged_scenes);
  9032. // 合并ref_props和extra_props(extra_props优先,去重)
  9033. $merged_props = [];
  9034. foreach($ref_props as $prop) {
  9035. $prop_name = getProp($prop, 'prop');
  9036. if (!isset($extra_props[$prop_name])) {
  9037. $merged_props[$prop_name] = $prop;
  9038. }
  9039. }
  9040. // 添加extra_props
  9041. foreach($extra_props as $prop_name => $prop) {
  9042. $merged_props[$prop_name] = $prop;
  9043. }
  9044. $ref_props = array_values($merged_props);
  9045. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  9046. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  9047. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  9048. // 构建强制主体、场景和道具提示词
  9049. $forced_roles_prompt = "";
  9050. $forced_scenes_prompt = "";
  9051. $forced_props_prompt = "";
  9052. if (!empty($extra_roles)) {
  9053. $forced_roles_list = "";
  9054. foreach($extra_roles as $role_name => $role) {
  9055. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  9056. }
  9057. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  9058. }
  9059. if (!empty($extra_scenes)) {
  9060. $forced_scenes_list = "";
  9061. foreach($extra_scenes as $scene_name => $scene) {
  9062. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  9063. }
  9064. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  9065. }
  9066. if (!empty($extra_props)) {
  9067. $forced_props_list = "";
  9068. foreach($extra_props as $prop_name => $prop) {
  9069. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  9070. }
  9071. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  9072. }
  9073. if ($anime_script_id) {
  9074. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  9075. }else if ($roles_content) {
  9076. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  9077. 主体范围:\n {$roles_content}\n
  9078. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  9079. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9080. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  9081. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9082. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  9083. }else {
  9084. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  9085. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9086. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  9087. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9088. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  9089. }
  9090. if ($anime_script_id) {
  9091. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  9092. }else if ($scenes_content) {
  9093. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  9094. 场景范围:\n {$scenes_content}\n
  9095. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  9096. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  9097. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9098. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  9099. }else {
  9100. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9101. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  9102. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9103. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  9104. }
  9105. if ($anime_script_id) {
  9106. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  9107. }else if ($props_content) {
  9108. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  9109. 道具范围:\n {$props_content}\n
  9110. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  9111. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  9112. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  9113. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  9114. }else {
  9115. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9116. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  9117. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  9118. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  9119. }
  9120. // 提取文件内容
  9121. if ($file) {
  9122. $uploaded_content = $this->extractFileContent($file);
  9123. if (!$uploaded_content) {
  9124. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  9125. }
  9126. } elseif ($script_id) {
  9127. $uploaded_content = $this->getContentByScriptId($script_id);
  9128. if (!$uploaded_content) {
  9129. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  9130. }
  9131. } elseif ($bid) {
  9132. $uploaded_content = $this->getContentByBid($bid);
  9133. if (!$uploaded_content) {
  9134. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  9135. }
  9136. } elseif ($content) {
  9137. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  9138. }
  9139. // elseif ($prompt) {
  9140. // $uploaded_content = filterContent($prompt);
  9141. // }
  9142. else {
  9143. $uploaded_content = '';
  9144. }
  9145. // 美术风格
  9146. $input_art_style = getProp($data, 'art_style');
  9147. if (!$input_art_style) {
  9148. $mappedArtStyle = getProp($anime, 'art_style');
  9149. }else {
  9150. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  9151. }
  9152. if (!$mappedArtStyle) {
  9153. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  9154. }else {
  9155. if (strstr($mappedArtStyle, '基础画风风格词')) {
  9156. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  9157. }else {
  9158. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  9159. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  9160. }
  9161. }
  9162. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  9163. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  9164. // 强制要求:
  9165. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9166. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9167. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9168. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  9169. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  9170. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  9171. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  9172. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  9173. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  9174. // 10.分镜要和场景列表、人物主体保持一致\n
  9175. // 普通要求:
  9176. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  9177. // {$role_demo}
  9178. // {$scene_demo}
  9179. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9180. // 4.1片段分割逻辑(优先级从高到低):
  9181. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9182. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9183. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9184. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9185. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9186. // - 片段数量格式为: 片段数量:8
  9187. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9188. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9189. // 4.3分镜结构:每个分镜包含以下字段:
  9190. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  9191. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  9192. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9193. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  9194. // - 运镜:场景+画面描述+运镜
  9195. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  9196. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9197. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  9198. // 5.$mappedArtStyle_prompt\n\n
  9199. // 示例格式:\n
  9200. // 第1集:隐形的守护者
  9201. // ###故事梗概
  9202. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9203. // ###美术风格
  9204. // 基础画风风格词:胡金铨武侠
  9205. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  9206. // ###主体列表
  9207. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9208. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  9209. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  9210. // ###场景列表
  9211. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  9212. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  9213. // ###分段剧本
  9214. // 片段数量:8
  9215. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9216. // ##片段1
  9217. // 时长:12s
  9218. // 分镜1
  9219. // 场景:边境小镇街道
  9220. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9221. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9222. // 配音台词:
  9223. // 背景音效:
  9224. // 分镜2
  9225. // 场景:悦来酒馆
  9226. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9227. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9228. // 配音台词:
  9229. // 背景音效:
  9230. // 分镜3
  9231. // 场景:悦来酒馆
  9232. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9233. // 运镜:从中景推向令牌特写。
  9234. // 配音台词:
  9235. // 背景音效:
  9236. // 分镜4
  9237. // 场景:悦来酒馆
  9238. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9239. // 运镜:极速推向酒水溅起的瞬间。
  9240. // 配音台词:
  9241. // 背景音效:
  9242. // 分镜5
  9243. // 镜头描述
  9244. // 场景:悦来酒馆
  9245. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9246. // 运镜:固定机位,利用倾斜构图制造压迫感。
  9247. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9248. // 背景音效:
  9249. // \n\n";
  9250. /*
  9251. // ====== 旧版 $demo(缓存优化前版本,动态数据内嵌在规则中间) ======
  9252. // 如需换回:删除下方新版 $demo,并把本块恢复为活动代码(去掉首尾注释标记)
  9253. // ===================================================================
  9254. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  9255. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  9256. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  9257. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  9258. 强制要求:
  9259. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  9260. 普通要求:
  9261. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  9262. {$role_demo}
  9263. {$scene_demo}
  9264. {$prop_demo}
  9265. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9266. 5.1片段分割逻辑(优先级从高到低):
  9267. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9268. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9269. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9270. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9271. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9272. - 片段数量格式为: 片段数量:8
  9273. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9274. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9275. 5.3分镜结构:每个分镜包含以下字段:
  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. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  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}
  9340. 示例格式:\n
  9341. 第1集:隐形的守护者
  9342. ###故事梗概
  9343. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9344. ###美术风格
  9345. 基础画风风格词:胡金铨武侠
  9346. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  9347. ###主体列表
  9348. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9349. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  9350. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  9351. ###场景列表
  9352. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  9353. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  9354. ###道具列表
  9355. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  9356. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  9357. ###分段剧本
  9358. 片段数量:8
  9359. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9360. ##片段1
  9361. 时长:12s
  9362. 分镜1
  9363. 出场角色:刀疤脸
  9364. 场景:边境小镇街道
  9365. 出场道具:酒杯-高脚杯
  9366. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9367. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9368. 配音台词:
  9369. 背景音效:
  9370. 分镜2
  9371. 出场角色:刀疤脸
  9372. 场景:悦来酒馆
  9373. 出场道具:酒杯-高脚杯
  9374. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9375. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9376. 配音台词:
  9377. 背景音效:
  9378. 分镜3
  9379. 出场角色:刀疤脸
  9380. 场景:悦来酒馆
  9381. 出场道具:酒杯-高脚杯
  9382. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9383. 运镜:从中景推向令牌特写。
  9384. 配音台词:
  9385. 背景音效:
  9386. 分镜4
  9387. 出场角色:刀疤脸
  9388. 场景:悦来酒馆
  9389. 出场道具:酒杯-高脚杯
  9390. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9391. 运镜:极速推向酒水溅起的瞬间。
  9392. 配音台词:
  9393. 背景音效:
  9394. 分镜5
  9395. 出场角色:刀疤脸
  9396. 场景:悦来酒馆
  9397. 出场道具:酒杯-高脚杯
  9398. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9399. 运镜:固定机位,利用倾斜构图制造压迫感。
  9400. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9401. 背景音效:
  9402. \n\n";
  9403. */
  9404. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  9405. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  9406. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  9407. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  9408. 强制要求:
  9409. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  9410. 普通要求:
  9411. 1.剧集标题必须与文档内容高度相关,剧集序号见文末【本次剧集信息】。
  9412. 2.<主体列表>的详细规则和可选范围见文末【本次生成数据-主体列表】。
  9413. 3.<场景列表>的详细规则和可选范围见文末【本次生成数据-场景列表】。
  9414. 4.<道具列表>的详细规则和可选范围见文末【本次生成数据-道具列表】。
  9415. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9416. 5.1片段分割逻辑(优先级从高到低):
  9417. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9418. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9419. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9420. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9421. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9422. - 片段数量格式为: 片段数量:8
  9423. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9424. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9425. 5.3分镜结构:每个分镜包含以下字段:
  9426. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  9427. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  9428. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9429. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9430. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9431. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9432. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9433. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9434. - 运镜:场景+画面描述+运镜
  9435. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  9436. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  9437. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9438. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  9439. 6.《情绪-视听语言映射表》:
  9440. 6.1 场景空间与时间心理学 (Scene & Temporality)
  9441. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9442. -----|---------|------------|----------------
  9443. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  9444. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  9445. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  9446. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  9447. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  9448. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9449. -----|---------|------------|----------------
  9450. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  9451. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  9452. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  9453. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  9454. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  9455. --------|---------|--------------|-------------
  9456. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  9457. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  9458. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  9459. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  9460. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  9461. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  9462. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  9463. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  9464. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  9465. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  9466. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  9467. -----|---------|------------|------------
  9468. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  9469. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  9470. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  9471. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  9472. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  9473. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  9474. --------|---------|--------------|----------
  9475. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  9476. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  9477. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  9478. 6.6 声音设计与潜意识影响 (Soundscape)
  9479. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  9480. -----|---------|------------|------------------
  9481. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  9482. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  9483. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  9484. 理论基石:
  9485. - The Five C's of Cinematography by Joseph V. Mascelli
  9486. - Film Art: An Introduction by David Bordwell
  9487. - Sight, Sound, Motion by Herbert Zettl
  9488. - Notes on the Cinematograph by Robert Bresson
  9489. \n\n
  9490. 7.美术风格要求见文末【本次生成数据-美术风格】。
  9491. 示例格式:\n
  9492. 第1集:隐形的守护者
  9493. ###故事梗概
  9494. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9495. ###美术风格
  9496. 基础画风风格词:胡金铨武侠
  9497. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  9498. ###主体列表
  9499. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9500. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  9501. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  9502. ###场景列表
  9503. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  9504. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  9505. ###道具列表
  9506. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  9507. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  9508. ###分段剧本
  9509. 片段数量:8
  9510. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9511. ##片段1
  9512. 时长:12s
  9513. 分镜1
  9514. 出场角色:刀疤脸
  9515. 场景:边境小镇街道
  9516. 出场道具:酒杯-高脚杯
  9517. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9518. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9519. 配音台词:
  9520. 背景音效:
  9521. 分镜2
  9522. 出场角色:刀疤脸
  9523. 场景:悦来酒馆
  9524. 出场道具:酒杯-高脚杯
  9525. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9526. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9527. 配音台词:
  9528. 背景音效:
  9529. 分镜3
  9530. 出场角色:刀疤脸
  9531. 场景:悦来酒馆
  9532. 出场道具:酒杯-高脚杯
  9533. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9534. 运镜:从中景推向令牌特写。
  9535. 配音台词:
  9536. 背景音效:
  9537. 分镜4
  9538. 出场角色:刀疤脸
  9539. 场景:悦来酒馆
  9540. 出场道具:酒杯-高脚杯
  9541. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9542. 运镜:极速推向酒水溅起的瞬间。
  9543. 配音台词:
  9544. 背景音效:
  9545. 分镜5
  9546. 出场角色:刀疤脸
  9547. 场景:悦来酒馆
  9548. 出场道具:酒杯-高脚杯
  9549. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9550. 运镜:固定机位,利用倾斜构图制造压迫感。
  9551. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9552. 背景音效:
  9553. \n\n本次生成数据(以上规则的动态数据均在此处,优先级等同对应编号规则):
  9554. 【本次剧集信息】剧集序号是{$episode_number}。
  9555. 【本次生成数据-主体列表】{$role_demo}
  9556. 【本次生成数据-场景列表】{$scene_demo}
  9557. 【本次生成数据-道具列表】{$prop_demo}
  9558. 【本次生成数据-美术风格】{$mappedArtStyle_prompt}
  9559. \n\n";
  9560. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  9561. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  9562. // $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  9563. $is_regenerate_version = true;
  9564. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  9565. $prompt = $origin_prompt;
  9566. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  9567. // 获取章节内容
  9568. $full_content = getProp($anime, 'content');
  9569. if ($uploaded_content) {
  9570. $full_content = $uploaded_content;
  9571. }
  9572. // 根据章节内容拆分章节
  9573. $chapters = splitContent($full_content);
  9574. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  9575. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  9576. $messages = [];
  9577. if ($prompt == '确认分镜大纲') {
  9578. // 暂时保留
  9579. $content = $chapter_content;
  9580. if ($is_single) $content = $full_content; // 单剧集使用全文
  9581. if (!$content) {
  9582. Utils::throwError('20003:章节内容无法获取,请确认');
  9583. }
  9584. $question = $is_single
  9585. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  9586. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  9587. // 构建消息
  9588. $messages[] =
  9589. [
  9590. 'role' => 'user',
  9591. 'content' => $question
  9592. ];
  9593. }else if ($prompt == '继续策划下一集') {
  9594. if ($is_single) {
  9595. Utils::throwError('20003:单剧集不支持继续策划下一集');
  9596. }
  9597. $content = $chapter_content;
  9598. if (!$content) {
  9599. Utils::throwError('20003:章节内容无法获取,请确认');
  9600. }
  9601. // 获取上一集最后记录
  9602. $prev_sequence = $episode_number - 1;
  9603. $messages = array_merge(
  9604. [
  9605. [
  9606. 'role' => 'system',
  9607. 'content' => $demo
  9608. ]
  9609. ],
  9610. $this->getEpisodeChatContent($anime_id, $prev_sequence, $content)
  9611. );
  9612. // 构建消息
  9613. $messages[] =
  9614. [
  9615. 'role' => 'user',
  9616. 'content' => "请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)"
  9617. ];
  9618. /*
  9619. // 旧版逻辑
  9620. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  9621. // 构建消息
  9622. $messages[] =
  9623. [
  9624. 'role' => 'user',
  9625. 'content' => $question
  9626. ];
  9627. */
  9628. // dd($messages);
  9629. }else {
  9630. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  9631. if (!$content) {
  9632. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  9633. }
  9634. if (!$content) {
  9635. Utils::throwError('20003:章节内容无法获取,请确认');
  9636. }
  9637. $messages = array_merge(
  9638. [
  9639. [
  9640. 'role' => 'system',
  9641. 'content' => $demo
  9642. ]
  9643. ],
  9644. $this->getEpisodeChatMessages($anime_id, $episode_number)
  9645. );
  9646. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  9647. $question = "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  9648. if ($origin_prompt) {
  9649. $question .= "本次修改要求如下:\n{$origin_prompt}";
  9650. }
  9651. // 将本集原文加入消息,供模型逐字摘录原文台词(修复重新生成时配音台词全部为"无"的问题)
  9652. $messages[] = [
  9653. 'role' => 'user',
  9654. 'content' => "本集剧情内容:\n\n{$content}\n"
  9655. ];
  9656. $messages[] =
  9657. [
  9658. 'role' => 'user',
  9659. 'content' => $question
  9660. ];
  9661. }
  9662. // 处理文本模型
  9663. $model = getProp($data, 'model');
  9664. if (!$model) {
  9665. // 用户没有输入,从anime表获取
  9666. $model = getProp($anime, 'model');
  9667. if (!$model) {
  9668. // anime表也没有,使用默认值
  9669. $model = 'deepseek-v4-pro';
  9670. }
  9671. }
  9672. // 验证模型是否在可用模型表中
  9673. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9674. $model = 'deepseek-v4-pro';
  9675. }
  9676. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  9677. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  9678. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  9679. if ($model === 'deepseek-chat') {
  9680. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  9681. $model = 'deepseek-v4-flash';
  9682. $thinkingMode = 'disabled';
  9683. } elseif ($model === 'deepseek-reasoner') {
  9684. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  9685. $model = 'deepseek-v4-flash';
  9686. $thinkingMode = 'enabled';
  9687. }
  9688. $post_data = [
  9689. 'model' => $model,
  9690. 'messages' => $messages,
  9691. // 'max_tokens' => 8192,
  9692. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9693. 'frequency_penalty' => 0,
  9694. 'presence_penalty' => 0,
  9695. 'response_format' => ['type' => 'text'],
  9696. 'thinking' => ['type' => $thinkingMode],
  9697. 'stream' => true // 启用流式输出
  9698. ];
  9699. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9700. // 根据模型类型选择调用方法
  9701. $fullContent = '';
  9702. $fullReasoningContent = '';
  9703. $usage = [];
  9704. try {
  9705. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9706. // DeepSeek 官方模型使用 DeepSeek API
  9707. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9708. } else if (in_array($model, $this->gpt_text_models)) {
  9709. // GPT-5.4 模型使用 TokenRouter API
  9710. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9711. } else if (in_array($model, $this->gemini_text_models)) {
  9712. // Gemini 模型使用 Gemini API
  9713. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9714. } else {
  9715. // 其他模型使用火山引擎API
  9716. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9717. }
  9718. // 验证返回值类型
  9719. if (!is_iterable($streamGenerator)) {
  9720. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  9721. dLog('deepseek')->error('chat流式生成器无效', [
  9722. 'generator_type' => $errorType,
  9723. 'model' => $model,
  9724. 'anime_id' => $anime_id,
  9725. 'episode_number' => $episode_number
  9726. ]);
  9727. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  9728. 'type' => $errorType,
  9729. 'model' => $model
  9730. ]);
  9731. yield [
  9732. 'type' => 'error',
  9733. 'episode' => [],
  9734. 'answer' => '',
  9735. 'reasoning' => '',
  9736. 'usage' => [],
  9737. 'error' => '接口返回数据异常,请重新请求'
  9738. ];
  9739. return;
  9740. }
  9741. // 处理流式输出
  9742. foreach ($streamGenerator as $chunk) {
  9743. if (isset($chunk['type'])) {
  9744. if ($chunk['type'] === 'done') {
  9745. // 最终结果
  9746. $fullContent = $chunk['full_content'];
  9747. $fullReasoningContent = $chunk['full_reasoning'];
  9748. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9749. } else {
  9750. // 逐块yield数据
  9751. yield $chunk;
  9752. }
  9753. }
  9754. }
  9755. } catch (\Exception $e) {
  9756. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  9757. 'model' => $model,
  9758. 'anime_id' => $anime_id,
  9759. 'episode_number' => $episode_number,
  9760. 'trace' => $e->getTraceAsString()
  9761. ]);
  9762. logDB('deepseek', 'error', 'chat流式处理失败', [
  9763. 'error' => $e->getMessage(),
  9764. 'model' => $model
  9765. ]);
  9766. yield [
  9767. 'type' => 'error',
  9768. 'episode' => [],
  9769. 'answer' => '',
  9770. 'reasoning' => '',
  9771. 'usage' => [],
  9772. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  9773. ];
  9774. return;
  9775. }
  9776. // 兼容模型偶发将整段正文包裹成 JSON 字符串返回
  9777. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9778. dLog('deepseek')->info('完整内容: '.$fullContent);
  9779. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  9780. // 处理完整内容并返回最终结果
  9781. $episode_arr = handleEpisodeContentForAce($fullContent);
  9782. dLog('deepseek')->info('解析内容: ', $episode_arr);
  9783. logDB('deepseek', 'info', '解析内容', $episode_arr);
  9784. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  9785. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  9786. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  9787. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  9788. // }
  9789. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  9790. $max_retries = 3;
  9791. $retry_count = 0;
  9792. $validation_failed = false;
  9793. $validation_error_msg = '';
  9794. // 验证生成的内容
  9795. if ($anime_script_id) {
  9796. // 检查是否有acts数据
  9797. if (empty($episode_arr['acts'])) {
  9798. $validation_failed = true;
  9799. $validation_error_msg = '未生成分镜剧本相关的内容';
  9800. } else {
  9801. // 校验主体列表:不能为空主体(旁白不算)
  9802. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9803. // 过滤掉"旁白"角色
  9804. $generated_roles = array_filter($generated_roles, function($role) {
  9805. return $role !== '旁白';
  9806. });
  9807. if (empty($generated_roles)) {
  9808. $validation_failed = true;
  9809. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9810. }
  9811. // 仅当存在强制主体设定时校验主体列表
  9812. if (!$validation_failed && !empty($extra_roles)) {
  9813. $expected_roles = array_keys($extra_roles);
  9814. // 找出生成的主体中不在预期列表中的主体
  9815. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9816. if (!empty($invalid_roles)) {
  9817. $validation_failed = true;
  9818. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9819. }
  9820. }
  9821. // 仅当存在强制场景设定时校验场景列表
  9822. if (!$validation_failed && !empty($extra_scenes)) {
  9823. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  9824. $expected_scenes = array_keys($extra_scenes);
  9825. // 找出生成的场景中不在预期列表中的场景
  9826. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9827. if (!empty($invalid_scenes)) {
  9828. $validation_failed = true;
  9829. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9830. }
  9831. }
  9832. // 仅当存在强制道具设定时校验道具列表
  9833. if (!$validation_failed && !empty($extra_props)) {
  9834. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9835. $expected_props = array_keys($extra_props);
  9836. // 找出生成的道具中不在预期列表中的道具
  9837. $invalid_props = array_diff($generated_props, $expected_props);
  9838. if (!empty($invalid_props)) {
  9839. $validation_failed = true;
  9840. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9841. }
  9842. }
  9843. }
  9844. } else {
  9845. // 如果没有anime_script_id,只检查是否有acts数据
  9846. if (empty($episode_arr['acts'])) {
  9847. $validation_failed = true;
  9848. $validation_error_msg = '未生成分镜剧本相关的内容';
  9849. } else {
  9850. // 校验主体列表:不能为空主体(旁白不算)
  9851. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9852. // 过滤掉"旁白"角色
  9853. $generated_roles = array_filter($generated_roles, function($role) {
  9854. return $role !== '旁白';
  9855. });
  9856. if (empty($generated_roles)) {
  9857. $validation_failed = true;
  9858. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9859. }
  9860. }
  9861. }
  9862. // 重试逻辑
  9863. while ($validation_failed && $retry_count < $max_retries) {
  9864. $retry_count++;
  9865. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  9866. 'reason' => $validation_error_msg,
  9867. 'anime_id' => $anime_id,
  9868. 'episode_number' => $episode_number
  9869. ]);
  9870. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  9871. 'reason' => $validation_error_msg,
  9872. 'anime_id' => $anime_id
  9873. ]);
  9874. // 发送流式重试提示
  9875. yield [
  9876. 'type' => 'retry',
  9877. 'retry_count' => $retry_count,
  9878. 'reason' => $validation_error_msg
  9879. ];
  9880. // 构建重试提示词
  9881. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  9882. if ($anime_script_id) {
  9883. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  9884. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9885. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  9886. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  9887. } else {
  9888. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9889. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  9890. }
  9891. // 添加重试消息到messages
  9892. $messages[] = [
  9893. 'role' => 'assistant',
  9894. 'content' => $fullContent
  9895. ];
  9896. $messages[] = [
  9897. 'role' => 'user',
  9898. 'content' => $retry_prompt
  9899. ];
  9900. // 更新post_data的messages
  9901. $post_data['messages'] = $messages;
  9902. // 重新调用API
  9903. try {
  9904. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9905. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9906. } else if (in_array($model, $this->gpt_text_models)) {
  9907. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9908. } else if (in_array($model, $this->gemini_text_models)) {
  9909. // Gemini 模型使用 Gemini API
  9910. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9911. } else {
  9912. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9913. }
  9914. // 处理流式输出
  9915. $fullContent = '';
  9916. $fullReasoningContent = '';
  9917. foreach ($streamGenerator as $chunk) {
  9918. if (isset($chunk['type'])) {
  9919. if ($chunk['type'] === 'done') {
  9920. $fullContent = $chunk['full_content'];
  9921. $fullReasoningContent = $chunk['full_reasoning'];
  9922. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9923. } else {
  9924. yield $chunk;
  9925. }
  9926. }
  9927. }
  9928. // 重新解析内容
  9929. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9930. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  9931. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  9932. $episode_arr = handleEpisodeContentForAce($fullContent);
  9933. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  9934. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  9935. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  9936. // }
  9937. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  9938. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  9939. // 重新验证
  9940. $validation_failed = false;
  9941. $validation_error_msg = '';
  9942. if ($anime_script_id) {
  9943. if (empty($episode_arr['acts'])) {
  9944. $validation_failed = true;
  9945. $validation_error_msg = '未生成分镜剧本相关的内容';
  9946. } else {
  9947. // 校验主体列表:不能为空主体(旁白不算)
  9948. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9949. // 过滤掉"旁白"角色
  9950. $generated_roles = array_filter($generated_roles, function($role) {
  9951. return $role !== '旁白';
  9952. });
  9953. if (empty($generated_roles)) {
  9954. $validation_failed = true;
  9955. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9956. }
  9957. // 仅当存在强制主体设定时校验主体列表
  9958. if (!$validation_failed && !empty($extra_roles)) {
  9959. $expected_roles = array_keys($extra_roles);
  9960. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9961. if (!empty($invalid_roles)) {
  9962. $validation_failed = true;
  9963. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9964. }
  9965. }
  9966. // 仅当存在强制场景设定时校验场景列表
  9967. if (!$validation_failed && !empty($extra_scenes)) {
  9968. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  9969. $expected_scenes = array_keys($extra_scenes);
  9970. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9971. if (!empty($invalid_scenes)) {
  9972. $validation_failed = true;
  9973. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9974. }
  9975. }
  9976. // 仅当存在强制道具设定时校验道具列表
  9977. if (!$validation_failed && !empty($extra_props)) {
  9978. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9979. $expected_props = array_keys($extra_props);
  9980. $invalid_props = array_diff($generated_props, $expected_props);
  9981. if (!empty($invalid_props)) {
  9982. $validation_failed = true;
  9983. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9984. }
  9985. }
  9986. }
  9987. } else {
  9988. if (empty($episode_arr['acts'])) {
  9989. $validation_failed = true;
  9990. $validation_error_msg = '未生成分镜剧本相关的内容';
  9991. } else {
  9992. // 校验主体列表:不能为空主体(旁白不算)
  9993. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9994. // 过滤掉"旁白"角色
  9995. $generated_roles = array_filter($generated_roles, function($role) {
  9996. return $role !== '旁白';
  9997. });
  9998. if (empty($generated_roles)) {
  9999. $validation_failed = true;
  10000. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  10001. }
  10002. }
  10003. }
  10004. } catch (\Exception $e) {
  10005. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  10006. 'trace' => $e->getTraceAsString()
  10007. ]);
  10008. break;
  10009. }
  10010. }
  10011. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  10012. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  10013. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  10014. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  10015. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  10016. if ($validation_failed && $retry_count >= $max_retries) {
  10017. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  10018. 'retry_count' => $retry_count,
  10019. 'last_error' => $validation_error_msg
  10020. ]);
  10021. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  10022. 'error' => $validation_error_msg,
  10023. 'anime_id' => $anime_id
  10024. ]);
  10025. $validation_failed = false;
  10026. $validation_error_msg = '';
  10027. }
  10028. // 如果重试后仍然失败
  10029. if ($validation_failed) {
  10030. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  10031. 'retry_count' => $retry_count,
  10032. 'last_error' => $validation_error_msg
  10033. ]);
  10034. try {
  10035. $now = date('Y-m-d H:i:s');
  10036. $records = [
  10037. [
  10038. 'uid' => $uid,
  10039. 'anime_id' => $anime_id,
  10040. 'sequence' => $episode_number,
  10041. 'role' => 'user',
  10042. 'content' => $prompt,
  10043. 'created_at' => $now,
  10044. 'updated_at' => $now
  10045. ],
  10046. [
  10047. 'uid' => $uid,
  10048. 'anime_id' => $anime_id,
  10049. 'sequence' => $episode_number,
  10050. 'role' => 'assistant',
  10051. 'content' => $fullContent,
  10052. 'created_at' => $now,
  10053. 'updated_at' => $now
  10054. ]
  10055. ];
  10056. DB::table('mp_anime_records')->insert($records);
  10057. } catch (\Exception $e) {
  10058. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  10059. }
  10060. yield [
  10061. 'type' => 'done',
  10062. 'episode' => [],
  10063. 'answer' => $fullContent,
  10064. 'reasoning' => $fullReasoningContent,
  10065. 'usage' => $usage,
  10066. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  10067. ];
  10068. return;
  10069. }
  10070. // 验证成功,记录日志
  10071. if ($retry_count > 0) {
  10072. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  10073. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  10074. }
  10075. // 老逻辑
  10076. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  10077. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  10078. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  10079. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  10080. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  10081. $existing_props = is_array($existing_props) ? $existing_props : [];
  10082. $now = date('Y-m-d H:i:s');
  10083. try {
  10084. DB::beginTransaction();
  10085. $saveResult = $this->saveEpisodeVersionData(
  10086. $anime_id,
  10087. $episode_number,
  10088. $episode_arr,
  10089. $existing_roles,
  10090. $existing_scenes,
  10091. $existing_props,
  10092. $current_episode,
  10093. $base_episode,
  10094. $is_regenerate_version,
  10095. $content,
  10096. $now,
  10097. $ref_products
  10098. );
  10099. $episode = $saveResult['episode'];
  10100. $episode_id = $saveResult['episode_id'];
  10101. $merged_roles = $saveResult['merged_roles'];
  10102. $merged_scenes = $saveResult['merged_scenes'];
  10103. $merged_props = $saveResult['merged_props'];
  10104. $record_content = $origin_prompt;
  10105. if ($uploaded_content !== '') {
  10106. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  10107. }
  10108. $records = [
  10109. [
  10110. 'uid' => $uid,
  10111. 'anime_id' => $anime_id,
  10112. 'role' => 'user',
  10113. 'content' => $record_content,
  10114. 'sequence' => $episode_number,
  10115. 'episode_id' => $episode_id,
  10116. 'created_at' => $now,
  10117. 'updated_at' => $now
  10118. ],
  10119. [
  10120. 'uid' => $uid,
  10121. 'anime_id' => $anime_id,
  10122. 'role' => 'assistant',
  10123. 'content' => $fullContent,
  10124. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  10125. 'sequence' => $episode_number,
  10126. 'episode_id' => $episode_id,
  10127. 'created_at' => $now,
  10128. 'updated_at' => $now
  10129. ]
  10130. ];
  10131. $boolen4 = DB::table('mp_anime_records')->insert($records);
  10132. if (!$boolen4) {
  10133. Utils::throwError('20003:对话记录保存失败');
  10134. }
  10135. // 保存模型到anime表
  10136. $update_anime_data = [
  10137. 'model' => $model,
  10138. 'updated_at' => $now
  10139. ];
  10140. if ($uploaded_content) {
  10141. $update_anime_data['content'] = $uploaded_content;
  10142. }
  10143. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  10144. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  10145. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  10146. 'anime_id' => $anime_id,
  10147. 'episode_number' => $episode_number,
  10148. 'model' => $model,
  10149. 'source' => 'chatForAce',
  10150. ]);
  10151. }catch (\Exception $e) {
  10152. DB::rollBack();
  10153. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  10154. yield [
  10155. 'type' => 'done',
  10156. 'answer' => $fullContent,
  10157. 'reasoning' => $fullReasoningContent,
  10158. 'usage' => $usage,
  10159. 'error' => $e->getMessage(),
  10160. ];
  10161. return;
  10162. }
  10163. DB::commit();
  10164. if ($is_global_generate_pics) {
  10165. // // 批量生成全局角色图片
  10166. // $this->batchSetGlobalRoleImg([
  10167. // 'anime_id' => $anime_id,
  10168. // ], true);
  10169. // // 批量生成全局场景图片
  10170. // $this->batchSetGlobalSceneImg([
  10171. // 'anime_id' => $anime_id,
  10172. // ], true);
  10173. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  10174. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  10175. }
  10176. $episode['episode_id'] = $episode_id;
  10177. $episode['roles'] = $merged_roles;
  10178. $episode['scenes'] = $merged_scenes;
  10179. $episode['props'] = $merged_props;
  10180. $episode['end_episode_sequence'] = $end_episode_sequence;
  10181. // 获取mp_animes表中的视频参数
  10182. $episode['video_params'] = [
  10183. 'video_model' => getProp($anime, 'video_model'),
  10184. 'video_resolution' => getProp($anime, 'video_resolution'),
  10185. 'ratio' => getProp($anime, 'video_ratio'),
  10186. ];
  10187. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  10188. yield [
  10189. 'type' => 'done',
  10190. 'episode' => $episode,
  10191. 'answer' => $fullContent,
  10192. 'reasoning' => $fullReasoningContent,
  10193. 'usage' => $usage
  10194. ];
  10195. }
  10196. /**
  10197. * chatForAce的非流式版本 - 用于定时任务
  10198. * 只获取最终 type=done 的数据,并验证必要字段
  10199. *
  10200. * @param array $data 请求数据
  10201. * @return array 生成结果
  10202. */
  10203. public function chatForAceNonStream($data) {
  10204. $finalResult = null;
  10205. // 调用流式方法,只保存 type=done 的数据
  10206. foreach ($this->chatForAce($data) as $chunk) {
  10207. // 只关注最终结果
  10208. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  10209. $finalResult = $chunk;
  10210. break; // 找到 done 就退出循环
  10211. }
  10212. }
  10213. // 验证最终结果
  10214. if (!$finalResult) {
  10215. return ['error' => '生成失败:未获取到最终结果'];
  10216. }
  10217. // 检查是否有错误
  10218. if (isset($finalResult['error']) && $finalResult['error']) {
  10219. return $finalResult;
  10220. }
  10221. // 验证必要字段
  10222. $episode = $finalResult['episode'] ?? [];
  10223. // 验证 roles(旁白不算主体,过滤后不能为空)
  10224. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  10225. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  10226. }
  10227. $nonNarratorRoles = array_filter(array_column($episode['roles'], 'role'), function($role) {
  10228. return $role !== '旁白';
  10229. });
  10230. if (empty($nonNarratorRoles)) {
  10231. return ['error' => '生成失败:主体列表(roles)为空或格式错误(旁白不算)'];
  10232. }
  10233. // 验证 scenes
  10234. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  10235. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  10236. }
  10237. // 验证 props(道具可以为空,但必须存在且为数组)
  10238. if (!isset($episode['props']) || !is_array($episode['props'])) {
  10239. $episode['props'] = [];
  10240. }
  10241. // 验证 acts(分镜剧本)
  10242. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  10243. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  10244. }
  10245. // 更新验证后的 episode 数据
  10246. $finalResult['episode'] = $episode;
  10247. // 记录验证成功日志
  10248. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  10249. 'roles_count' => count($episode['roles']),
  10250. 'scenes_count' => count($episode['scenes']),
  10251. 'props_count' => count($episode['props']),
  10252. 'acts_count' => count($episode['acts'])
  10253. ]);
  10254. return $finalResult;
  10255. }
  10256. /**
  10257. * 批量生成多个分集
  10258. *
  10259. * @param array $data 请求数据
  10260. * @return array 任务信息
  10261. */
  10262. public function batchGenerateEpisodes($data) {
  10263. $uid = Site::getUid();
  10264. $cpid = Site::getCpid();
  10265. $anime_id = getProp($data, 'anime_id');
  10266. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  10267. $start_episode_number = getProp($data, 'start_episode_number');
  10268. $end_episode_number = getProp($data, 'end_episode_number');
  10269. if (!$anime_id) {
  10270. Utils::throwError('20003:anime_id参数缺失');
  10271. }
  10272. if ($generate_episode_number < 1) {
  10273. Utils::throwError('20003:生成集数必须大于0');
  10274. }
  10275. // 获取动漫信息
  10276. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10277. if (!$anime) {
  10278. Utils::throwError('20003:该剧集不存在');
  10279. }
  10280. // 检查是否是全能模式
  10281. if ((int)getProp($anime, 'ace_mode') !== 1) {
  10282. Utils::throwError('20003:只有全能模式才支持批量生成');
  10283. }
  10284. // 检查是否是多剧集模式
  10285. if ((int)getProp($anime, 'is_multi') !== 1) {
  10286. Utils::throwError('20003:单剧集不支持批量生成');
  10287. }
  10288. // 指定起始/结束剧集序号时的校验
  10289. $hasSpecifiedRange = ($start_episode_number !== null && $start_episode_number !== '')
  10290. || ($end_episode_number !== null && $end_episode_number !== '');
  10291. if ($hasSpecifiedRange) {
  10292. if ($start_episode_number === null || $start_episode_number === ''
  10293. || $end_episode_number === null || $end_episode_number === '') {
  10294. Utils::throwError('20003:起始剧集序号和结束剧集序号必须同时提供');
  10295. }
  10296. $start_episode_number = (int)$start_episode_number;
  10297. $end_episode_number = (int)$end_episode_number;
  10298. if ($start_episode_number < 1 || $end_episode_number < $start_episode_number) {
  10299. Utils::throwError('20003:剧集序号范围错误,结束剧集序号不能小于起始剧集序号');
  10300. }
  10301. $startEpisodeNumber = $start_episode_number;
  10302. $endEpisodeNumber = $end_episode_number;
  10303. } else {
  10304. // 未指定范围时,以 generate_episode_number 判断要生成的集数,从当前已生成的最大集数的下一集开始
  10305. $currentMaxEpisode = DB::table('mp_anime_episodes')
  10306. ->where('anime_id', $anime_id)
  10307. ->where('is_default', 1)
  10308. ->max('episode_number');
  10309. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  10310. // 确定起始集数
  10311. $startEpisodeNumber = $currentMaxEpisode + 1;
  10312. // 计算结束集数
  10313. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  10314. }
  10315. // 本次实际生成的集数
  10316. $totalEpisodeCount = $endEpisodeNumber - $startEpisodeNumber + 1;
  10317. // 检查是否超过总集数限制
  10318. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  10319. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  10320. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  10321. }
  10322. // 创建任务前验重:批量任务表与剧集表中是否已存在范围内的剧集序号
  10323. $duplicatedBatchEpisodes = DB::table('mp_batch_episode_generation_details')
  10324. ->where('anime_id', $anime_id)
  10325. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  10326. ->pluck('episode_number')
  10327. ->unique()
  10328. ->sort()
  10329. ->values()
  10330. ->toArray();
  10331. $duplicatedAnimeEpisodes = DB::table('mp_anime_episodes')
  10332. ->where('anime_id', $anime_id)
  10333. ->where('is_default', 1)
  10334. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  10335. ->pluck('episode_number')
  10336. ->unique()
  10337. ->sort()
  10338. ->values()
  10339. ->toArray();
  10340. if (!empty($duplicatedBatchEpisodes) || !empty($duplicatedAnimeEpisodes)) {
  10341. $duplicateMessages = [];
  10342. if (!empty($duplicatedBatchEpisodes)) {
  10343. $duplicateMessages[] = '批量生成任务中已存在第' . implode('、', $duplicatedBatchEpisodes) . '集';
  10344. }
  10345. if (!empty($duplicatedAnimeEpisodes)) {
  10346. $duplicateMessages[] = '剧集中已存在第' . implode('、', $duplicatedAnimeEpisodes) . '集';
  10347. }
  10348. Utils::throwError('20003:' . implode(';', $duplicateMessages) . ',请勿重复创建');
  10349. }
  10350. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  10351. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  10352. ->where('anime_id', $anime_id)
  10353. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  10354. ->whereIn('status', ['pending', 'processing', 'completed'])
  10355. ->count();
  10356. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  10357. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  10358. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  10359. if ($needEpisodeCount > 0) {
  10360. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints() * $needEpisodeCount, $uid);
  10361. }
  10362. $now = date('Y-m-d H:i:s');
  10363. $createdTasks = [];
  10364. $skippedTasks = [];
  10365. // 为每一集创建详情记录
  10366. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  10367. // 检查是否已有该集的任务记录
  10368. $existingTask = DB::table('mp_batch_episode_generation_details')
  10369. ->where('anime_id', $anime_id)
  10370. ->where('episode_number', $episodeNumber)
  10371. ->first();
  10372. if ($existingTask) {
  10373. // 如果已存在且未完成,跳过
  10374. if (in_array($existingTask->status, ['pending', 'processing'])) {
  10375. $skippedTasks[] = $episodeNumber;
  10376. continue;
  10377. }
  10378. // 如果是失败状态,可以重新创建(删除旧记录)
  10379. if ($existingTask->status === 'failed') {
  10380. DB::table('mp_batch_episode_generation_details')
  10381. ->where('id', $existingTask->id)
  10382. ->delete();
  10383. }
  10384. // 如果是已完成状态,也跳过
  10385. if ($existingTask->status === 'completed') {
  10386. $skippedTasks[] = $episodeNumber;
  10387. continue;
  10388. }
  10389. }
  10390. // 准备任务数据
  10391. $taskData = [
  10392. 'anime_id' => $anime_id,
  10393. 'uid' => $uid,
  10394. 'cpid' => $cpid,
  10395. 'episode_number' => $episodeNumber,
  10396. 'status' => 'pending',
  10397. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  10398. 'retry_count' => 0,
  10399. 'created_at' => $now,
  10400. 'updated_at' => $now
  10401. ];
  10402. // 创建任务记录
  10403. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  10404. if ($taskId) {
  10405. $createdTasks[] = $episodeNumber;
  10406. }
  10407. }
  10408. if (empty($createdTasks)) {
  10409. if (!empty($skippedTasks)) {
  10410. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  10411. } else {
  10412. Utils::throwError('20003:创建批量生成任务失败');
  10413. }
  10414. }
  10415. // 创建/复用任务中心记录(按入参+type验重,避免重复任务)
  10416. $taskCenterId = $this->createBatchGenerateEpisodesTaskCenter(
  10417. $uid,
  10418. $cpid,
  10419. $anime_id,
  10420. $generate_episode_number,
  10421. $startEpisodeNumber,
  10422. $endEpisodeNumber
  10423. );
  10424. return [
  10425. 'anime_id' => $anime_id,
  10426. 'start_episode' => $startEpisodeNumber,
  10427. 'end_episode' => $endEpisodeNumber,
  10428. 'total_episodes' => $totalEpisodeCount,
  10429. 'created_episodes' => $createdTasks,
  10430. 'skipped_episodes' => $skippedTasks,
  10431. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$totalEpisodeCount}集。" .
  10432. "已创建: " . implode(',', $createdTasks) .
  10433. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : ""),
  10434. 'task_center_id' => $taskCenterId
  10435. ];
  10436. }
  10437. /**
  10438. * 根据入参创建或复用批量生成分集的任务中心记录
  10439. *
  10440. * 以入参(anime_id、generate_episode_number)计算 md5 存入 params_md5 字段用于验重:
  10441. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  10442. * 避免生成重复任务;唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复。
  10443. *
  10444. * @param int|string $uid
  10445. * @param int|string $cpid
  10446. * @param int|string $anime_id
  10447. * @param int $generate_episode_number
  10448. * @param int $startEpisodeNumber
  10449. * @param int $endEpisodeNumber
  10450. * @return int 任务中心ID
  10451. */
  10452. private function createBatchGenerateEpisodesTaskCenter($uid, $cpid, $anime_id, $generate_episode_number, $startEpisodeNumber, $endEpisodeNumber) {
  10453. $params = [
  10454. 'anime_id' => (int)$anime_id,
  10455. 'generate_episode_number' => (int)$generate_episode_number,
  10456. 'start_episode' => (int)$startEpisodeNumber,
  10457. 'end_episode' => (int)$endEpisodeNumber,
  10458. ];
  10459. // 验重键:入参 + 生成范围(anime_id + generate_episode_number + start/end)+ task_type
  10460. $paramsMd5 = md5(json_encode([
  10461. 'anime_id' => (int)$anime_id,
  10462. 'generate_episode_number' => (int)$generate_episode_number,
  10463. 'start_episode' => (int)$startEpisodeNumber,
  10464. 'end_episode' => (int)$endEpisodeNumber,
  10465. ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  10466. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  10467. $existing = DB::table('mp_task_center')
  10468. ->where('uid', (int)$uid)
  10469. ->where('cpid', (int)$cpid)
  10470. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10471. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  10472. ->where('params_md5', $paramsMd5)
  10473. ->orderBy('id', 'desc')
  10474. ->first();
  10475. if ($existing) {
  10476. dLog('deepseek')->info('复用批量生成分集任务中心记录,避免重复任务', [
  10477. 'anime_id' => $anime_id,
  10478. 'task_center_id' => $existing->id,
  10479. 'params_md5' => $paramsMd5,
  10480. ]);
  10481. return (int)$existing->id;
  10482. }
  10483. $now = date('Y-m-d H:i:s');
  10484. DB::table('mp_task_center')->insertOrIgnore([
  10485. 'uid' => (int)$uid,
  10486. 'cpid' => (int)$cpid,
  10487. 'task_type' => MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES,
  10488. 'title' => '批量生成分集',
  10489. 'ref_task_id' => 0,
  10490. 'status' => MpTaskCenter::STATUS_PROCESSING,
  10491. 'result' => null,
  10492. 'error_message' => null,
  10493. 'prompt' => null,
  10494. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  10495. 'params_md5' => $paramsMd5,
  10496. 'created_at' => $now,
  10497. 'updated_at' => $now,
  10498. ]);
  10499. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  10500. $taskId = (int)DB::table('mp_task_center')
  10501. ->where('uid', (int)$uid)
  10502. ->where('cpid', (int)$cpid)
  10503. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10504. ->where('params_md5', $paramsMd5)
  10505. ->orderBy('id', 'desc')
  10506. ->value('id');
  10507. dLog('deepseek')->info('创建批量生成分集任务中心记录', [
  10508. 'anime_id' => $anime_id,
  10509. 'task_center_id' => $taskId,
  10510. 'params_md5' => $paramsMd5,
  10511. ]);
  10512. return $taskId;
  10513. }
  10514. /**
  10515. * 批量生成分集全部结束后,更新任务中心记录的状态和结果
  10516. *
  10517. * 由批量生成 worker 子进程在退出前调用。分集详情任务的状态会在多处更新
  10518. * (completed/failed/pending/processing),这里只在所有详情任务均已结束时
  10519. * 统一汇总更新,避免在每个更新点重复处理。
  10520. *
  10521. * @param int|string $animeId
  10522. * @return int 更新的任务中心记录数
  10523. */
  10524. public function finishBatchGenerateEpisodesTaskCenters($animeId) {
  10525. $animeId = (int)$animeId;
  10526. $updated = 0;
  10527. // 该 anime 是否还有未结束的详情任务
  10528. $hasUnfinished = DB::table('mp_batch_episode_generation_details')
  10529. ->where('anime_id', $animeId)
  10530. ->whereIn('status', ['pending', 'processing'])
  10531. ->exists();
  10532. // 扫描该 anime 相关的未完成任务中心记录
  10533. $tasks = DB::table('mp_task_center')
  10534. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10535. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  10536. ->orderBy('id', 'desc')
  10537. ->limit(500)
  10538. ->get();
  10539. if ($hasUnfinished && !$tasks) {
  10540. return 0;
  10541. }
  10542. foreach ($tasks as $task) {
  10543. try {
  10544. $taskParams = json_decode((string)$task->params, true);
  10545. if (!is_array($taskParams) || (int)($taskParams['anime_id'] ?? 0) !== $animeId) {
  10546. continue;
  10547. }
  10548. $startEpisode = (int)($taskParams['start_episode'] ?? 0);
  10549. $endEpisode = (int)($taskParams['end_episode'] ?? 0);
  10550. if ($startEpisode < 1 || $endEpisode < $startEpisode) {
  10551. continue;
  10552. }
  10553. $details = DB::table('mp_batch_episode_generation_details')
  10554. ->where('anime_id', $animeId)
  10555. ->whereBetween('episode_number', [$startEpisode, $endEpisode])
  10556. ->get();
  10557. // 该批次范围内存在缺失记录,等待下一次检查
  10558. if ($details->isEmpty() || $details->count() < ($endEpisode - $startEpisode + 1)) {
  10559. continue;
  10560. }
  10561. $completedEpisodes = [];
  10562. $failedEpisodes = [];
  10563. $allFinished = true;
  10564. foreach ($details as $detail) {
  10565. if ($detail->status === 'completed') {
  10566. $completedEpisodes[] = $detail->episode_number;
  10567. } elseif ($detail->status === 'failed') {
  10568. $failedEpisodes[] = [
  10569. 'episode_number' => $detail->episode_number,
  10570. 'error_message' => $detail->error_message ?? '',
  10571. ];
  10572. } else {
  10573. // pending/processing(防御处理,正常不会走到)
  10574. $allFinished = false;
  10575. break;
  10576. }
  10577. }
  10578. if (!$allFinished) {
  10579. continue;
  10580. }
  10581. $result = json_encode([
  10582. 'anime_id' => $animeId,
  10583. 'start_episode' => $startEpisode,
  10584. 'end_episode' => $endEpisode,
  10585. 'total_episodes' => count($details),
  10586. 'completed_count' => count($completedEpisodes),
  10587. 'failed_count' => count($failedEpisodes),
  10588. 'completed_episodes' => $completedEpisodes,
  10589. 'failed_episodes' => $failedEpisodes,
  10590. ], JSON_UNESCAPED_UNICODE);
  10591. DB::table('mp_task_center')
  10592. ->where('id', $task->id)
  10593. ->update([
  10594. 'status' => !empty($failedEpisodes) ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  10595. 'result' => $result,
  10596. 'error_message' => !empty($failedEpisodes) ? ('有 ' . count($failedEpisodes) . ' 集生成失败') : null,
  10597. 'updated_at' => date('Y-m-d H:i:s'),
  10598. ]);
  10599. $updated++;
  10600. dLog('command')->info('批量生成分集任务已完成,更新任务中心', [
  10601. 'task_center_id' => $task->id,
  10602. 'anime_id' => $animeId,
  10603. 'start_episode' => $startEpisode,
  10604. 'end_episode' => $endEpisode,
  10605. ]);
  10606. } catch (\Exception $e) {
  10607. dLog('command')->error('更新批量生成分集任务中心异常', [
  10608. 'task_center_id' => $task->id,
  10609. 'anime_id' => $animeId,
  10610. 'error' => $e->getMessage(),
  10611. ]);
  10612. }
  10613. }
  10614. return $updated;
  10615. }
  10616. /**
  10617. * 获取批量生成任务状态
  10618. *
  10619. * @param array $data 请求数据
  10620. * @return array 任务状态信息
  10621. */
  10622. public function getBatchGenerationTaskStatus($data) {
  10623. $anime_id = getProp($data, 'anime_id');
  10624. if (!$anime_id) {
  10625. Utils::throwError('20003:anime_id参数缺失');
  10626. }
  10627. // 获取该anime的所有任务
  10628. $tasks = DB::table('mp_batch_episode_generation_details')
  10629. ->where('anime_id', $anime_id)
  10630. ->orderBy('episode_number')
  10631. ->get()
  10632. ->map(function($item) {
  10633. return [
  10634. 'id' => $item->id,
  10635. 'episode_number' => $item->episode_number,
  10636. 'status' => $item->status,
  10637. 'error_message' => $item->error_message,
  10638. 'retry_count' => $item->retry_count,
  10639. 'created_at' => $item->created_at,
  10640. 'updated_at' => $item->updated_at,
  10641. 'completed_at' => $item->completed_at
  10642. ];
  10643. })
  10644. ->toArray();
  10645. if (empty($tasks)) {
  10646. Utils::throwError('20003:该剧集没有批量生成任务');
  10647. }
  10648. // 统计各状态数量
  10649. $totalCount = count($tasks);
  10650. $pendingCount = 0;
  10651. $processingCount = 0;
  10652. $completedCount = 0;
  10653. $failedCount = 0;
  10654. $failed_episodes = [];
  10655. foreach ($tasks as $task) {
  10656. switch ($task['status']) {
  10657. case 'pending':
  10658. $pendingCount++;
  10659. break;
  10660. case 'processing':
  10661. $processingCount++;
  10662. break;
  10663. case 'completed':
  10664. $completedCount++;
  10665. break;
  10666. case 'failed':
  10667. $failedCount++;
  10668. // 组装失败分集对象(新对象):分集序号、错误原因
  10669. $failed_episodes[] = [
  10670. 'episode_number' => $task['episode_number'],
  10671. 'error_message' => $task['error_message'] ?? ''
  10672. ];
  10673. break;
  10674. }
  10675. }
  10676. // 计算进度百分比
  10677. $progress = 0;
  10678. if ($totalCount > 0) {
  10679. $progress = round(($completedCount / $totalCount) * 100, 2);
  10680. }
  10681. // 判断整体状态
  10682. $overallStatus = 'processing';
  10683. if ($completedCount === $totalCount) {
  10684. $overallStatus = 'completed';
  10685. } elseif ($pendingCount === $totalCount) {
  10686. $overallStatus = 'pending';
  10687. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  10688. $overallStatus = 'failed';
  10689. }
  10690. return [
  10691. 'anime_id' => $anime_id,
  10692. 'total_episodes' => $totalCount,
  10693. 'pending_count' => $pendingCount,
  10694. 'processing_count' => $processingCount,
  10695. 'completed_count' => $completedCount,
  10696. 'failed_count' => $failedCount,
  10697. 'progress' => $progress,
  10698. 'overall_status' => $overallStatus,
  10699. 'failed_episodes' => $failed_episodes,
  10700. 'tasks' => $tasks
  10701. ];
  10702. }
  10703. /**
  10704. * 将生成内容中不在强制列表中的资源合并进强制列表
  10705. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  10706. *
  10707. * @param array $generated 生成内容中的资源列表
  10708. * @param array $forced 强制资源列表(key为资源名称)
  10709. * @param string $type 资源类型:role、scene、prop
  10710. * @return array
  10711. */
  10712. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  10713. {
  10714. foreach ($generated as $item) {
  10715. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  10716. if ($name === null || $name === '') {
  10717. continue;
  10718. }
  10719. if ($name === '旁白') {
  10720. continue;
  10721. }
  10722. if (!isset($forced[$name])) {
  10723. $forced[$name] = $item;
  10724. }
  10725. }
  10726. return $forced;
  10727. }
  10728. /**
  10729. * 智能匹配并替换主体和场景名称
  10730. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  10731. *
  10732. * @param array $episode_arr 解析后的剧集数据
  10733. * @param array $extra_roles 强制主体设定(key为主体名称)
  10734. * @param array $extra_scenes 强制场景设定(key为场景名称)
  10735. * @return array 替换后的剧集数据
  10736. */
  10737. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  10738. $replaced_count = 0;
  10739. // 1. 处理主体列表
  10740. if (!empty($episode_arr['roles'])) {
  10741. foreach ($episode_arr['roles'] as &$role) {
  10742. $generated_role_name = $role['role'] ?? '';
  10743. // 跳过旁白
  10744. if ($generated_role_name === '旁白') {
  10745. continue;
  10746. }
  10747. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  10748. if (!isset($extra_roles[$generated_role_name])) {
  10749. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  10750. if ($matched_role) {
  10751. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  10752. $role['role'] = $matched_role;
  10753. $replaced_count++;
  10754. }
  10755. }
  10756. }
  10757. }
  10758. // 2. 处理场景列表
  10759. if (!empty($episode_arr['scenes'])) {
  10760. foreach ($episode_arr['scenes'] as &$scene) {
  10761. $generated_scene_name = $scene['scene'] ?? '';
  10762. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  10763. if (!isset($extra_scenes[$generated_scene_name])) {
  10764. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  10765. if ($matched_scene) {
  10766. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  10767. $scene['scene'] = $matched_scene;
  10768. $replaced_count++;
  10769. }
  10770. }
  10771. }
  10772. }
  10773. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  10774. if (!empty($episode_arr['acts'])) {
  10775. foreach ($episode_arr['acts'] as &$act) {
  10776. if (!empty($act['segments'])) {
  10777. foreach ($act['segments'] as &$segment) {
  10778. if (!empty($segment['segment_content'])) {
  10779. $original_content = $segment['segment_content'];
  10780. $replaced_content = $original_content;
  10781. // 替换场景名 - 在文本中查找并替换
  10782. foreach (array_keys($extra_scenes) as $full_scene_name) {
  10783. // 尝试找到可能的短名称
  10784. $potential_short_names = [];
  10785. // 提取场景名的主要部分(冒号之前)
  10786. if (mb_strpos($full_scene_name, ':') !== false) {
  10787. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  10788. $potential_short_names[] = $short_name;
  10789. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  10790. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  10791. $potential_short_names[] = $short_name;
  10792. }
  10793. // 替换场景字段中的短名称
  10794. foreach ($potential_short_names as $short_name) {
  10795. if ($short_name !== $full_scene_name) {
  10796. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  10797. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  10798. if ($new_content !== $replaced_content) {
  10799. $replaced_content = $new_content;
  10800. $replaced_count++;
  10801. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  10802. }
  10803. }
  10804. }
  10805. }
  10806. // 替换配音角色名(跳过旁白)
  10807. foreach (array_keys($extra_roles) as $full_role_name) {
  10808. if ($full_role_name === '旁白') {
  10809. continue;
  10810. }
  10811. // 尝试找到可能的短名称
  10812. $potential_short_names = [];
  10813. // 提取角色名的主要部分(短横线之前)
  10814. if (mb_strpos($full_role_name, '-') !== false) {
  10815. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  10816. $potential_short_names[] = $short_name;
  10817. }
  10818. // 替换配音台词中的短名称
  10819. foreach ($potential_short_names as $short_name) {
  10820. if ($short_name !== $full_role_name) {
  10821. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  10822. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  10823. if ($new_content !== $replaced_content) {
  10824. $replaced_content = $new_content;
  10825. $replaced_count++;
  10826. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  10827. }
  10828. }
  10829. }
  10830. }
  10831. // 如果有替换,更新segment_content
  10832. if ($replaced_content !== $original_content) {
  10833. $segment['segment_content'] = $replaced_content;
  10834. }
  10835. }
  10836. }
  10837. }
  10838. }
  10839. }
  10840. if ($replaced_count > 0) {
  10841. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  10842. 'replaced_count' => $replaced_count
  10843. ]);
  10844. }
  10845. return $episode_arr;
  10846. }
  10847. /**
  10848. * 查找匹配的名称
  10849. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  10850. *
  10851. * @param string $generated_name 生成的名称
  10852. * @param array $expected_names 预期的名称列表
  10853. * @return string|null 匹配到的名称,如果没有匹配则返回null
  10854. */
  10855. private function findMatchingName($generated_name, $expected_names) {
  10856. if (empty($generated_name)) {
  10857. return null;
  10858. }
  10859. // 尝试精确匹配
  10860. if (in_array($generated_name, $expected_names)) {
  10861. return $generated_name;
  10862. }
  10863. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  10864. foreach ($expected_names as $expected_name) {
  10865. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  10866. if (mb_strpos($expected_name, $generated_name) === 0) {
  10867. return $expected_name;
  10868. }
  10869. }
  10870. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  10871. // 这样可以处理一些变体,但优先级较低
  10872. foreach ($expected_names as $expected_name) {
  10873. if (mb_strpos($expected_name, $generated_name) !== false) {
  10874. return $expected_name;
  10875. }
  10876. }
  10877. return null;
  10878. }
  10879. /**
  10880. * 重新生成分段剧本
  10881. * @param array $data 包含以下字段:
  10882. * - prompt: string|null 用户修改要求(可选)
  10883. * - template_id: int|null 提示词模板ID(可选)
  10884. * - act_id: int|null 单个片段ID(与episode_id二选一)
  10885. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  10886. * @return array 返回生成结果
  10887. */
  10888. public function regenerateSegmentScript($data) {
  10889. $uid = Site::getUid();
  10890. $prompt = trim((string)getProp($data, 'prompt', ''));
  10891. $template_id = getProp($data, 'template_id', 0);
  10892. $act_id = getProp($data, 'act_id', 0);
  10893. $episode_id = getProp($data, 'episode_id', 0);
  10894. // 验证:prompt和template_id至少提供一个
  10895. if (empty($prompt) && empty($template_id)) {
  10896. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  10897. }
  10898. // 验证:act_id和episode_id二选一
  10899. if (empty($act_id) && empty($episode_id)) {
  10900. Utils::throwError('20003:请提供片段ID或剧集ID');
  10901. }
  10902. if (!empty($act_id) && !empty($episode_id)) {
  10903. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  10904. }
  10905. // 积分余额预检(仅剧集ID模式收费)
  10906. if (!empty($episode_id)) {
  10907. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  10908. }
  10909. // 如果提供了template_id,获取模板提示词
  10910. $template_prompt = '';
  10911. if ($template_id > 0) {
  10912. $template = DB::table('mp_prompt_templates')
  10913. ->where('id', $template_id)
  10914. ->where('is_deleted', 0)
  10915. ->first();
  10916. if (!$template) {
  10917. Utils::throwError('20003:提示词模板不存在或已删除');
  10918. }
  10919. $template_prompt = $template->template_prompt ?? '';
  10920. }
  10921. // 合并用户提示词和模板提示词
  10922. $final_prompt = '';
  10923. if (!empty($template_prompt)) {
  10924. $final_prompt = $template_prompt;
  10925. if (!empty($prompt)) {
  10926. $final_prompt .= "\n\n补充要求:" . $prompt;
  10927. }
  10928. } else {
  10929. $final_prompt = $prompt;
  10930. }
  10931. // 获取需要重新生成的内容参考
  10932. $reference_content = '';
  10933. $target_episode_id = 0;
  10934. $target_anime_id = 0;
  10935. $target_episode_number = 0;
  10936. if ($act_id > 0) {
  10937. // 单个片段模式:获取该片段的内容
  10938. $segment = DB::table('mp_episode_segments')
  10939. ->where('id', $act_id)
  10940. ->first();
  10941. if (!$segment) {
  10942. Utils::throwError('20003:片段不存在');
  10943. }
  10944. $target_episode_id = $segment->episode_id;
  10945. $target_anime_id = $segment->anime_id;
  10946. $target_episode_number = $segment->episode_number;
  10947. $reference_content = $segment->act_content ?? '';
  10948. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  10949. } else {
  10950. // 整个剧集模式:获取所有片段的内容
  10951. $segments = DB::table('mp_episode_segments')
  10952. ->where('episode_id', $episode_id)
  10953. ->orderBy('act_number')
  10954. ->get();
  10955. if ($segments->isEmpty()) {
  10956. Utils::throwError('20003:该剧集没有片段数据');
  10957. }
  10958. $target_episode_id = $episode_id;
  10959. $target_anime_id = $segments[0]->anime_id;
  10960. $target_episode_number = $segments[0]->episode_number;
  10961. // 拼接所有片段内容,保留格式用于AI理解
  10962. $act_contents = [];
  10963. foreach ($segments as $seg) {
  10964. $act_number = $seg->act_number;
  10965. $act_content = $seg->act_content ?? '';
  10966. if (!empty($act_content)) {
  10967. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  10968. }
  10969. }
  10970. $reference_content = implode("\n\n", $act_contents);
  10971. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  10972. if ($episode_content) {
  10973. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  10974. }else {
  10975. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  10976. }
  10977. }
  10978. if (empty($reference_content)) {
  10979. Utils::throwError('20003:没有可参考的片段内容');
  10980. }
  10981. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  10982. $episode = DB::table('mp_anime_episodes')
  10983. ->where('id', $target_episode_id)
  10984. ->first();
  10985. if (!$episode) {
  10986. Utils::throwError('20003:剧集不存在');
  10987. }
  10988. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  10989. $anime_script_id = getProp($anime, 'script_id');
  10990. $intro = $episode->intro ?? '';
  10991. $art_style = $episode->art_style ?? '';
  10992. $roles = json_decode($episode->roles ?? '[]', true);
  10993. $scenes = json_decode($episode->scenes ?? '[]', true);
  10994. $props = json_decode($episode->props ?? '[]', true);
  10995. // 构建提示词中的主体列表和场景列表参考
  10996. $roles_ref = '';
  10997. if (!empty($roles) && is_array($roles)) {
  10998. $roles_list = [];
  10999. foreach ($roles as $role) {
  11000. $role_name = getProp($role, 'role', '');
  11001. $role_desc = getProp($role, 'description', '');
  11002. $pic_prompt = getProp($role, 'pic_prompt', '');
  11003. $voice_prompt = getProp($role, 'voice_prompt', '');
  11004. if (!empty($role_name)) {
  11005. $role_line = $role_name;
  11006. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  11007. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  11008. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  11009. $roles_list[] = $role_line;
  11010. }
  11011. }
  11012. if (!empty($roles_list)) {
  11013. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  11014. }
  11015. }
  11016. $scenes_ref = '';
  11017. if (!empty($scenes) && is_array($scenes)) {
  11018. $scenes_list = [];
  11019. foreach ($scenes as $scene) {
  11020. $scene_name = getProp($scene, 'scene', '');
  11021. $scene_desc = getProp($scene, 'description', '');
  11022. $pic_prompt = getProp($scene, 'pic_prompt', '');
  11023. if (!empty($scene_name)) {
  11024. $scene_line = $scene_name;
  11025. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  11026. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  11027. $scenes_list[] = $scene_line;
  11028. }
  11029. }
  11030. if (!empty($scenes_list)) {
  11031. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  11032. }
  11033. }
  11034. $props_ref = '';
  11035. if (!empty($props) && is_array($props)) {
  11036. $props_list = [];
  11037. foreach ($props as $prop) {
  11038. $prop_name = getProp($prop, 'prop', '');
  11039. $prop_desc = getProp($prop, 'description', '');
  11040. $pic_prompt = getProp($prop, 'pic_prompt', '');
  11041. if (!empty($prop_name)) {
  11042. $prop_line = $prop_name;
  11043. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  11044. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  11045. $props_list[] = $prop_line;
  11046. }
  11047. }
  11048. if (!empty($props_list)) {
  11049. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  11050. }
  11051. }
  11052. // 构建美术风格参考
  11053. $art_style_ref = '';
  11054. if (!empty($art_style)) {
  11055. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  11056. }
  11057. // 构建内容简介参考
  11058. $intro_ref = '';
  11059. if (!empty($intro)) {
  11060. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  11061. }
  11062. // 构建完整的AI提示词
  11063. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  11064. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  11065. $user_prompt .= $intro_ref;
  11066. $user_prompt .= $art_style_ref;
  11067. $user_prompt .= $reference_content;
  11068. // $user_prompt .= $roles_ref;
  11069. // $user_prompt .= $scenes_ref;
  11070. $system_prompt = "\n\n【强制要求】\n";
  11071. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  11072. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  11073. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  11074. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  11075. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  11076. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  11077. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  11078. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  11079. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  11080. ###分段剧本
  11081. 片段数量:8
  11082. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  11083. ##片段1
  11084. 时长:12s
  11085. 分镜1
  11086. 出场角色:刀疤脸
  11087. 场景:边境小镇街道
  11088. 出场道具:酒杯-高脚杯
  11089. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  11090. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  11091. 配音台词:
  11092. 背景音效:
  11093. 分镜2
  11094. 出场角色:刀疤脸
  11095. 场景:悦来酒馆
  11096. 出场道具:酒杯-高脚杯
  11097. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  11098. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  11099. 配音台词:
  11100. 背景音效:
  11101. 分镜3
  11102. 出场角色:刀疤脸
  11103. 场景:悦来酒馆
  11104. 出场道具:酒杯-高脚杯
  11105. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  11106. 运镜:从中景推向令牌特写。
  11107. 配音台词:
  11108. 背景音效:
  11109. 分镜4
  11110. 出场角色:刀疤脸
  11111. 场景:悦来酒馆
  11112. 出场道具:酒杯-高脚杯
  11113. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  11114. 运镜:极速推向酒水溅起的瞬间。
  11115. 配音台词:
  11116. 背景音效:
  11117. 分镜5
  11118. 出场角色:刀疤脸
  11119. 场景:悦来酒馆
  11120. 出场道具:酒杯-高脚杯
  11121. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  11122. 运镜:固定机位,利用倾斜构图制造压迫感。
  11123. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  11124. 背景音效:";
  11125. // 获取模型配置
  11126. $model = getProp($data, 'model');
  11127. if (!$model) {
  11128. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  11129. }
  11130. // 验证模型是否在可用模型表中
  11131. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  11132. $model = 'deepseek-v4-pro';
  11133. }
  11134. // 模型兼容性处理
  11135. $thinkingMode = 'disabled';
  11136. $reasoningEffort = 'high';
  11137. if ($model === 'deepseek-chat') {
  11138. $model = 'deepseek-v4-flash';
  11139. $thinkingMode = 'disabled';
  11140. } elseif ($model === 'deepseek-reasoner') {
  11141. $model = 'deepseek-v4-flash';
  11142. $thinkingMode = 'enabled';
  11143. }
  11144. // 构建消息
  11145. $messages = [
  11146. [
  11147. 'role' => 'system',
  11148. 'content' => $system_prompt
  11149. ],
  11150. [
  11151. 'role' => 'user',
  11152. 'content' => $user_prompt
  11153. ]
  11154. ];
  11155. // dd($messages);
  11156. // 构建请求参数
  11157. $post_data = [
  11158. 'model' => $model,
  11159. 'messages' => $messages,
  11160. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  11161. 'frequency_penalty' => 0,
  11162. 'presence_penalty' => 0,
  11163. 'response_format' => ['type' => 'text'],
  11164. 'thinking' => ['type' => $thinkingMode],
  11165. 'stream' => false // 非流式输出
  11166. ];
  11167. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  11168. // 调用AI生成新的分段剧本
  11169. try {
  11170. $fullContent = '';
  11171. $usage = [];
  11172. // 根据模型类型选择调用方法
  11173. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11174. // DeepSeek 官方模型使用 DeepSeek API
  11175. $chatResult = $this->chatOnly($post_data);
  11176. } else if (in_array($model, $this->gpt_text_models)) {
  11177. // GPT 模型使用 TokenRouter API
  11178. $chatResult = $this->gpt54ChatOnly($post_data);
  11179. } else {
  11180. // 其他模型使用火山引擎API
  11181. $chatResult = $this->volcEngineChatCompletion($post_data);
  11182. }
  11183. if (is_array($chatResult)) {
  11184. $fullContent = $chatResult['fullContent'] ?? '';
  11185. $usage = $chatResult['usage'] ?? [];
  11186. }
  11187. $generated_content = $fullContent;
  11188. if (empty($generated_content)) {
  11189. Utils::throwError('20003:AI生成内容为空,请重试');
  11190. }
  11191. // 解析生成的内容 - 按片段分割
  11192. $parsed_segments = [];
  11193. // 先在开头添加换行符,确保第1片段也能被正确分割
  11194. $normalizedText = "\n" . $generated_content;
  11195. $parts = preg_split('/\n\s*##/', $normalizedText);
  11196. foreach ($parts as $part) {
  11197. $part = trim($part);
  11198. if (empty($part)) continue;
  11199. // 匹配"片段X"格式
  11200. if (!preg_match('/^片段\d+/', $part)) {
  11201. continue;
  11202. }
  11203. // 分离标题和内容
  11204. $lines = explode("\n", $part, 2);
  11205. $actTitle = trim($lines[0]);
  11206. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  11207. // 解析标题,提取序号
  11208. $actNumber = 0;
  11209. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  11210. $actNumber = intval($segmentTitleMatch[1]);
  11211. } else {
  11212. $actNumber = count($parsed_segments) + 1;
  11213. }
  11214. // 提取时长(仅保留数字)
  11215. $actDuration = 0;
  11216. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  11217. $actDurationStr = trim($actDurationMatch[1]);
  11218. // 提取数字部分(支持整数和小数)
  11219. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  11220. $actDuration = (float)$numMatch[1];
  11221. }
  11222. }
  11223. // 清理act_content:去除时长、旁白音色等非分镜内容行
  11224. // 只保留分镜内容,并确保分镜标记使用【】格式
  11225. $cleaned_content = '';
  11226. $content_lines = explode("\n", $actContent);
  11227. $is_capturing = false; // 标记是否开始捕获分镜内容
  11228. $count = 0;
  11229. foreach ($content_lines as $line) {
  11230. $trimmed_line = trim($line);
  11231. // 跳过时长和旁白音色行
  11232. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  11233. continue;
  11234. }
  11235. // 检测是否是分镜开始
  11236. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  11237. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  11238. $count++;
  11239. $is_capturing = true;
  11240. // 如果没有【】,则添加
  11241. if (!preg_match('/^【/u', $trimmed_line)) {
  11242. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  11243. }
  11244. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  11245. }
  11246. // 如果已经开始捕获,则添加该行
  11247. if ($is_capturing && !empty($trimmed_line)) {
  11248. $cleaned_content .= $trimmed_line."\n";
  11249. }
  11250. }
  11251. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  11252. $parsed_segments[] = [
  11253. 'act_number' => $actNumber,
  11254. 'act_title' => $actTitle,
  11255. 'act_duration' => $actDuration,
  11256. 'act_content' => $cleaned_content,
  11257. ];
  11258. }
  11259. if (empty($parsed_segments)) {
  11260. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  11261. }
  11262. // 收集所有资产名称(角色、场景、道具)
  11263. $product_names = [];
  11264. // 收集角色名称
  11265. if (!empty($roles) && is_array($roles)) {
  11266. foreach ($roles as $role) {
  11267. $role_name = getProp($role, 'role', '');
  11268. if (!empty($role_name)) {
  11269. $product_names[] = $role_name;
  11270. }
  11271. }
  11272. }
  11273. // 收集场景名称
  11274. if (!empty($scenes) && is_array($scenes)) {
  11275. foreach ($scenes as $scene) {
  11276. $scene_name = getProp($scene, 'scene', '');
  11277. if (!empty($scene_name)) {
  11278. $product_names[] = $scene_name;
  11279. }
  11280. }
  11281. }
  11282. // 收集道具名称
  11283. if (!empty($props) && is_array($props)) {
  11284. foreach ($props as $prop) {
  11285. $prop_name = getProp($prop, 'prop', '');
  11286. if (!empty($prop_name)) {
  11287. $product_names[] = $prop_name;
  11288. }
  11289. }
  11290. }
  11291. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  11292. $product_names = array_unique($product_names);
  11293. usort($product_names, function($a, $b) {
  11294. return mb_strlen($b) - mb_strlen($a);
  11295. });
  11296. // 处理每个片段的 act_show_content
  11297. foreach ($parsed_segments as &$segment) {
  11298. $act_content = getProp($segment, 'act_content', '');
  11299. if (empty($act_content)) {
  11300. $segment['act_show_content'] = '';
  11301. continue;
  11302. }
  11303. $processed_content = $act_content;
  11304. // 统一替换所有资产名称为 {资产名} 格式
  11305. // 使用占位符避免嵌套替换问题
  11306. $placeholder_map = [];
  11307. $placeholder_index = 0;
  11308. foreach ($product_names as $product_name) {
  11309. // 转义特殊字符
  11310. $escaped_product = preg_quote($product_name, '/');
  11311. // 检查是否匹配且未被 {} 包裹
  11312. $processed_content = preg_replace_callback(
  11313. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  11314. function($matches) use (&$placeholder_map, &$placeholder_index) {
  11315. // 使用唯一占位符
  11316. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  11317. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  11318. $placeholder_index++;
  11319. return $placeholder;
  11320. },
  11321. $processed_content
  11322. );
  11323. }
  11324. // 将所有占位符替换回实际内容
  11325. foreach ($placeholder_map as $placeholder => $replacement) {
  11326. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  11327. }
  11328. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  11329. $shot_counter = 0;
  11330. $processed_content = preg_replace_callback(
  11331. '/【(?:镜头|分镜)(\d+)】/u',
  11332. function($matches) use (&$shot_counter) {
  11333. $shot_counter++;
  11334. return '【镜头' . $shot_counter . '】';
  11335. },
  11336. $processed_content
  11337. );
  11338. $segment['act_show_content'] = $processed_content;
  11339. }
  11340. unset($segment); // 解除引用
  11341. // 保存到数据库
  11342. $now = date('Y-m-d H:i:s');
  11343. $saved_acts = []; // 用于记录保存后的片段信息
  11344. if ($act_id > 0) {
  11345. // 单个片段模式:更新单条记录
  11346. if (count($parsed_segments) > 0) {
  11347. $new_segment = $parsed_segments[0];
  11348. $update_data = [
  11349. 'act_content' => getProp($new_segment, 'act_content', ''),
  11350. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  11351. 'act_title' => getProp($new_segment, 'act_title', ''),
  11352. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  11353. 'updated_at' => $now,
  11354. ];
  11355. DB::table('mp_episode_segments')
  11356. ->where('id', $act_id)
  11357. ->update($update_data);
  11358. // 获取更新后的记录
  11359. $updated_act = DB::table('mp_episode_segments')
  11360. ->where('id', $act_id)
  11361. ->first();
  11362. if ($updated_act) {
  11363. $saved_acts[] = [
  11364. 'act_id' => $updated_act->id,
  11365. 'act_number' => $updated_act->act_number,
  11366. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  11367. 'act_content' => $updated_act->act_content,
  11368. 'act_show_content' => $updated_act->act_show_content,
  11369. 'video_url' => $updated_act->video_url ?? '',
  11370. 'video_duration' => $updated_act->video_duration ?? 0,
  11371. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  11372. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  11373. ];
  11374. }
  11375. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  11376. }
  11377. } else {
  11378. // 整个剧集模式:删除原有记录并批量保存新记录
  11379. DB::beginTransaction();
  11380. try {
  11381. // 删除原有的所有片段记录
  11382. DB::table('mp_episode_segments')
  11383. ->where('episode_id', $target_episode_id)
  11384. ->delete();
  11385. // 批量插入新的片段记录
  11386. $segments_to_insert = [];
  11387. foreach ($parsed_segments as $index => $segment) {
  11388. $act_number = $index + 1;
  11389. $segments_to_insert[] = [
  11390. 'anime_id' => $target_anime_id,
  11391. 'episode_id' => $target_episode_id,
  11392. 'episode_number' => $target_episode_number,
  11393. 'act_number' => $act_number,
  11394. 'act_title' => getProp($segment, 'act_title', ''),
  11395. 'act_duration' => getProp($segment, 'act_duration', 0),
  11396. 'act_content' => getProp($segment, 'act_content', ''),
  11397. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  11398. 'created_at' => $now,
  11399. 'updated_at' => $now,
  11400. ];
  11401. }
  11402. if (!empty($segments_to_insert)) {
  11403. DB::table('mp_episode_segments')->insert($segments_to_insert);
  11404. }
  11405. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  11406. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  11407. 'anime_id' => $target_anime_id,
  11408. 'episode_id' => $target_episode_id,
  11409. 'model' => $model,
  11410. 'source' => 'regenerateSegmentScript',
  11411. ]);
  11412. DB::commit();
  11413. // 查询保存后的所有片段记录
  11414. $saved_segments = DB::table('mp_episode_segments')
  11415. ->where('episode_id', $target_episode_id)
  11416. ->orderBy('act_number')
  11417. ->get();
  11418. foreach ($saved_segments as $saved_segment) {
  11419. $saved_acts[] = [
  11420. 'act_id' => $saved_segment->id,
  11421. 'act_number' => $saved_segment->act_number,
  11422. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  11423. 'act_content' => $saved_segment->act_content,
  11424. 'act_show_content' => $saved_segment->act_show_content,
  11425. 'video_url' => $saved_segment->video_url ?? '',
  11426. 'video_duration' => $saved_segment->video_duration ?? 0,
  11427. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  11428. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  11429. ];
  11430. }
  11431. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  11432. 'episode_id' => $target_episode_id,
  11433. 'segments_count' => count($segments_to_insert)
  11434. ]);
  11435. } catch (\Exception $e) {
  11436. DB::rollBack();
  11437. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  11438. Utils::throwError('20003:保存失败,请重试');
  11439. }
  11440. }
  11441. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  11442. return [
  11443. 'anime_id' => $target_anime_id,
  11444. 'episode_id' => $target_episode_id,
  11445. 'title' => getProp($episode, 'title', ''),
  11446. 'episode_number' => $target_episode_number,
  11447. 'is_generated' => getProp($episode, 'is_generated', 0),
  11448. 'acts' => $saved_acts,
  11449. ];
  11450. } catch (\Exception $e) {
  11451. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  11452. throw $e;
  11453. }
  11454. }
  11455. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  11456. {
  11457. $episode_arr = [
  11458. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  11459. 'intro' => getProp($script_arr, 'intro'),
  11460. 'art_style' => getProp($script_arr, 'art_style'),
  11461. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  11462. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  11463. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  11464. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  11465. ];
  11466. if (empty($episode_arr['acts'])) {
  11467. $fallback_episode_arr = handleEpisodeContent($fullContent);
  11468. if (!empty($fallback_episode_arr['acts'])) {
  11469. $episode_arr = array_merge($fallback_episode_arr, [
  11470. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  11471. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  11472. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  11473. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  11474. ]);
  11475. }
  11476. }
  11477. // if (!getProp($episode_arr, 'episode_title')) {
  11478. // $episode_title = '';
  11479. // $episodes = getProp($script_arr, 'episodes', []);
  11480. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  11481. // $episode_title = '第1集:' . $episodes[0]['title'];
  11482. // }
  11483. // if (!$episode_title) {
  11484. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  11485. // }
  11486. // $episode_arr['episode_title'] = $episode_title;
  11487. // }
  11488. return $episode_arr;
  11489. }
  11490. private function saveEpisodeVersionData(
  11491. int $anime_id,
  11492. int $episode_number,
  11493. array $episode_arr,
  11494. array $existing_roles,
  11495. array $existing_scenes,
  11496. array $existing_props,
  11497. $current_episode,
  11498. $base_episode,
  11499. bool $is_regenerate_version,
  11500. string $content,
  11501. string $now,
  11502. array $ref_products = []
  11503. ): array {
  11504. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  11505. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  11506. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  11507. // 过滤掉关键字段为空的条目
  11508. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  11509. return !empty($item['role'] ?? null);
  11510. }));
  11511. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  11512. return !empty($item['scene'] ?? null);
  11513. }));
  11514. $merged_props = array_values(array_filter($generated_props, function ($item) {
  11515. return !empty($item['prop'] ?? null);
  11516. }));
  11517. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  11518. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  11519. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  11520. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  11521. $ace_mode = getProp($anime, 'ace_mode');
  11522. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  11523. $global_roles = json_decode(getProp($anime, 'roles'), true);
  11524. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  11525. $global_roles = is_array($global_roles) ? $global_roles : [];
  11526. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  11527. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  11528. $art_style_type = getProp($anime, 'art_style_type');
  11529. // 检查并创建 roles 的图片生成任务
  11530. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  11531. // 检查并创建 scenes 的图片生成任务
  11532. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  11533. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  11534. if ($arr && is_array($arr)) {
  11535. $merged_roles = $arr['roles'];
  11536. $merged_scenes = $arr['scenes'];
  11537. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  11538. }
  11539. // 确保数据是数组类型
  11540. if (!is_array($merged_roles)) {
  11541. dLog('deepseek')->error('merged_roles不是数组类型', [
  11542. 'type' => gettype($merged_roles),
  11543. 'value' => $merged_roles
  11544. ]);
  11545. $merged_roles = [];
  11546. }
  11547. if (!is_array($merged_scenes)) {
  11548. dLog('deepseek')->error('merged_scenes不是数组类型', [
  11549. 'type' => gettype($merged_scenes),
  11550. 'value' => $merged_scenes
  11551. ]);
  11552. $merged_scenes = [];
  11553. }
  11554. if (!is_array($merged_props)) {
  11555. dLog('deepseek')->error('merged_props不是数组类型', [
  11556. 'type' => gettype($merged_props),
  11557. 'value' => $merged_props
  11558. ]);
  11559. $merged_props = [];
  11560. }
  11561. // 同步新出现的主体和场景到全局
  11562. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  11563. $role_arr = [];
  11564. foreach ($merged_roles as $item) {
  11565. $role_arr[$item['role']] = $item;
  11566. }
  11567. $version_count = DB::table('mp_anime_episodes')
  11568. ->where('anime_id', $anime_id)
  11569. ->where('episode_number', $episode_number)
  11570. ->count('id');
  11571. $episode = [
  11572. 'anime_id' => $anime_id,
  11573. 'episode_number' => $episode_number,
  11574. 'title' => getProp($episode_arr, 'episode_title'),
  11575. 'content' => $content,
  11576. 'intro' => getProp($episode_arr, 'intro'),
  11577. 'art_style' => getProp($episode_arr, 'art_style'),
  11578. 'roles' => json_encode($merged_roles, 256),
  11579. 'scenes' => json_encode($merged_scenes, 256),
  11580. 'props' => json_encode($merged_props, 256),
  11581. 'generate_status' => '待执行',
  11582. 'generate_at' => $now,
  11583. 'is_default' => 1,
  11584. 'updated_at' => $now,
  11585. ];
  11586. $del_flag = false;
  11587. if ($is_regenerate_version) {
  11588. DB::table('mp_anime_episodes')
  11589. ->where('anime_id', $anime_id)
  11590. ->where('episode_number', $episode_number)
  11591. ->update(['is_default' => 0, 'updated_at' => $now]);
  11592. $episode['sequence'] = $version_count + 1;
  11593. $episode['created_at'] = $now;
  11594. $episode['cpid'] = Site::getCpid();
  11595. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  11596. if (!$episode_id) {
  11597. Utils::throwError('20003:创建剧集版本失败');
  11598. }
  11599. } else {
  11600. $target_episode = $current_episode ?: $base_episode;
  11601. if ($target_episode) {
  11602. $episode_id = getProp($target_episode, 'id');
  11603. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  11604. DB::table('mp_anime_episodes')
  11605. ->where('anime_id', $anime_id)
  11606. ->where('episode_number', $episode_number)
  11607. ->where('id', '<>', $episode_id)
  11608. ->update(['is_default' => 0, 'updated_at' => $now]);
  11609. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  11610. if ($boolen === false) {
  11611. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  11612. Utils::throwError('20003:分集内容保存失败');
  11613. }
  11614. $del_flag = true;
  11615. } else {
  11616. DB::table('mp_anime_episodes')
  11617. ->where('anime_id', $anime_id)
  11618. ->where('episode_number', $episode_number)
  11619. ->update(['is_default' => 0, 'updated_at' => $now]);
  11620. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  11621. $episode['created_at'] = $now;
  11622. $episode['cpid'] = Site::getCpid();
  11623. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  11624. if (!$episode_id) {
  11625. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  11626. Utils::throwError('20003:分集内容保存失败');
  11627. }
  11628. }
  11629. }
  11630. $segments = [];
  11631. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  11632. // 如果是第2集及以后,获取上一集的主体音色数据
  11633. $previous_roles_voice = [];
  11634. if ($episode_number >= 2) {
  11635. $previous_episode = DB::table('mp_anime_episodes')
  11636. ->where('anime_id', $anime_id)
  11637. ->where('episode_number', $episode_number - 1)
  11638. ->where('is_default', 1)
  11639. ->first();
  11640. if ($previous_episode) {
  11641. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  11642. if (is_array($previous_roles)) {
  11643. foreach ($previous_roles as $prev_role) {
  11644. $role_name = getProp($prev_role, 'role');
  11645. if ($role_name) {
  11646. $previous_roles_voice[$role_name] = [
  11647. 'voice_name' => getProp($prev_role, 'voice_name'),
  11648. 'voice_type' => getProp($prev_role, 'voice_type'),
  11649. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  11650. ];
  11651. $voice_prompt = getProp($prev_role, 'voice_prompt');
  11652. if ($voice_prompt) {
  11653. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  11654. }
  11655. }
  11656. }
  11657. }
  11658. }
  11659. }
  11660. // 将继承的音色数据同步到当前集的主体列表
  11661. if (!empty($previous_roles_voice)) {
  11662. foreach ($merged_roles as &$role) {
  11663. $role_name = getProp($role, 'role');
  11664. if ($role_name && isset($previous_roles_voice[$role_name])) {
  11665. // 强制继承上一集的音色数据
  11666. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  11667. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  11668. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  11669. // 如果上一集有 voice_prompt 则继承,否则跳过
  11670. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  11671. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  11672. }
  11673. }
  11674. }
  11675. unset($role); // 解除引用
  11676. // 更新 role_arr 以便后续使用
  11677. $role_arr = [];
  11678. foreach ($merged_roles as $item) {
  11679. $role_arr[$item['role']] = $item;
  11680. }
  11681. }
  11682. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  11683. $emotion_list = array_flip($emotion_list);
  11684. foreach ($acts as $act) {
  11685. $act_segments = getProp($act, 'segments', []);
  11686. if (!is_array($act_segments)) {
  11687. continue;
  11688. }
  11689. if ((int)$ace_mode === 1) {
  11690. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  11691. $merged_parts = [];
  11692. foreach ($act_segments as $seg) {
  11693. $seg_num = getProp($seg, 'segment_number');
  11694. $seg_content = getProp($seg, 'segment_content');
  11695. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  11696. }
  11697. $act_content = implode("\n", $merged_parts);
  11698. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  11699. $segments[] = [
  11700. 'anime_id' => $anime_id,
  11701. 'episode_id' => $episode_id,
  11702. 'episode_number' => $episode_number,
  11703. 'act_number' => getProp($act, 'act_number'),
  11704. 'act_title' => getProp($act, 'act_title'),
  11705. 'act_duration' => getProp($act, 'act_duration'),
  11706. 'act_content' => $act_content,
  11707. 'created_at' => $now,
  11708. 'updated_at' => $now
  11709. ];
  11710. } else {
  11711. foreach ($act_segments as $segment) {
  11712. $voice_actor = getProp($segment, 'voice_actor');
  11713. // 优先从上一集继承音色数据
  11714. $timbre_info = [];
  11715. if (isset($previous_roles_voice[$voice_actor])) {
  11716. // 从上一集继承音色数据
  11717. $timbre_info = $previous_roles_voice[$voice_actor];
  11718. } elseif (isset($role_arr[$voice_actor])) {
  11719. // 使用当前集的主体音色数据
  11720. $timbre_info = $role_arr[$voice_actor];
  11721. }
  11722. $voice_type = getProp($timbre_info, 'voice_type');
  11723. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  11724. if ($timbre_emotion) {
  11725. $timbre_emotion = explode(',', $timbre_emotion);
  11726. } else {
  11727. $timbre_emotion = [];
  11728. }
  11729. $emotion = getProp($segment, 'emotion', '中性');
  11730. if (!in_array($emotion, $timbre_emotion)) {
  11731. $emotion = '中性';
  11732. }
  11733. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  11734. $segments[] = [
  11735. 'anime_id' => $anime_id,
  11736. 'episode_id' => $episode_id,
  11737. 'episode_number' => $episode_number,
  11738. 'act_number' => getProp($act, 'act_number'),
  11739. 'act_title' => getProp($act, 'act_title'),
  11740. 'act_duration' => getProp($act, 'act_duration'),
  11741. 'segment_id' => getProp($segment, 'segment_id'),
  11742. 'segment_number' => getProp($segment, 'segment_number'),
  11743. 'segment_content' => getProp($segment, 'segment_content'),
  11744. 'description' => getProp($segment, 'description'),
  11745. 'composition' => getProp($segment, 'composition'),
  11746. 'camera_movement' => getProp($segment, 'camera_movement'),
  11747. 'voice_actor' => $voice_actor,
  11748. 'dialogue' => getProp($segment, 'dialogue'),
  11749. 'frame_type' => getProp($segment, 'frame_type'),
  11750. 'scene' => getProp($segment, 'scene'),
  11751. 'characters' => getProp($segment, 'characters'),
  11752. 'tail_frame' => getProp($segment, 'tail_frame'),
  11753. 'voice_name' => getProp($timbre_info, 'voice_name'),
  11754. 'voice_type' => $voice_type,
  11755. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  11756. 'emotion' => $emotion,
  11757. 'emotion_type' => $emotion_type,
  11758. 'gender' => getProp($segment, 'gender', '0'),
  11759. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  11760. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  11761. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  11762. 'pitch' => getProp($segment, 'pitch', 0),
  11763. 'created_at' => $now,
  11764. 'updated_at' => $now
  11765. ];
  11766. }
  11767. }
  11768. }
  11769. if ($segments) {
  11770. if ($del_flag) {
  11771. DB::table('mp_episode_segments')
  11772. ->where('anime_id', $anime_id)
  11773. ->where('episode_id', $episode_id)
  11774. ->delete();
  11775. }
  11776. $boolen = DB::table('mp_episode_segments')->insert($segments);
  11777. if (!$boolen) {
  11778. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  11779. Utils::throwError('20003:分镜内容保存失败');
  11780. }
  11781. }
  11782. dLog('deepseek')->info('segments', $segments);
  11783. // ace_mode=1: acts 返回值按合并格式调整
  11784. if ((int)$ace_mode === 1) {
  11785. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  11786. $act_map = [];
  11787. foreach ($table_act_data as $item) {
  11788. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  11789. }
  11790. $restructured_acts = [];
  11791. foreach ($acts as $act) {
  11792. $act_segments = getProp($act, 'segments', []);
  11793. if (!is_array($act_segments)) {
  11794. continue;
  11795. }
  11796. $merged_parts = [];
  11797. foreach ($act_segments as $seg) {
  11798. $seg_num = getProp($seg, 'segment_number');
  11799. $seg_content = getProp($seg, 'segment_content');
  11800. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  11801. }
  11802. $act_content = implode("\n", $merged_parts);
  11803. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  11804. $restructured_acts[] = [
  11805. 'anime_id' => $anime_id,
  11806. 'episode_id' => $episode_id,
  11807. 'episode_number' => $episode_number,
  11808. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  11809. 'act_number' => getProp($act, 'act_number'),
  11810. 'act_title' => getProp($act, 'act_title'),
  11811. 'act_duration' => getProp($act, 'act_duration'),
  11812. 'act_content' => $act_content,
  11813. 'created_at' => $now,
  11814. 'updated_at' => $now,
  11815. ];
  11816. }
  11817. $acts = $restructured_acts;
  11818. }
  11819. $episode['episode_id'] = $episode_id;
  11820. $episode['roles'] = $merged_roles;
  11821. $episode['scenes'] = $merged_scenes;
  11822. $episode['props'] = $merged_props;
  11823. $episode['acts'] = $acts;
  11824. return [
  11825. 'episode' => $episode,
  11826. 'episode_id' => $episode_id,
  11827. 'merged_roles' => $merged_roles,
  11828. 'merged_scenes' => $merged_scenes,
  11829. 'merged_props' => $merged_props,
  11830. ];
  11831. }
  11832. private function buildEpisodeItemContent(array $items, string $nameKey): string
  11833. {
  11834. $content = '';
  11835. foreach ($items as $item) {
  11836. $name = trim((string)getProp($item, $nameKey));
  11837. if ($name === '' || $name === '旁白') {
  11838. continue;
  11839. }
  11840. $description = trim((string)getProp($item, 'description'));
  11841. $content .= $name . ': ' . $description;
  11842. if ($nameKey == 'role') {
  11843. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  11844. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11845. $voice_name = trim(getProp($item, 'voice_name'));
  11846. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  11847. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  11848. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  11849. }else {
  11850. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  11851. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11852. }
  11853. $content .= "\n";
  11854. }
  11855. return trim($content);
  11856. }
  11857. private function getEpisodeChatContent($animeId, $sequence, $content) {
  11858. if ((int)$sequence <= 0) {
  11859. return [];
  11860. }
  11861. $origin_content = '';
  11862. if ($content) {
  11863. $origin_content = '本集剧情内容:'.$content;
  11864. }else {
  11865. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  11866. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  11867. }
  11868. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  11869. // 获取分集信息
  11870. $episode = DB::table('mp_anime_episodes')
  11871. ->where('anime_id', $animeId)
  11872. ->where('episode_number', $sequence)
  11873. ->where('is_default', 1)
  11874. ->first();
  11875. if (!$episode) {
  11876. return [];
  11877. }
  11878. $episode_id = getProp($episode, 'id');
  11879. $episode_number = getProp($episode, 'episode_number');
  11880. $title = getProp($episode, 'title');
  11881. $intro = getProp($episode, 'intro');
  11882. $art_style = getProp($episode, 'art_style');
  11883. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  11884. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  11885. // 组装纯文本内容
  11886. $content = '';
  11887. // 添加分集标题和梗概
  11888. $content .= "###第{$episode_number}集:{$title}\n\n";
  11889. $content .= "###故事梗概\n";
  11890. $content .= trim($intro) . "\n\n";
  11891. // 添加美术风格
  11892. $content .= "###美术风格\n";
  11893. $content .= trim($art_style) . "\n\n";
  11894. // 添加主体列表
  11895. $content .= "###主体列表\n";
  11896. $pangbai_voice_prompt = "";
  11897. foreach ($roles as $role) {
  11898. $name = getProp($role, 'role');
  11899. $description = getProp($role, 'description');
  11900. $pic_prompt = getProp($role, 'pic_prompt');
  11901. $voice_prompt = getProp($role, 'voice_prompt');
  11902. $voice_name = getProp($role, 'voice_name');
  11903. $content .= "{$name}: {$description}";
  11904. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11905. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  11906. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  11907. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  11908. $content .= "\n";
  11909. }
  11910. $content .= "\n";
  11911. // 添加场景列表
  11912. $content .= "###场景列表\n";
  11913. foreach ($scenes as $scene) {
  11914. $name = getProp($scene, 'scene');
  11915. $description = getProp($scene, 'description');
  11916. $pic_prompt = getProp($scene, 'pic_prompt');
  11917. $content .= "{$name}: {$description}";
  11918. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11919. $content .= "\n";
  11920. }
  11921. $content .= "\n";
  11922. // 获取分镜信息
  11923. $segments = DB::table('mp_episode_segments')
  11924. ->where('anime_id', $animeId)
  11925. ->where('episode_id', $episode_id)
  11926. ->orderBy('segment_number')
  11927. ->get();
  11928. if ($segments && count($segments) > 0) {
  11929. if ((int)$ace_mode === 1) {
  11930. $content .= "###分段剧本\n";
  11931. // 获取片段数量
  11932. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  11933. $content .= "片段数量:{$act_count}\n";
  11934. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  11935. $content .= "\n";
  11936. }else {
  11937. $content .= "###分镜剧本\n";
  11938. }
  11939. // 按幕分组
  11940. $currentAct = null;
  11941. foreach ($segments as $segment) {
  11942. $act_number = getProp($segment, 'act_number');
  11943. $act_title = getProp($segment, 'act_title');
  11944. $act_duration = getProp($segment, 'act_duration');
  11945. $segment_number = getProp($segment, 'segment_number');
  11946. $segment_content = getProp($segment, 'segment_content');
  11947. $scene_description = getProp($segment, 'scene_description');
  11948. $scene_name = getProp($segment, 'scene_name');
  11949. $composition = getProp($segment, 'composition');
  11950. $camera_movement = getProp($segment, 'camera_movement');
  11951. $voice_type = getProp($segment, 'voice_type');
  11952. $characters = getProp($segment, 'characters');
  11953. $dialogue = getProp($segment, 'dialogue');
  11954. $frame_type = getProp($segment, 'frame_type');
  11955. $tail_frame_description = getProp($segment, 'tail_frame_description');
  11956. // 判断是否是全能模式
  11957. if ((int)$ace_mode === 1) { // 全能模式
  11958. // 如果是新的分段,添加分段标题
  11959. if ($act_number !== $currentAct) {
  11960. $currentAct = $act_number;
  11961. $content .= "##{$act_title}\n";
  11962. $content .= "时长:{$act_duration}s\n";
  11963. }
  11964. }else {
  11965. // 如果是新的幕,添加幕标题
  11966. if ($act_number !== $currentAct) {
  11967. $currentAct = $act_number;
  11968. $content .= "##第{$act_number}幕:{$scene_name}\n";
  11969. }
  11970. }
  11971. // 添加分镜信息
  11972. $content .= "分镜{$segment_number}\n";
  11973. $content .= "分镜内容:\n{$segment_content}\n";
  11974. // $content .= "画面描述:{$scene_description}\n";
  11975. // $content .= "场景:{$scene_name}\n";
  11976. // $content .= "构图设计:{$composition}\n";
  11977. // $content .= "运镜调度:{$camera_movement}\n";
  11978. // if (!empty($voice_type)) {
  11979. // $content .= "配音角色:{$voice_type}\n";
  11980. // }
  11981. // if (!empty($characters)) {
  11982. // $content .= "出镜角色:{$characters}\n";
  11983. // }
  11984. // if (!empty($dialogue)) {
  11985. // $content .= "台词内容:\"{$dialogue}\"\n";
  11986. // }
  11987. // $content .= "画面类型:{$frame_type}\n";
  11988. // $content .= "尾帧描述:{$tail_frame_description}\n";
  11989. $content .= "\n";
  11990. }
  11991. }
  11992. $content = trim($content);
  11993. if($content) $content = "上集剧本内容:\n{$content}";
  11994. return [
  11995. [
  11996. 'role' => 'user',
  11997. 'content' => $origin_content
  11998. ],
  11999. [
  12000. 'role' => 'assistant',
  12001. 'content' => $content
  12002. ]
  12003. ];
  12004. }
  12005. private function getEpisodeChatMessages($animeId, $sequence): array
  12006. {
  12007. if ((int)$sequence <= 0) {
  12008. return [];
  12009. }
  12010. return DB::table('mp_anime_records')
  12011. ->where('anime_id', $animeId)
  12012. ->where('sequence', $sequence)
  12013. ->where('episode_id', '>', 0)
  12014. ->select('role', 'content')
  12015. ->orderBy('created_at')
  12016. ->orderBy('id')
  12017. ->get()
  12018. ->map(function ($value) {
  12019. return (array)$value;
  12020. })
  12021. ->toArray();
  12022. }
  12023. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  12024. {
  12025. $existingMap = [];
  12026. foreach ($existingItems as $item) {
  12027. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  12028. if ($itemKey === '') {
  12029. continue;
  12030. }
  12031. $existingMap[$itemKey] = $item;
  12032. }
  12033. if (!$generatedItems) {
  12034. return array_values($existingItems);
  12035. }
  12036. $merged = [];
  12037. foreach ($generatedItems as $item) {
  12038. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  12039. if ($itemKey === '') {
  12040. continue;
  12041. }
  12042. if (isset($existingMap[$itemKey])) {
  12043. if (trim((string)getProp($item, 'description')) === '') {
  12044. $merged[] = $existingMap[$itemKey];
  12045. continue;
  12046. }
  12047. // 检查内容是否发生变化
  12048. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  12049. if (!$isChanged) {
  12050. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  12051. $mergedItem = [
  12052. $nameKey => trim((string)getProp($item, $nameKey)),
  12053. 'description' => trim((string)getProp($item, 'description')),
  12054. ];
  12055. // 如果有 pic_prompt,添加到合并项中
  12056. $picPrompt = getProp($item, 'pic_prompt');
  12057. if (!empty($picPrompt)) {
  12058. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  12059. }
  12060. // 继承现有项的 URL
  12061. $existingUrl = getProp($existingMap[$itemKey], 'url');
  12062. if (!empty($existingUrl)) {
  12063. $mergedItem['url'] = $existingUrl;
  12064. }
  12065. // 继承现有项的 task_id
  12066. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  12067. if (!empty($existingTaskId)) {
  12068. $mergedItem['task_id'] = $existingTaskId;
  12069. }
  12070. // 继承现有项的 task_status
  12071. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  12072. if (!empty($existingTaskStatus)) {
  12073. $mergedItem['task_status'] = $existingTaskStatus;
  12074. }
  12075. // 保留生成项的音色字段
  12076. $voiceName = getProp($item, 'voice_name');
  12077. if (!empty($voiceName)) {
  12078. $mergedItem['voice_name'] = $voiceName;
  12079. }
  12080. $voiceType = getProp($item, 'voice_type');
  12081. if (!empty($voiceType)) {
  12082. $mergedItem['voice_type'] = $voiceType;
  12083. }
  12084. $audioUrl = getProp($item, 'voice_audio_url');
  12085. if (!empty($audioUrl)) {
  12086. $mergedItem['voice_audio_url'] = $audioUrl;
  12087. }
  12088. $merged[] = $mergedItem;
  12089. } else {
  12090. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  12091. $mergedItem = [
  12092. $nameKey => trim((string)getProp($item, $nameKey)),
  12093. 'description' => trim((string)getProp($item, 'description')),
  12094. ];
  12095. // 如果有 pic_prompt,添加到合并项中
  12096. $picPrompt = getProp($item, 'pic_prompt');
  12097. if (!empty($picPrompt)) {
  12098. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  12099. }
  12100. // 保留生成项的音色字段
  12101. $voiceName = getProp($item, 'voice_name');
  12102. if (!empty($voiceName)) {
  12103. $mergedItem['voice_name'] = $voiceName;
  12104. }
  12105. $voiceType = getProp($item, 'voice_type');
  12106. if (!empty($voiceType)) {
  12107. $mergedItem['voice_type'] = $voiceType;
  12108. }
  12109. $audioUrl = getProp($item, 'voice_audio_url');
  12110. if (!empty($audioUrl)) {
  12111. $mergedItem['voice_audio_url'] = $audioUrl;
  12112. }
  12113. // 不继承 URL、task_id 和 task_status(重置状态)
  12114. $merged[] = $mergedItem;
  12115. }
  12116. } else {
  12117. // 新增项,保留生成项的所有字段
  12118. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  12119. }
  12120. }
  12121. return $merged ?: array_values($existingItems);
  12122. }
  12123. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  12124. {
  12125. $resetItem = [
  12126. $nameKey => trim((string)getProp($item, $nameKey)),
  12127. 'description' => trim((string)getProp($item, 'description')),
  12128. ];
  12129. // 保留指定的字段
  12130. foreach ($preserveFields as $field) {
  12131. $value = getProp($item, $field);
  12132. if (!empty($value)) {
  12133. $resetItem[$field] = $value;
  12134. }
  12135. }
  12136. return $resetItem;
  12137. }
  12138. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  12139. {
  12140. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  12141. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  12142. if ($existingKey !== $generatedKey) {
  12143. return true;
  12144. }
  12145. // 比较 description 是否变化
  12146. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  12147. return true;
  12148. }
  12149. // 比较 pic_prompt 是否变化
  12150. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  12151. }
  12152. private function normalizeEpisodeResourceKey($value): string
  12153. {
  12154. $value = trim((string)$value);
  12155. if ($value === '') {
  12156. return '';
  12157. }
  12158. return strtolower((string)preg_replace('/\s+/u', '', $value));
  12159. }
  12160. // 生成全局角色图片
  12161. private function batchSetGlobalRoleImg($data, $is_force=false) {
  12162. $anime_id = getProp($data, 'anime_id');
  12163. if (!$anime_id) Utils::throwError('1002:请选择对话');
  12164. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12165. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  12166. $art_style = getProp($anime, 'art_style');
  12167. $update_flag = false;
  12168. foreach ($roles as &$role) {
  12169. $role_name = getProp($role, 'role');
  12170. if ($role_name == '旁白') continue;
  12171. // 优先使用 pic_prompt,如果没有则使用 description
  12172. $pic_prompt = getProp($role, 'pic_prompt');
  12173. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  12174. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  12175. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  12176. // 参考图地址
  12177. $ref_img_url = getProp($role, 'url');
  12178. if (!$is_force && $ref_img_url) continue;
  12179. $update_flag = true;
  12180. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  12181. try {
  12182. $params = [
  12183. 'prompt' => $description,
  12184. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  12185. 'ref_img_urls' => []
  12186. ];
  12187. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12188. $task_id = $task->id;
  12189. if (!$task_id) {
  12190. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  12191. }
  12192. $role['task_id'] = $task_id;
  12193. $role['task_status'] = 'processing';
  12194. } catch (\Exception $e) {
  12195. Utils::throwError("20003:" . $e->getMessage());
  12196. }
  12197. }
  12198. if (!$update_flag) return true;
  12199. // 保存角色信息
  12200. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  12201. 'roles' => json_encode($roles, 256),
  12202. 'generate_status' => '执行中',
  12203. 'generate_at' => date('Y-m-d H:i:s'),
  12204. 'updated_at' => date('Y-m-d H:i:s')
  12205. ]);
  12206. if (!$boolen) {
  12207. Utils::throwError('20003:保存角色信息失败');
  12208. }
  12209. return $boolen;
  12210. }
  12211. // 生成全局场景图片
  12212. private function batchSetGlobalSceneImg($data, $is_force=false) {
  12213. $anime_id = getProp($data, 'anime_id');
  12214. if (!$anime_id) Utils::throwError('1002:请选择对话');
  12215. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12216. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  12217. $art_style = getProp($anime, 'art_style');
  12218. $update_flag = false;
  12219. foreach ($scenes as &$scene) {
  12220. $scene_name = getProp($scene, 'scene');
  12221. // 优先使用 pic_prompt,如果没有则使用 description
  12222. $pic_prompt = getProp($scene, 'pic_prompt');
  12223. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  12224. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  12225. // 参考图地址
  12226. $ref_img_url = getProp($scene, 'url');
  12227. if (!$is_force && $ref_img_url) continue;
  12228. $update_flag = true;
  12229. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  12230. try {
  12231. $params = [
  12232. 'prompt' => $description,
  12233. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  12234. 'ref_img_urls' => []
  12235. ];
  12236. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12237. $task_id = $task->id;
  12238. if (!$task_id) {
  12239. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  12240. }
  12241. $scene['task_id'] = $task_id;
  12242. $scene['task_status'] = 'processing';
  12243. } catch (\Exception $e) {
  12244. Utils::throwError("20003:" . $e->getMessage());
  12245. }
  12246. }
  12247. if (!$update_flag) return true;
  12248. // 保存角色信息
  12249. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  12250. 'scenes' => json_encode($scenes, 256),
  12251. 'generate_status' => '执行中',
  12252. 'generate_at' => date('Y-m-d H:i:s'),
  12253. 'updated_at' => date('Y-m-d H:i:s')
  12254. ]);
  12255. if (!$boolen) {
  12256. Utils::throwError('20003:保存角色信息失败');
  12257. }
  12258. return $boolen;
  12259. }
  12260. // 生成分镜主体、场景和道具图片
  12261. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  12262. $character_prefix = '';
  12263. $scene_prefix = '';
  12264. $prop_prefix = '';
  12265. if ($art_style_type) {
  12266. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  12267. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  12268. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  12269. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  12270. }
  12271. $update_flag = false;
  12272. // 获取上一集的roles、scenes和props数据
  12273. $prev_roles = [];
  12274. $prev_scenes = [];
  12275. $prev_props = [];
  12276. if ($episode_number > 1) {
  12277. $prev_episode = DB::table('mp_anime_episodes')
  12278. ->where('anime_id', $anime_id)
  12279. ->where('episode_number', $episode_number - 1)
  12280. ->where('is_default', 1)
  12281. ->first();
  12282. if ($prev_episode) {
  12283. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  12284. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  12285. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  12286. dLog('deepseek')->info("获取上一集数据成功", [
  12287. 'anime_id' => $anime_id,
  12288. 'prev_episode_number' => $episode_number - 1,
  12289. 'prev_roles_count' => count($prev_roles),
  12290. 'prev_scenes_count' => count($prev_scenes),
  12291. 'prev_props_count' => count($prev_props)
  12292. ]);
  12293. }
  12294. }
  12295. // 处理角色图片生成
  12296. foreach ($roles as &$role) {
  12297. $role_name = getProp($role, 'role');
  12298. if ($role_name == '旁白') continue;
  12299. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  12300. if (isset($ref_products[$role_name])) {
  12301. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  12302. if ($role['url']) continue;
  12303. }
  12304. $role_description = getProp($role, 'description');
  12305. $role_pic_prompt = getProp($role, 'pic_prompt');
  12306. $role_url = getProp($role, 'url');
  12307. // 检查是否可以从上一集继承
  12308. $inherited = false;
  12309. if (!$is_force && !empty($prev_roles)) {
  12310. foreach ($prev_roles as $prev_role) {
  12311. $prev_role_name = getProp($prev_role, 'role');
  12312. $prev_description = getProp($prev_role, 'description');
  12313. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  12314. $prev_url = getProp($prev_role, 'url');
  12315. $prev_task_id = getProp($prev_role, 'task_id');
  12316. $prev_task_status = getProp($prev_role, 'task_status');
  12317. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  12318. if ($role_name == $prev_role_name
  12319. && $role_description == $prev_description
  12320. && $role_pic_prompt == $prev_pic_prompt
  12321. && !empty($prev_url)) {
  12322. $role['task_id'] = $prev_task_id;
  12323. $role['task_status'] = $prev_task_status;
  12324. $role['url'] = $prev_url;
  12325. $inherited = true;
  12326. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  12327. 'anime_id' => $anime_id,
  12328. 'episode_number' => $episode_number,
  12329. 'task_id' => $prev_task_id,
  12330. 'url' => $prev_url
  12331. ]);
  12332. break;
  12333. }
  12334. }
  12335. }
  12336. // 如果已继承或已有url,跳过生成
  12337. if ($inherited || (!$is_force && $role_url)) {
  12338. continue;
  12339. }
  12340. // 优先使用 pic_prompt,如果没有则使用 description
  12341. $pic_prompt = getProp($role, 'pic_prompt');
  12342. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  12343. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  12344. $update_flag = true;
  12345. // 调用AIImageGenerationService的生成图片任务接口
  12346. try {
  12347. $params = [
  12348. 'prompt' => $description,
  12349. 'ref_img_urls' => []
  12350. ];
  12351. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12352. $task_id = $task->id;
  12353. if (!$task_id) {
  12354. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  12355. continue; // 不中断,继续处理其他角色
  12356. }
  12357. $role['task_id'] = $task_id;
  12358. $role['task_status'] = 'processing';
  12359. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  12360. 'anime_id' => $anime_id,
  12361. 'episode_number' => $episode_number,
  12362. 'task_id' => $task_id
  12363. ]);
  12364. } catch (\Exception $e) {
  12365. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  12366. // 不抛出异常,继续处理其他角色
  12367. }
  12368. }
  12369. // 处理场景图片生成
  12370. foreach ($scenes as &$scene) {
  12371. $scene_name = getProp($scene, 'scene');
  12372. $scene_description = getProp($scene, 'description');
  12373. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  12374. $scene_url = getProp($scene, 'url');
  12375. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  12376. if (isset($ref_products[$scene_name])) {
  12377. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  12378. if ($scene['url']) continue;
  12379. }
  12380. // 检查是否可以从上一集继承
  12381. $inherited = false;
  12382. if (!$is_force && !empty($prev_scenes)) {
  12383. foreach ($prev_scenes as $prev_scene) {
  12384. $prev_scene_name = getProp($prev_scene, 'scene');
  12385. $prev_description = getProp($prev_scene, 'description');
  12386. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  12387. $prev_url = getProp($prev_scene, 'url');
  12388. $prev_task_id = getProp($prev_scene, 'task_id');
  12389. $prev_task_status = getProp($prev_scene, 'task_status');
  12390. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  12391. if ($scene_name == $prev_scene_name
  12392. && $scene_description == $prev_description
  12393. && $scene_pic_prompt == $prev_pic_prompt
  12394. && !empty($prev_url)) {
  12395. $scene['task_id'] = $prev_task_id;
  12396. $scene['task_status'] = $prev_task_status;
  12397. $scene['url'] = $prev_url;
  12398. $inherited = true;
  12399. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  12400. 'anime_id' => $anime_id,
  12401. 'episode_number' => $episode_number,
  12402. 'task_id' => $prev_task_id,
  12403. 'url' => $prev_url
  12404. ]);
  12405. break;
  12406. }
  12407. }
  12408. }
  12409. // 如果已继承或已有url,跳过生成
  12410. if ($inherited || (!$is_force && $scene_url)) {
  12411. continue;
  12412. }
  12413. // 优先使用 pic_prompt,如果没有则使用 description
  12414. $pic_prompt = getProp($scene, 'pic_prompt');
  12415. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  12416. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  12417. $update_flag = true;
  12418. // 调用AIImageGenerationService的生成图片任务接口
  12419. try {
  12420. $params = [
  12421. 'prompt' => $description,
  12422. 'ref_img_urls' => []
  12423. ];
  12424. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12425. $task_id = $task->id;
  12426. if (!$task_id) {
  12427. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  12428. continue; // 不中断,继续处理其他场景
  12429. }
  12430. $scene['task_id'] = $task_id;
  12431. $scene['task_status'] = 'processing';
  12432. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  12433. 'anime_id' => $anime_id,
  12434. 'episode_number' => $episode_number,
  12435. 'task_id' => $task_id
  12436. ]);
  12437. } catch (\Exception $e) {
  12438. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  12439. // 不抛出异常,继续处理其他场景
  12440. }
  12441. }
  12442. // 处理道具图片生成(逻辑与场景一致)
  12443. foreach ($props as &$prop) {
  12444. $prop_name = getProp($prop, 'prop');
  12445. $prop_description = getProp($prop, 'description');
  12446. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  12447. $prop_url = getProp($prop, 'url');
  12448. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  12449. if (isset($ref_products[$prop_name])) {
  12450. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  12451. if ($prop['url']) continue;
  12452. }
  12453. // 检查是否可以从上一集继承
  12454. $inherited = false;
  12455. if (!$is_force && !empty($prev_props)) {
  12456. foreach ($prev_props as $prev_prop) {
  12457. $prev_prop_name = getProp($prev_prop, 'prop');
  12458. $prev_description = getProp($prev_prop, 'description');
  12459. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  12460. $prev_url = getProp($prev_prop, 'url');
  12461. $prev_task_id = getProp($prev_prop, 'task_id');
  12462. $prev_task_status = getProp($prev_prop, 'task_status');
  12463. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  12464. if ($prop_name == $prev_prop_name
  12465. && $prop_description == $prev_description
  12466. && $prop_pic_prompt == $prev_pic_prompt
  12467. && !empty($prev_url)) {
  12468. $prop['task_id'] = $prev_task_id;
  12469. $prop['task_status'] = $prev_task_status;
  12470. $prop['url'] = $prev_url;
  12471. $inherited = true;
  12472. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  12473. 'anime_id' => $anime_id,
  12474. 'episode_number' => $episode_number,
  12475. 'task_id' => $prev_task_id,
  12476. 'url' => $prev_url
  12477. ]);
  12478. break;
  12479. }
  12480. }
  12481. }
  12482. // 如果已继承或已有url,跳过生成
  12483. if ($inherited || (!$is_force && $prop_url)) {
  12484. continue;
  12485. }
  12486. // 优先使用 pic_prompt,如果没有则使用 description
  12487. $pic_prompt = getProp($prop, 'pic_prompt');
  12488. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  12489. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  12490. $update_flag = true;
  12491. // 调用AIImageGenerationService的生成图片任务接口
  12492. try {
  12493. $params = [
  12494. 'prompt' => $description,
  12495. 'ref_img_urls' => []
  12496. ];
  12497. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12498. $task_id = $task->id;
  12499. if (!$task_id) {
  12500. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  12501. continue; // 不中断,继续处理其他道具
  12502. }
  12503. $prop['task_id'] = $task_id;
  12504. $prop['task_status'] = 'processing';
  12505. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  12506. 'anime_id' => $anime_id,
  12507. 'episode_number' => $episode_number,
  12508. 'task_id' => $task_id
  12509. ]);
  12510. } catch (\Exception $e) {
  12511. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  12512. // 不抛出异常,继续处理其他道具
  12513. }
  12514. }
  12515. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  12516. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  12517. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  12518. // // 保存剧集的角色和场景信息
  12519. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  12520. // 'roles' => json_encode($roles, 256),
  12521. // 'scenes' => json_encode($scenes, 256),
  12522. // 'generate_status' => '执行中',
  12523. // 'generate_at' => date('Y-m-d H:i:s'),
  12524. // 'updated_at' => date('Y-m-d H:i:s')
  12525. // ]);
  12526. // if (!$boolen) {
  12527. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  12528. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  12529. // }
  12530. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  12531. // 'episode_id' => $episode_id,
  12532. 'roles_count' => count($roles),
  12533. 'scenes_count' => count($scenes),
  12534. 'props_count' => count($props)
  12535. ]);
  12536. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  12537. }
  12538. /**
  12539. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  12540. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  12541. *
  12542. * @param int $anime_id 动漫对话ID
  12543. * @param array $episode_roles 剧集角色数据
  12544. * @param array $episode_scenes 剧集场景数据
  12545. * @param array $episode_props 剧集道具数据
  12546. * @return bool
  12547. */
  12548. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  12549. // 获取全局数据
  12550. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12551. if (!$anime) {
  12552. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  12553. return false;
  12554. }
  12555. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  12556. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  12557. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  12558. $roles_added = false;
  12559. $roles_updated = false;
  12560. $scenes_added = false;
  12561. $props_added = false;
  12562. // 处理角色同步
  12563. foreach ($episode_roles as $episode_role) {
  12564. $episode_role_name = getProp($episode_role, 'role');
  12565. $episode_description = getProp($episode_role, 'description');
  12566. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  12567. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  12568. // 跳过旁白
  12569. if ($episode_role_name == '旁白') {
  12570. continue;
  12571. }
  12572. // 检查全局中是否已存在相同的角色
  12573. $exists = false;
  12574. $global_role_index = -1;
  12575. foreach ($global_roles as $index => $global_role) {
  12576. $global_role_name = getProp($global_role, 'role');
  12577. $global_description = getProp($global_role, 'description');
  12578. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  12579. // 如果role、description、pic_prompt三项都一致,则认为已存在
  12580. if ($episode_role_name == $global_role_name
  12581. && $episode_description == $global_description
  12582. && $episode_pic_prompt == $global_pic_prompt) {
  12583. $exists = true;
  12584. $global_role_index = $index;
  12585. break;
  12586. }
  12587. }
  12588. // 如果不存在,则添加到全局
  12589. if (!$exists) {
  12590. $global_roles[] = $episode_role;
  12591. $roles_added = true;
  12592. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  12593. 'anime_id' => $anime_id,
  12594. 'role' => $episode_role_name
  12595. ]);
  12596. } else {
  12597. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  12598. if (!empty($episode_voice_prompt)) {
  12599. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  12600. // 如果全局没有voice_prompt或与剧集不一致,则更新
  12601. if ($global_voice_prompt !== $episode_voice_prompt) {
  12602. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  12603. $roles_updated = true;
  12604. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  12605. 'anime_id' => $anime_id,
  12606. 'role' => $episode_role_name,
  12607. 'voice_prompt' => $episode_voice_prompt
  12608. ]);
  12609. }
  12610. }
  12611. }
  12612. }
  12613. // 处理场景同步
  12614. foreach ($episode_scenes as $episode_scene) {
  12615. $episode_scene_name = getProp($episode_scene, 'scene');
  12616. $episode_description = getProp($episode_scene, 'description');
  12617. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  12618. // 检查全局中是否已存在相同的场景
  12619. $exists = false;
  12620. foreach ($global_scenes as $global_scene) {
  12621. $global_scene_name = getProp($global_scene, 'scene');
  12622. $global_description = getProp($global_scene, 'description');
  12623. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  12624. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  12625. if ($episode_scene_name == $global_scene_name
  12626. && $episode_description == $global_description
  12627. && $episode_pic_prompt == $global_pic_prompt) {
  12628. $exists = true;
  12629. break;
  12630. }
  12631. }
  12632. // 如果不存在,则添加到全局
  12633. if (!$exists) {
  12634. $global_scenes[] = $episode_scene;
  12635. $scenes_added = true;
  12636. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  12637. 'anime_id' => $anime_id,
  12638. 'scene' => $episode_scene_name
  12639. ]);
  12640. }
  12641. }
  12642. // 处理道具同步(逻辑与场景一致)
  12643. foreach ($episode_props as $episode_prop) {
  12644. $episode_prop_name = getProp($episode_prop, 'prop');
  12645. $episode_description = getProp($episode_prop, 'description');
  12646. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  12647. // 检查全局中是否已存在相同的道具
  12648. $exists = false;
  12649. foreach ($global_props as $global_prop) {
  12650. $global_prop_name = getProp($global_prop, 'prop');
  12651. $global_description = getProp($global_prop, 'description');
  12652. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  12653. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  12654. if ($episode_prop_name == $global_prop_name
  12655. && $episode_description == $global_description
  12656. && $episode_pic_prompt == $global_pic_prompt) {
  12657. $exists = true;
  12658. break;
  12659. }
  12660. }
  12661. // 如果不存在,则添加到全局
  12662. if (!$exists) {
  12663. $global_props[] = $episode_prop;
  12664. $props_added = true;
  12665. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  12666. 'anime_id' => $anime_id,
  12667. 'prop' => $episode_prop_name
  12668. ]);
  12669. }
  12670. }
  12671. // 如果有新增或更新,则更新全局数据
  12672. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  12673. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  12674. if ($roles_added || $roles_updated) {
  12675. $update_data['roles'] = json_encode($global_roles, 256);
  12676. }
  12677. if ($scenes_added) {
  12678. $update_data['scenes'] = json_encode($global_scenes, 256);
  12679. }
  12680. if ($props_added) {
  12681. $update_data['props'] = json_encode($global_props, 256);
  12682. }
  12683. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  12684. dLog('deepseek')->info('剧集数据同步到全局完成', [
  12685. 'anime_id' => $anime_id,
  12686. 'roles_added' => $roles_added,
  12687. 'roles_updated' => $roles_updated,
  12688. 'scenes_added' => $scenes_added,
  12689. 'props_added' => $props_added,
  12690. 'global_roles_count' => count($global_roles),
  12691. 'global_scenes_count' => count($global_scenes),
  12692. 'global_props_count' => count($global_props)
  12693. ]);
  12694. }
  12695. return true;
  12696. }
  12697. /**
  12698. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  12699. *
  12700. * @param int $anime_id 动漫对话ID
  12701. * @param int $episode_id 分集ID
  12702. * @return bool
  12703. */
  12704. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  12705. // 获取全局角色和场景数据
  12706. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12707. if (!$anime) {
  12708. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  12709. return false;
  12710. }
  12711. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  12712. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  12713. // 获取指定的分集
  12714. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  12715. if (!$episode) {
  12716. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  12717. return false;
  12718. }
  12719. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  12720. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  12721. $roles_updated = false;
  12722. $scenes_updated = false;
  12723. // 继承角色的task_id、task_status和url
  12724. foreach ($episode_roles as &$episode_role) {
  12725. $episode_role_name = getProp($episode_role, 'role');
  12726. $episode_description = getProp($episode_role, 'description');
  12727. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  12728. $episode_url = getProp($episode_role, 'url');
  12729. // 跳过旁白角色
  12730. if ($episode_role_name == '旁白') {
  12731. continue;
  12732. }
  12733. // 如果剧集中已有URL,跳过
  12734. if (!empty($episode_url)) {
  12735. continue;
  12736. }
  12737. // 遍历全局角色数据,查找匹配的角色
  12738. foreach ($global_roles as $global_role) {
  12739. $global_role_name = getProp($global_role, 'role');
  12740. $global_description = getProp($global_role, 'description');
  12741. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  12742. $global_url = getProp($global_role, 'url');
  12743. $global_task_id = getProp($global_role, 'task_id');
  12744. $global_task_status = getProp($global_role, 'task_status');
  12745. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  12746. if ($episode_role_name == $global_role_name
  12747. && $episode_description == $global_description
  12748. && $episode_pic_prompt == $global_pic_prompt) {
  12749. // 继承 task_id、task_status 和 url
  12750. if (!empty($global_task_id)) {
  12751. $episode_role['task_id'] = $global_task_id;
  12752. $episode_role['task_status'] = $global_task_status;
  12753. $roles_updated = true;
  12754. dLog('deepseek')->info('剧集角色继承全局task_id', [
  12755. 'episode_id' => $episode_id,
  12756. 'role' => $episode_role_name,
  12757. 'task_id' => $global_task_id,
  12758. 'task_status' => $global_task_status
  12759. ]);
  12760. }
  12761. if (!empty($global_url)) {
  12762. $episode_role['url'] = $global_url;
  12763. $roles_updated = true;
  12764. dLog('deepseek')->info('剧集角色继承全局url', [
  12765. 'episode_id' => $episode_id,
  12766. 'role' => $episode_role_name,
  12767. 'url' => $global_url
  12768. ]);
  12769. }
  12770. break;
  12771. }
  12772. }
  12773. }
  12774. // 继承场景的task_id、task_status和url
  12775. foreach ($episode_scenes as &$episode_scene) {
  12776. $episode_scene_name = getProp($episode_scene, 'scene');
  12777. $episode_description = getProp($episode_scene, 'description');
  12778. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  12779. $episode_url = getProp($episode_scene, 'url');
  12780. // 如果剧集中已有URL,跳过
  12781. if (!empty($episode_url)) {
  12782. continue;
  12783. }
  12784. // 遍历全局场景数据,查找匹配的场景
  12785. foreach ($global_scenes as $global_scene) {
  12786. $global_scene_name = getProp($global_scene, 'scene');
  12787. $global_description = getProp($global_scene, 'description');
  12788. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  12789. $global_url = getProp($global_scene, 'url');
  12790. $global_task_id = getProp($global_scene, 'task_id');
  12791. $global_task_status = getProp($global_scene, 'task_status');
  12792. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  12793. if ($episode_scene_name == $global_scene_name
  12794. && $episode_description == $global_description
  12795. && $episode_pic_prompt == $global_pic_prompt) {
  12796. // 继承 task_id、task_status 和 url
  12797. if (!empty($global_task_id)) {
  12798. $episode_scene['task_id'] = $global_task_id;
  12799. $episode_scene['task_status'] = $global_task_status;
  12800. $scenes_updated = true;
  12801. dLog('deepseek')->info('剧集场景继承全局task_id', [
  12802. 'episode_id' => $episode_id,
  12803. 'scene' => $episode_scene_name,
  12804. 'task_id' => $global_task_id,
  12805. 'task_status' => $global_task_status
  12806. ]);
  12807. }
  12808. if (!empty($global_url)) {
  12809. $episode_scene['url'] = $global_url;
  12810. $scenes_updated = true;
  12811. dLog('deepseek')->info('剧集场景继承全局url', [
  12812. 'episode_id' => $episode_id,
  12813. 'scene' => $episode_scene_name,
  12814. 'url' => $global_url
  12815. ]);
  12816. }
  12817. break;
  12818. }
  12819. }
  12820. }
  12821. // 如果有更新,则保存到数据库
  12822. if ($roles_updated || $scenes_updated) {
  12823. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  12824. if ($roles_updated) {
  12825. $update_data['roles'] = json_encode($episode_roles, 256);
  12826. }
  12827. if ($scenes_updated) {
  12828. $update_data['scenes'] = json_encode($episode_scenes, 256);
  12829. }
  12830. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  12831. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  12832. 'episode_id' => $episode_id,
  12833. 'roles_updated' => $roles_updated,
  12834. 'scenes_updated' => $scenes_updated
  12835. ]);
  12836. }
  12837. return true;
  12838. }
  12839. public function chatChangeImg($data) {
  12840. $segment = getProp($data, 'segment');
  12841. $segment_content = getProp($segment, 'segment_content');
  12842. $prompt = getProp($data, 'prompt');
  12843. $ref_img = getProp($data, 'ref_img');
  12844. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  12845. // 处理文本模型
  12846. $model = getProp($data, 'model');
  12847. if (!$model) {
  12848. // 用户没有输入,从anime表获取
  12849. $segment_id = getProp($segment, 'segment_id');
  12850. if ($segment_id) {
  12851. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  12852. if ($episode_id) {
  12853. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  12854. if ($anime_id) {
  12855. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  12856. }
  12857. }
  12858. }
  12859. if (!$model) {
  12860. // anime表也没有,使用默认值
  12861. $model = 'doubao-seed-2-0-mini-260215';
  12862. }
  12863. }
  12864. // 验证模型是否在可用模型表中
  12865. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  12866. $model = 'doubao-seed-2-0-mini-260215';
  12867. }
  12868. $messages[] =
  12869. [
  12870. 'role' => 'user',
  12871. 'content' => $question
  12872. ];
  12873. $post_data = [
  12874. 'model' => $model,
  12875. 'messages' => $messages,
  12876. // 'max_tokens' => 8192,
  12877. 'temperature' => 0.7,
  12878. 'frequency_penalty' => 0,
  12879. 'presence_penalty' => 0,
  12880. 'response_format' => ['type' => 'text'],
  12881. 'stream' => false // 是否启用流式输出
  12882. ];
  12883. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  12884. // DeepSeek 官方模型使用 DeepSeek API
  12885. $chatResult = $this->chatOnly($post_data);
  12886. } else if (in_array($model, $this->gpt_text_models)) {
  12887. // GPT-5.4 模型使用 TokenRouter API
  12888. $chatResult = $this->gpt54ChatOnly($post_data);
  12889. } else {
  12890. // 其他模型使用火山引擎API
  12891. $chatResult = $this->volcEngineChatCompletion($post_data);
  12892. }
  12893. if (is_array($chatResult)) {
  12894. extract($chatResult);
  12895. }else {
  12896. Utils::throwError('20003: 接口调用失败!');
  12897. }
  12898. // 仅记录 token 使用明细(不扣积分)
  12899. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  12900. 'model' => $model,
  12901. 'source' => 'chatChangeImg',
  12902. ], $model);
  12903. return [
  12904. 'type' => 'done',
  12905. // 'episode' => $episode,
  12906. 'answer' => $fullContent,
  12907. 'reasoning' => $fullReasoningContent,
  12908. 'usage' => $usage
  12909. ];
  12910. }
  12911. /**
  12912. * 仅调用 deepseek 对话接口(非流式)
  12913. *
  12914. * @param array $post_data
  12915. * @param int $timeout
  12916. * @return array
  12917. */
  12918. private function chatOnly($post_data, $timeout = 1800) {
  12919. $post_data['max_tokens'] = 300000;
  12920. $client = new Client(['timeout' => $timeout, 'verify' => false]);
  12921. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  12922. $response = $result->getBody()->getContents();
  12923. $response_arr = json_decode($response, true);
  12924. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  12925. $fullContent = '';
  12926. $fullReasoningContent = [];
  12927. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  12928. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  12929. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  12930. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  12931. }
  12932. return [
  12933. 'fullContent' => $fullContent,
  12934. 'fullReasoningContent' => $fullReasoningContent,
  12935. 'usage' => $usage
  12936. ];
  12937. }
  12938. /**
  12939. * 用 deepseek-v4-flash 非流式分析报错,返回不超过50字的用户友好提示
  12940. *
  12941. * @param string $errorMessage
  12942. * @return string|null
  12943. */
  12944. public function analyzeErrorMessage($errorMessage)
  12945. {
  12946. try {
  12947. $post_data = [
  12948. 'model' => 'deepseek-v4-flash',
  12949. 'messages' => [
  12950. [
  12951. 'role' => 'system',
  12952. 'content' => '你是视频生成任务的报错分析助手。请根据用户给出的原始报错,用一句中文提示告诉用户问题原因和下一步怎么做,不超过50个字,直接输出提示内容,不要解释、不要输出代码。',
  12953. ],
  12954. [
  12955. 'role' => 'user',
  12956. 'content' => (string)$errorMessage,
  12957. ],
  12958. ],
  12959. 'temperature' => 0.3,
  12960. 'frequency_penalty' => 0,
  12961. 'presence_penalty' => 0,
  12962. 'response_format' => ['type' => 'text'],
  12963. 'stream' => false,
  12964. ];
  12965. $result = $this->chatOnly($post_data, 8);
  12966. // 调用成功即记录 token 使用明细(不扣积分),保证错误分析这类隐性 AI 调用进入统计口径
  12967. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  12968. 'model' => 'deepseek-v4-flash',
  12969. 'source' => 'analyzeErrorMessage',
  12970. ], 'deepseek-v4-flash');
  12971. $content = trim((string)($result['fullContent'] ?? ''));
  12972. if ($content === '') {
  12973. return null;
  12974. }
  12975. return mb_substr($content, 0, 50);
  12976. } catch (\Exception $e) {
  12977. dLog('deepseek')->error('视频任务报错分析失败: ' . $e->getMessage(), [
  12978. 'error_message' => $errorMessage
  12979. ]);
  12980. return null;
  12981. }
  12982. }
  12983. // 仅调用 GPT-5.4 对话接口(非流式)
  12984. private function gpt54ChatOnly($post_data) {
  12985. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  12986. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  12987. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  12988. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  12989. $usedLunaFallback = false;
  12990. if (empty($apiKey)) {
  12991. Utils::throwError('20003:GPT-5.4 API Key未配置');
  12992. }
  12993. // 先探活,服务不可用时自动重试
  12994. $this->ensureGptServiceAvailable($apiKey);
  12995. $client = new Client(['timeout' => 1800, 'verify' => false]);
  12996. // 移除 thinking 参数,GPT-5.4 不支持
  12997. if (isset($post_data['thinking'])) {
  12998. unset($post_data['thinking']);
  12999. }
  13000. if (isset($post_data['reasoning_effort'])) {
  13001. unset($post_data['reasoning_effort']);
  13002. }
  13003. $post_data['max_completion_tokens'] = 100000;
  13004. // 确保 stream 为 false
  13005. $post_data['stream'] = false;
  13006. $maxRetries = $this->gptRetryTimes();
  13007. $interval = $this->gptRetryInterval();
  13008. $attempt = 0;
  13009. while (true) {
  13010. try {
  13011. $headers = [
  13012. 'Authorization' => 'Bearer ' . $apiKey,
  13013. 'Content-Type' => 'application/json'
  13014. ];
  13015. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  13016. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  13017. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  13018. 'json' => $post_data,
  13019. 'headers' => $headers
  13020. ]);
  13021. $response = $result->getBody()->getContents();
  13022. $response_arr = json_decode($response, true);
  13023. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  13024. $fullContent = '';
  13025. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  13026. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  13027. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  13028. }
  13029. return [
  13030. 'fullContent' => $fullContent,
  13031. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  13032. 'usage' => $usage
  13033. ];
  13034. } catch (\Exception $e) {
  13035. // 报错或超时时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  13036. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  13037. $usedLunaFallback = true;
  13038. $apiKey = $lunaApiKey;
  13039. dLog('deepseek')->warning('GPT-5.4 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  13040. continue;
  13041. }
  13042. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  13043. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  13044. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  13045. throw $e;
  13046. }
  13047. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  13048. 'retry' => $attempt + 1,
  13049. 'max_retries' => $maxRetries,
  13050. 'error' => $e->getMessage()
  13051. ]);
  13052. sleep($interval);
  13053. $attempt++;
  13054. }
  13055. }
  13056. }
  13057. public function getContentByBid($bid) {
  13058. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  13059. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  13060. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  13061. $content = '';
  13062. foreach ($chapters as $chapter) {
  13063. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  13064. }
  13065. return $content;
  13066. }
  13067. public function getContentByScriptId($script_id) {
  13068. $content = '';
  13069. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  13070. if ($contents) {
  13071. $content = implode(PHP_EOL, $contents);
  13072. }else {
  13073. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  13074. }
  13075. return $content;
  13076. }
  13077. /**
  13078. * 根据文件类型提取文本内容
  13079. *
  13080. * @param mixed $file 文件对象或文件路径
  13081. * @return string
  13082. */
  13083. public function extractFileContent($file) {
  13084. // 获取文件路径和扩展名
  13085. if (is_string($file)) {
  13086. $filePath = $file;
  13087. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  13088. } else {
  13089. // Laravel UploadedFile 对象
  13090. $filePath = $file->getRealPath();
  13091. $extension = strtolower($file->getClientOriginalExtension());
  13092. }
  13093. $content = '';
  13094. switch ($extension) {
  13095. case 'txt':
  13096. $content = $this->extractTxtContent($filePath);
  13097. break;
  13098. case 'pdf':
  13099. $content = $this->extractPdfContent($filePath);
  13100. break;
  13101. case 'doc':
  13102. case 'docx':
  13103. $content = $this->extractWordContent($filePath);
  13104. break;
  13105. // case 'jpg':
  13106. // case 'jpeg':
  13107. // case 'png':
  13108. // case 'gif':
  13109. // case 'bmp':
  13110. // case 'webp':
  13111. // $content = $this->extractImageContent($filePath);
  13112. // break;
  13113. default:
  13114. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  13115. }
  13116. // 移除非法 UTF-8 字节,避免后续 JSON 编码或正则解析异常
  13117. if (!mb_check_encoding($content, 'UTF-8')) {
  13118. $cleaned = @iconv('UTF-8', 'UTF-8//IGNORE', $content);
  13119. $content = $cleaned === false ? $content : $cleaned;
  13120. }
  13121. return $content;
  13122. }
  13123. /**
  13124. * 提取 TXT 文件内容
  13125. */
  13126. private function extractTxtContent($filePath) {
  13127. if (!file_exists($filePath)) {
  13128. Utils::throwError('20003:文件不存在');
  13129. }
  13130. $content = file_get_contents($filePath);
  13131. // 尝试检测并转换编码
  13132. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  13133. if ($encoding && $encoding !== 'UTF-8') {
  13134. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  13135. }
  13136. return trim($content);
  13137. }
  13138. /**
  13139. * 提取 PDF 文件内容
  13140. */
  13141. private function extractPdfContent($filePath) {
  13142. if (!file_exists($filePath)) {
  13143. Utils::throwError('20003:文件不存在');
  13144. }
  13145. try {
  13146. $parser = new PdfParser();
  13147. $pdf = $parser->parseFile($filePath);
  13148. $content = $pdf->getText();
  13149. return trim($content);
  13150. } catch (\Exception $e) {
  13151. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  13152. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  13153. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  13154. }
  13155. }
  13156. /**
  13157. * 提取 Word 文件内容(支持 doc 和 docx)
  13158. */
  13159. private function extractWordContent($filePath) {
  13160. if (!file_exists($filePath)) {
  13161. Utils::throwError('20003:文件不存在');
  13162. }
  13163. try {
  13164. $phpWord = WordIOFactory::load($filePath);
  13165. $content = '';
  13166. foreach ($phpWord->getSections() as $section) {
  13167. foreach ($section->getElements() as $element) {
  13168. $content .= $this->extractWordElementText($element);
  13169. }
  13170. }
  13171. return trim($content);
  13172. } catch (\Exception $e) {
  13173. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  13174. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  13175. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  13176. }
  13177. }
  13178. /**
  13179. * 递归提取 Word 元素中的文本
  13180. */
  13181. private function extractWordElementText($element) {
  13182. $text = '';
  13183. if (method_exists($element, 'getText')) {
  13184. $text .= $element->getText() . "\n";
  13185. } elseif (method_exists($element, 'getElements')) {
  13186. foreach ($element->getElements() as $childElement) {
  13187. $text .= $this->extractWordElementText($childElement);
  13188. }
  13189. }
  13190. return $text;
  13191. }
  13192. /**
  13193. * 提取图片内容(使用火山引擎 OCR)
  13194. */
  13195. private function extractImageContent($filePath) {
  13196. if (!file_exists($filePath)) {
  13197. Utils::throwError('20003:文件不存在');
  13198. }
  13199. try {
  13200. // 读取图片并转换为 base64
  13201. $imageData = file_get_contents($filePath);
  13202. $base64Image = base64_encode($imageData);
  13203. // 调用火山引擎 OCR 服务
  13204. $content = $this->callVolcEngineOCR($base64Image);
  13205. return trim($content);
  13206. } catch (\Exception $e) {
  13207. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  13208. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  13209. Utils::throwError('20003:图片识别失败');
  13210. }
  13211. }
  13212. /**
  13213. * 调用火山引擎 OCR 服务识别图片文字
  13214. *
  13215. * @param string $base64Image base64 编码的图片数据
  13216. * @return string 识别的文字内容
  13217. */
  13218. private function callVolcEngineOCR($base64Image) {
  13219. $method = 'POST';
  13220. $service = 'cv';
  13221. $host = 'visual.volcengineapi.com';
  13222. $region = env('VOLC_REGION', 'cn-north-1');
  13223. $access_key = env('VOLC_AK');
  13224. $secret_key = env('VOLC_SK');
  13225. $action = 'OCRNormal';
  13226. $version = '2020-08-26';
  13227. if (!$access_key || !$secret_key) {
  13228. Utils::throwError('20003:请配置火山引擎 AK/SK');
  13229. }
  13230. // 请求体
  13231. $body = json_encode([
  13232. 'image_base64' => $base64Image
  13233. ]);
  13234. // 生成签名
  13235. $headers = $this->getVolcEngineSignHeaders(
  13236. $method, $service, $host, $region,
  13237. "Action={$action}&Version={$version}",
  13238. $access_key, $secret_key, $body
  13239. );
  13240. $client = new Client(['timeout' => 1800, 'verify' => false]);
  13241. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  13242. 'headers' => $headers,
  13243. 'body' => $body
  13244. ]);
  13245. $response_arr = json_decode($response->getBody()->getContents(), true);
  13246. // 提取识别的文字
  13247. $textLines = [];
  13248. if (isset($response_arr['data']['line_texts'])) {
  13249. $textLines = $response_arr['data']['line_texts'];
  13250. } elseif (isset($response_arr['data']['ocr_infos'])) {
  13251. foreach ($response_arr['data']['ocr_infos'] as $info) {
  13252. if (isset($info['text'])) {
  13253. $textLines[] = $info['text'];
  13254. }
  13255. }
  13256. }
  13257. if (empty($textLines)) {
  13258. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  13259. return '';
  13260. }
  13261. return implode("\n", $textLines);
  13262. }
  13263. /**
  13264. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  13265. */
  13266. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  13267. $contentType = 'application/json';
  13268. $accept = 'application/json';
  13269. // 获取当前UTC时间
  13270. $t = new DateTime('now', new DateTimeZone('UTC'));
  13271. $xDate = $t->format('Ymd\THis\Z');
  13272. $dateStamp = $t->format('Ymd');
  13273. // 计算 body 的 sha256 哈希
  13274. $payloadHash = hash('sha256', $body);
  13275. // 1. 拼接规范请求串
  13276. $canonicalUri = '/';
  13277. $canonicalQueryString = $queryString;
  13278. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  13279. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  13280. $canonicalRequest = implode("\n", [
  13281. $method,
  13282. $canonicalUri,
  13283. $canonicalQueryString,
  13284. $canonicalHeaders,
  13285. $signedHeaders,
  13286. $payloadHash
  13287. ]);
  13288. // 2. 拼接待签名字符串
  13289. $algorithm = 'HMAC-SHA256';
  13290. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  13291. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  13292. $stringToSign = implode("\n", [
  13293. $algorithm,
  13294. $xDate,
  13295. $credentialScope,
  13296. $hashedCanonicalRequest
  13297. ]);
  13298. // 3. 计算签名
  13299. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  13300. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  13301. // 4. 添加签名到请求头
  13302. $authorizationHeader = sprintf(
  13303. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  13304. $algorithm,
  13305. $access_key,
  13306. $credentialScope,
  13307. $signedHeaders,
  13308. $signature
  13309. );
  13310. return [
  13311. 'Accept' => $accept,
  13312. 'Content-Type' => $contentType,
  13313. 'Host' => $host,
  13314. 'X-Date' => $xDate,
  13315. 'X-Content-Sha256'=> $payloadHash,
  13316. 'Authorization' => $authorizationHeader
  13317. ];
  13318. }
  13319. public function generateScriptWords($cid, $model = 'r1') {
  13320. ini_set('max_execution_time', 0);
  13321. if (!$cid) Utils::throwError('20003: 请选择章节!');
  13322. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  13323. // 模型兼容性处理和思考模式设置
  13324. $thinkingMode = 'disabled';
  13325. $reasoningEffort = 'high';
  13326. if ($model == 'r1') {
  13327. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  13328. $thinkingMode = 'enabled';
  13329. } else {
  13330. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  13331. $thinkingMode = 'disabled';
  13332. }
  13333. $messages = [
  13334. [
  13335. 'role' => 'system',
  13336. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  13337. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  13338. 2.非对话部分请全部用旁白角色代替
  13339. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  13340. ],
  13341. [
  13342. 'role' => 'user',
  13343. 'content' => $content
  13344. ]
  13345. ];
  13346. $post_data = [
  13347. 'model' => $model,
  13348. 'messages' => $messages,
  13349. // 'max_tokens' => 8192,
  13350. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  13351. 'frequency_penalty' => 0,
  13352. 'presence_penalty' => 0,
  13353. 'thinking' => ['type' => $thinkingMode],
  13354. 'response_format' => [
  13355. 'type' => 'text'
  13356. ],
  13357. 'stream' => false
  13358. ];
  13359. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  13360. // 根据模型类型选择调用方法
  13361. $fullContent = '';
  13362. $usage = [];
  13363. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  13364. // DeepSeek 官方模型使用 DeepSeek API
  13365. $chatResult = $this->chatOnly($post_data);
  13366. } else if (in_array($model, $this->gpt_text_models)) {
  13367. // GPT-5.4 模型使用 TokenRouter API
  13368. $chatResult = $this->gpt54ChatOnly($post_data);
  13369. } else {
  13370. // 其他模型使用火山引擎API
  13371. $chatResult = $this->volcEngineChatCompletion($post_data);
  13372. }
  13373. if (is_array($chatResult)) {
  13374. $fullContent = $chatResult['fullContent'];
  13375. $usage = $chatResult['usage'] ?? [];
  13376. }
  13377. // 仅记录 token 使用明细(不扣积分)
  13378. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  13379. 'model' => $model,
  13380. 'cid' => $cid,
  13381. 'source' => 'generateScriptWords',
  13382. ], $model);
  13383. return $fullContent;
  13384. }
  13385. /**
  13386. * 智能化解析集数信息
  13387. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  13388. *
  13389. * @param string $prompt 用户输入的提示词
  13390. * @return int|null 解析出的集数,如果没有找到则返回null
  13391. */
  13392. private function extractEpisodeNumber($prompt)
  13393. {
  13394. if (empty($prompt)) {
  13395. return null;
  13396. }
  13397. // 定义各种可能的表达模式
  13398. $patterns = [
  13399. // 基本模式:改成N集、调整成N集、修改成N集
  13400. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  13401. // 扩展模式:分成N集、拆分成N集、分割成N集
  13402. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  13403. // 数量模式:N集、共N集、总共N集
  13404. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  13405. // 制作模式:制作N集、生成N集、创建N集
  13406. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  13407. // 计划模式:计划N集、预计N集、打算N集
  13408. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  13409. // 需要模式:需要N集、要N集
  13410. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  13411. // 中文数字模式:改成三集、调整成五集等
  13412. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  13413. // 英文数字模式
  13414. '/(?: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',
  13415. ];
  13416. // 中文数字转阿拉伯数字的映射
  13417. $chineseNumbers = [
  13418. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  13419. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  13420. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  13421. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  13422. ];
  13423. // 逐个尝试匹配模式
  13424. foreach ($patterns as $pattern) {
  13425. if (preg_match($pattern, $prompt, $matches)) {
  13426. $number = trim($matches[1]);
  13427. // 如果是中文数字,转换为阿拉伯数字
  13428. if (isset($chineseNumbers[$number])) {
  13429. return $chineseNumbers[$number];
  13430. }
  13431. // 如果是阿拉伯数字,直接返回
  13432. if (is_numeric($number)) {
  13433. $episodeNum = intval($number);
  13434. // 合理性检查:集数应该在1-100之间
  13435. if ($episodeNum >= 1 && $episodeNum <= 100) {
  13436. return $episodeNum;
  13437. }
  13438. }
  13439. }
  13440. }
  13441. return null;
  13442. }
  13443. /**
  13444. * 调用火山引擎对话(Chat) API
  13445. *
  13446. * @param array $params 包含以下参数:
  13447. * - model: 模型ID(必填)
  13448. * - messages: 消息列表(必填)
  13449. * - stream: 是否流式输出(可选,默认false)
  13450. * - max_tokens: 最大输出token数(可选)
  13451. * - temperature: 采样温度(可选,默认1)
  13452. * - top_p: 核采样概率(可选,默认0.7)
  13453. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  13454. * - presence_penalty: 存在惩罚系数(可选,默认0)
  13455. * - stop: 停止词(可选)
  13456. * - tools: 工具列表(可选)
  13457. * @return array|Generator 非流式返回数组,流式返回生成器
  13458. */
  13459. public function volcEngineChatCompletion(array $params)
  13460. {
  13461. $apiKey = env('VOLC_AI_API_KEY');
  13462. if (empty($apiKey)) {
  13463. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  13464. }
  13465. // 构建请求参数
  13466. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  13467. $requestData = [
  13468. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  13469. 'messages' => $params['messages'] ?? [],
  13470. ];
  13471. if (!in_array($originalModel, $this->valid_text_models)) {
  13472. Utils::throwError('20003:该模型不支持!');
  13473. }
  13474. // 添加可选参数
  13475. if (isset($params['stream'])) {
  13476. $requestData['stream'] = $params['stream'];
  13477. }
  13478. if (isset($params['stream_options'])) {
  13479. $requestData['stream_options'] = $params['stream_options'];
  13480. }
  13481. if (isset($params['max_tokens'])) {
  13482. $requestData['max_tokens'] = $params['max_tokens'];
  13483. }else if (isset($params['max_completion_tokens'])) {
  13484. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  13485. }else {
  13486. $requestData['max_completion_tokens'] = 100000;
  13487. }
  13488. if (isset($params['temperature'])) {
  13489. $requestData['temperature'] = $params['temperature'];
  13490. }
  13491. if (isset($params['top_p'])) {
  13492. $requestData['top_p'] = $params['top_p'];
  13493. }
  13494. if (isset($params['frequency_penalty'])) {
  13495. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  13496. }
  13497. if (isset($params['presence_penalty'])) {
  13498. $requestData['presence_penalty'] = $params['presence_penalty'];
  13499. }
  13500. if (isset($params['stop'])) {
  13501. $requestData['stop'] = $params['stop'];
  13502. }
  13503. if (isset($params['tools'])) {
  13504. $requestData['tools'] = $params['tools'];
  13505. }
  13506. if (isset($params['tool_choice'])) {
  13507. $requestData['tool_choice'] = $params['tool_choice'];
  13508. }
  13509. if (isset($params['response_format'])) {
  13510. $requestData['response_format'] = $params['response_format'];
  13511. }
  13512. if (isset($params['thinking'])) {
  13513. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  13514. if (is_array($params['thinking'])) {
  13515. $requestData['thinking'] = $params['thinking'];
  13516. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  13517. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  13518. }
  13519. } else {
  13520. $requestData['thinking'] = ['type' => $params['thinking']];
  13521. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  13522. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  13523. }
  13524. }
  13525. } else {
  13526. $requestData['thinking'] = ['type' => 'disabled'];
  13527. }
  13528. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  13529. $client = new Client(['verify' => false, 'timeout' => 1800]);
  13530. try {
  13531. // 判断是否为流式输出
  13532. $isStream = isset($params['stream']) && $params['stream'] === true;
  13533. if ($isStream) {
  13534. // 流式输出
  13535. // 流式请求默认声明返回 usage(未显式传参时)
  13536. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  13537. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  13538. } else {
  13539. // 非流式输出
  13540. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  13541. 'headers' => [
  13542. 'Authorization' => 'Bearer ' . $apiKey,
  13543. 'Content-Type' => 'application/json',
  13544. ],
  13545. 'json' => $requestData
  13546. ]);
  13547. $responseData = json_decode($response->getBody(), true);
  13548. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  13549. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  13550. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  13551. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  13552. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  13553. }
  13554. return [
  13555. 'fullContent' => $fullContent,
  13556. 'fullReasoningContent' => $fullReasoningContent,
  13557. 'usage' => $usage
  13558. ];
  13559. }
  13560. } catch (\Exception $e) {
  13561. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  13562. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  13563. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  13564. }
  13565. }
  13566. /**
  13567. * 火山引擎对话API流式输出
  13568. *
  13569. * @param Client $client HTTP客户端
  13570. * @param string $apiKey API密钥
  13571. * @param array $requestData 请求数据
  13572. * @return Generator
  13573. */
  13574. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  13575. {
  13576. try {
  13577. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  13578. 'headers' => [
  13579. 'Authorization' => 'Bearer ' . $apiKey,
  13580. 'Content-Type' => 'application/json',
  13581. ],
  13582. 'json' => $requestData,
  13583. 'stream' => true
  13584. ]);
  13585. $body = $response->getBody();
  13586. $buffer = '';
  13587. $fullContent = '';
  13588. $fullReasoningContent = '';
  13589. $usage = [];
  13590. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  13591. // 逐行读取流式响应
  13592. while (!$body->eof()) {
  13593. $chunk = $body->read(1024);
  13594. $buffer .= $chunk;
  13595. // 按行分割
  13596. $lines = explode("\n", $buffer);
  13597. $buffer = array_pop($lines);
  13598. foreach ($lines as $line) {
  13599. $line = trim($line);
  13600. if (empty($line)) {
  13601. continue;
  13602. }
  13603. // 检查是否是SSE数据行
  13604. if (strpos($line, 'data: ') !== 0) {
  13605. continue;
  13606. }
  13607. $data = substr($line, 6);
  13608. if ($data === '[DONE]') {
  13609. dLog('deepseek')->info('收到结束标记');
  13610. break 2;
  13611. }
  13612. try {
  13613. $json = json_decode($data, true);
  13614. if (json_last_error() !== JSON_ERROR_NONE) {
  13615. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  13616. continue;
  13617. }
  13618. if (isset($json['choices'][0]['delta'])) {
  13619. $delta = $json['choices'][0]['delta'];
  13620. // 处理思维链内容
  13621. if (isset($delta['reasoning_content'])) {
  13622. $fullReasoningContent .= $delta['reasoning_content'];
  13623. yield [
  13624. 'type' => 'reasoning',
  13625. 'content' => $delta['reasoning_content'],
  13626. 'full_reasoning' => $fullReasoningContent
  13627. ];
  13628. }
  13629. // 处理回答内容
  13630. if (isset($delta['content'])) {
  13631. $fullContent .= $delta['content'];
  13632. yield [
  13633. 'type' => 'content',
  13634. 'content' => $delta['content'],
  13635. ];
  13636. }
  13637. }
  13638. // 获取使用统计信息
  13639. if (isset($json['usage'])) {
  13640. $usage = $json['usage'];
  13641. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  13642. }
  13643. } catch (\Exception $e) {
  13644. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  13645. continue;
  13646. }
  13647. }
  13648. }
  13649. dLog('deepseek')->info('流式读取完成', [
  13650. 'content_length' => strlen($fullContent),
  13651. 'reasoning_length' => strlen($fullReasoningContent)
  13652. ]);
  13653. yield [
  13654. 'type' => 'done',
  13655. 'full_content' => $fullContent,
  13656. 'full_reasoning' => $fullReasoningContent,
  13657. 'usage' => $usage
  13658. ];
  13659. } catch (\Exception $e) {
  13660. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  13661. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  13662. throw $e;
  13663. }
  13664. }
  13665. /**
  13666. * 检查并创建图片生成任务
  13667. *
  13668. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  13669. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  13670. * @param string $nameKey 资源名称字段('role' 或 'scene')
  13671. * @param string $art_style 美术风格
  13672. * @return array 更新后的资源列表
  13673. */
  13674. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  13675. {
  13676. // 确保参数为数组
  13677. $merged_items = is_array($merged_items) ? $merged_items : [];
  13678. $global_items = is_array($global_items) ? $global_items : [];
  13679. // 构建全局资源映射表,用于快速查找
  13680. $global_map = [];
  13681. foreach ($global_items as $item) {
  13682. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13683. if ($itemKey === '') {
  13684. continue;
  13685. }
  13686. $global_map[$itemKey] = $item;
  13687. }
  13688. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  13689. foreach ($merged_items as &$item) {
  13690. $item_name = getProp($item, $nameKey);
  13691. $item_description = getProp($item, 'description');
  13692. // $item_url = getProp($item, 'url');
  13693. // // 如果已有图片URL,跳过
  13694. // if (!empty($item_url)) {
  13695. // continue;
  13696. // }
  13697. // 如果是旁白角色,跳过
  13698. if ($nameKey === 'role' && $item_name === '旁白') {
  13699. continue;
  13700. }
  13701. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  13702. if ($itemKey === '') {
  13703. continue;
  13704. }
  13705. $need_create_task = false;
  13706. // 条件1:在全局资源中找不到匹配的名称
  13707. if (!isset($global_map[$itemKey])) {
  13708. $need_create_task = true;
  13709. } else {
  13710. // 条件2:名称匹配但描述或 pic_prompt 不一致
  13711. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  13712. $current_description = trim((string)$item_description);
  13713. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  13714. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  13715. // 如果 description 或 pic_prompt 有变化,需要重新生成
  13716. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  13717. $need_create_task = true;
  13718. }
  13719. }
  13720. // 如果需要创建任务,调用图片生成服务
  13721. if ($need_create_task) {
  13722. try {
  13723. // 优先使用 pic_prompt,如果没有则使用 description
  13724. $pic_prompt = getProp($item, 'pic_prompt');
  13725. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  13726. // 添加美术风格前缀
  13727. if ($art_style) {
  13728. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  13729. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  13730. $description = "{$prefix}:{$description}";
  13731. }
  13732. $params = [
  13733. 'prompt' => $description,
  13734. 'ref_img_urls' => []
  13735. ];
  13736. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13737. $task_id = $task->id;
  13738. if ($task_id) {
  13739. $item['task_id'] = $task_id;
  13740. $item['task_status'] = 'processing';
  13741. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  13742. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  13743. }
  13744. } catch (\Exception $e) {
  13745. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  13746. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  13747. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  13748. // 不抛出异常,继续处理其他资源
  13749. }
  13750. }
  13751. }
  13752. return $merged_items;
  13753. }
  13754. /**
  13755. * 同步新出现的主体和场景到全局
  13756. *
  13757. * @param int $anime_id 动漫ID
  13758. * @param array $merged_roles 合并后的角色列表
  13759. * @param array $merged_scenes 合并后的场景列表
  13760. * @param array $global_roles 全局角色列表
  13761. * @param array $global_scenes 全局场景列表
  13762. * @return void
  13763. */
  13764. private function syncNewResourcesToGlobal(
  13765. int $anime_id,
  13766. array $merged_roles,
  13767. array $merged_scenes,
  13768. array $global_roles,
  13769. array $global_scenes
  13770. ): void {
  13771. // 构建全局角色映射表
  13772. $global_role_map = [];
  13773. foreach ($global_roles as $role) {
  13774. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  13775. if ($roleKey !== '') {
  13776. $global_role_map[$roleKey] = $role;
  13777. }
  13778. }
  13779. // 构建全局场景映射表
  13780. $global_scene_map = [];
  13781. foreach ($global_scenes as $scene) {
  13782. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  13783. if ($sceneKey !== '') {
  13784. $global_scene_map[$sceneKey] = $scene;
  13785. }
  13786. }
  13787. $need_update = false;
  13788. $new_global_roles = $global_roles;
  13789. $new_global_scenes = $global_scenes;
  13790. // 检查并添加新角色到全局
  13791. foreach ($merged_roles as $role) {
  13792. $role_name = getProp($role, 'role');
  13793. // 跳过旁白
  13794. if ($role_name === '旁白') {
  13795. continue;
  13796. }
  13797. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  13798. if ($roleKey === '') {
  13799. continue;
  13800. }
  13801. // 如果全局中不存在该角色,添加到全局
  13802. if (!isset($global_role_map[$roleKey])) {
  13803. $new_global_roles[] = [
  13804. 'role' => $role_name,
  13805. 'description' => getProp($role, 'description', ''),
  13806. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  13807. 'voice_name' => getProp($role, 'voice_name', ''),
  13808. 'voice_type' => getProp($role, 'voice_type', ''),
  13809. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  13810. 'url' => getProp($role, 'url', ''),
  13811. 'task_id' => getProp($role, 'task_id', ''),
  13812. 'task_status' => getProp($role, 'task_status', ''),
  13813. ];
  13814. $global_role_map[$roleKey] = true; // 标记已添加
  13815. $need_update = true;
  13816. dLog('deepseek')->info("新角色同步到全局", [
  13817. 'anime_id' => $anime_id,
  13818. 'role' => $role_name,
  13819. 'task_id' => getProp($role, 'task_id', ''),
  13820. ]);
  13821. }
  13822. // else {
  13823. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  13824. // $global_role = $global_role_map[$roleKey];
  13825. // if (is_array($global_role)) {
  13826. // $updated = false;
  13827. // $update_fields = [];
  13828. // // 检查描述是否更新
  13829. // $current_description = trim((string)getProp($role, 'description'));
  13830. // $global_description = trim((string)getProp($global_role, 'description'));
  13831. // if ($current_description !== '' && $current_description !== $global_description) {
  13832. // $updated = true;
  13833. // $update_fields[] = 'description';
  13834. // }
  13835. // // 检查pic_prompt是否更新
  13836. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  13837. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  13838. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  13839. // $updated = true;
  13840. // $update_fields[] = 'pic_prompt';
  13841. // }
  13842. // // 检查图片任务信息是否更新
  13843. // $current_task_id = getProp($role, 'task_id');
  13844. // $global_task_id = getProp($global_role, 'task_id');
  13845. // if ($current_task_id && $current_task_id !== $global_task_id) {
  13846. // $updated = true;
  13847. // $update_fields[] = 'task_id';
  13848. // }
  13849. // // 如果有更新,同步到全局
  13850. // if ($updated) {
  13851. // foreach ($new_global_roles as &$global_role_item) {
  13852. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  13853. // if ($global_role_key === $roleKey) {
  13854. // if (in_array('description', $update_fields)) {
  13855. // $global_role_item['description'] = $current_description;
  13856. // }
  13857. // if (in_array('pic_prompt', $update_fields)) {
  13858. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  13859. // }
  13860. // if (in_array('task_id', $update_fields)) {
  13861. // $global_role_item['task_id'] = $current_task_id;
  13862. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  13863. // $global_role_item['url'] = getProp($role, 'url', '');
  13864. // }
  13865. // break;
  13866. // }
  13867. // }
  13868. // $need_update = true;
  13869. // dLog('deepseek')->info("角色信息更新到全局", [
  13870. // 'anime_id' => $anime_id,
  13871. // 'role' => $role_name,
  13872. // 'update_fields' => implode(',', $update_fields),
  13873. // ]);
  13874. // }
  13875. // }
  13876. // }
  13877. }
  13878. // 检查并添加新场景到全局
  13879. foreach ($merged_scenes as $scene) {
  13880. $scene_name = getProp($scene, 'scene');
  13881. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  13882. if ($sceneKey === '') {
  13883. continue;
  13884. }
  13885. // 如果全局中不存在该场景,添加到全局
  13886. if (!isset($global_scene_map[$sceneKey])) {
  13887. $new_global_scenes[] = [
  13888. 'scene' => $scene_name,
  13889. 'description' => getProp($scene, 'description', ''),
  13890. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  13891. 'url' => getProp($scene, 'url', ''),
  13892. 'task_id' => getProp($scene, 'task_id', ''),
  13893. 'task_status' => getProp($scene, 'task_status', ''),
  13894. ];
  13895. $global_scene_map[$sceneKey] = true; // 标记已添加
  13896. $need_update = true;
  13897. dLog('deepseek')->info("新场景同步到全局", [
  13898. 'anime_id' => $anime_id,
  13899. 'scene' => $scene_name,
  13900. 'task_id' => getProp($scene, 'task_id', ''),
  13901. ]);
  13902. }
  13903. // else {
  13904. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  13905. // $global_scene = $global_scene_map[$sceneKey];
  13906. // if (is_array($global_scene)) {
  13907. // $updated = false;
  13908. // $update_fields = [];
  13909. // // 检查描述是否更新
  13910. // $current_description = trim((string)getProp($scene, 'description'));
  13911. // $global_description = trim((string)getProp($global_scene, 'description'));
  13912. // if ($current_description !== '' && $current_description !== $global_description) {
  13913. // $updated = true;
  13914. // $update_fields[] = 'description';
  13915. // }
  13916. // // 检查pic_prompt是否更新
  13917. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  13918. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  13919. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  13920. // $updated = true;
  13921. // $update_fields[] = 'pic_prompt';
  13922. // }
  13923. // // 检查图片任务信息是否更新
  13924. // $current_task_id = getProp($scene, 'task_id');
  13925. // $global_task_id = getProp($global_scene, 'task_id');
  13926. // if ($current_task_id && $current_task_id !== $global_task_id) {
  13927. // $updated = true;
  13928. // $update_fields[] = 'task_id';
  13929. // }
  13930. // // 如果有更新,同步到全局
  13931. // if ($updated) {
  13932. // foreach ($new_global_scenes as &$global_scene_item) {
  13933. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  13934. // if ($global_scene_key === $sceneKey) {
  13935. // if (in_array('description', $update_fields)) {
  13936. // $global_scene_item['description'] = $current_description;
  13937. // }
  13938. // if (in_array('pic_prompt', $update_fields)) {
  13939. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  13940. // }
  13941. // if (in_array('task_id', $update_fields)) {
  13942. // $global_scene_item['task_id'] = $current_task_id;
  13943. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  13944. // $global_scene_item['url'] = getProp($scene, 'url', '');
  13945. // }
  13946. // break;
  13947. // }
  13948. // }
  13949. // $need_update = true;
  13950. // dLog('deepseek')->info("场景信息更新到全局", [
  13951. // 'anime_id' => $anime_id,
  13952. // 'scene' => $scene_name,
  13953. // 'update_fields' => implode(',', $update_fields),
  13954. // ]);
  13955. // }
  13956. // }
  13957. // }
  13958. }
  13959. // 如果有新增或更新,更新数据库
  13960. if ($need_update) {
  13961. $update_data = [
  13962. 'roles' => json_encode($new_global_roles, 256),
  13963. 'scenes' => json_encode($new_global_scenes, 256),
  13964. 'updated_at' => date('Y-m-d H:i:s'),
  13965. ];
  13966. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  13967. if ($result !== false) {
  13968. dLog('deepseek')->info("全局角色和场景更新成功", [
  13969. 'anime_id' => $anime_id,
  13970. 'roles_count' => count($new_global_roles),
  13971. 'scenes_count' => count($new_global_scenes),
  13972. ]);
  13973. } else {
  13974. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  13975. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  13976. }
  13977. }
  13978. }
  13979. }