DeepSeekService.php 783 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418
  1. <?php
  2. namespace App\Services\DeepSeek;
  3. use App\Consts\ErrorConst;
  4. use App\Consts\BaseConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use GuzzleHttp\Client;
  8. use DateTime;
  9. use DateTimeZone;
  10. use App\Services\AIGeneration\AIImageGenerationService;
  11. use App\Services\PointsService;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Log;
  14. use Illuminate\Support\Facades\Redis;
  15. use OSS\Core\OssException;
  16. use OSS\OssClient;
  17. use Smalot\PdfParser\Parser as PdfParser;
  18. use TCPDF;
  19. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  20. use Predis\Command\Traits\Get\Get;
  21. class DeepSeekService
  22. {
  23. private $url;
  24. private $api_key;
  25. private $sys_message;
  26. private $headers;
  27. private $valid_text_models;
  28. private $gpt_text_models;
  29. private $gemini_text_models;
  30. protected $aiImageGenerationService;
  31. protected $pointsService;
  32. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  33. $this->aiImageGenerationService = $aiImageGenerationService;
  34. $this->pointsService = $pointsService;
  35. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  36. $this->api_key = env('DEEPSEEK_API_KEY');
  37. $this->headers = [
  38. 'Authorization' => 'Bearer '.$this->api_key,
  39. 'Content-Type' => 'application/json; charset=UTF-8'
  40. ];
  41. // 火山引擎模型列表
  42. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  43. // GPT文本模型列表
  44. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  45. // Gemini文本模型列表
  46. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  47. $this->sys_message = [
  48. 'role' => 'system',
  49. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  50. 强制要求:\n
  51. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  52. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  53. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  54. 普通要求:\n
  55. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  56. 2.<分集剧本>的要求如下:
  57.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  58.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  59.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  60.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  61. \n\n
  62. 示例如下:\n
  63. ###剧本名:西昆仑
  64. ###故事梗概
  65. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  66. ###剧本亮点
  67. 亮点1:绝境奇药,生死一线
  68. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  69. 亮点2:结拜兄妹,化解尴尬
  70. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  71. 亮点3:纤发夺命,情愫暗涌
  72. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  73. ###人物关系
  74. 阿雪与梁萧之间存在兄妹之情。
  75. ###核心矛盾
  76. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  77. ###主体列表
  78. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  79. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  80. 阴阳球:天地异宝,能化生精气,救人于危难。
  81. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  82. ###美术风格
  83. 基础画风风格词:厚涂古风
  84. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  85. ###场景列表
  86. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  87. ###分集剧本
  88. ##分集01
  89. 第1集: 第一集的标题
  90. 场景描述:地点、时间、场景
  91. 运镜:固定近距离
  92. 出场角色:男主、女主
  93. 台词内容:
  94. 女主: 女主对话
  95. 男主:男主对话
  96. 女主: 女主对话
  97. 男主: 男主对话
  98. ##分集02
  99. 第2集: 第二集的标题
  100. 场景描述:地点、时间、场景
  101. 运镜:固定近距离
  102. 出场角色:男主、女主
  103. 台词内容:
  104. 女主: 女主对话
  105. 男主:男主对话
  106. 女主: 女主对话
  107. 男主: 男主对话"
  108. ];
  109. }
  110. /**
  111. * 通用文生文方法 - 支持多模型流式输出、图片输入;视频输入仅 Gemini 模型支持
  112. *
  113. * @param array $data 请求参数
  114. * @return \Generator 返回生成器,用于流式输出
  115. */
  116. public function generateText($data) {
  117. // 获取请求参数
  118. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  119. $messages = getProp($data, 'messages', []);
  120. $systemPrompt = getProp($data, 'system_prompt', '');
  121. $prompt = getProp($data, 'prompt', '');
  122. $images = getProp($data, 'images', []); // 支持多张图片
  123. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  124. $videos = getProp($data, 'videos', []); // Gemini 支持视频文件
  125. $videoUrls = getProp($data, 'video_urls', []); // Gemini 支持视频URL
  126. $isGeminiModel = in_array($model, $this->gemini_text_models);
  127. if ((!empty($videos) || !empty($videoUrls)) && !$isGeminiModel) {
  128. Utils::throwError('20003:仅Gemini模型支持视频输入');
  129. }
  130. // Gemini 多模态(图片/视频 -> 文本)按模型预检积分;纯文本不扣费
  131. $uid = Site::getUid();
  132. $chargeModality = '';
  133. $chargePoints = 0;
  134. $hasImageMedia = !empty($images) || !empty($imageUrls)
  135. || $this->messagesContainMedia($messages, ['image_url', 'image']);
  136. $hasVideoMedia = !empty($videos) || !empty($videoUrls)
  137. || $this->messagesContainMedia($messages, ['video_url', 'video']);
  138. if ($isGeminiModel && ($hasImageMedia || $hasVideoMedia)) {
  139. $chargeModality = $hasVideoMedia ? 'video' : 'image';
  140. $pricingModel = $this->geminiMultimodalPricingModel($model);
  141. if ($pricingModel !== '') {
  142. $chargePoints = $this->pointsService->getVideoChargePoints(['model' => $pricingModel]);
  143. if ($chargePoints > 0) {
  144. $this->pointsService->checkUserPointsEnough($chargePoints, $uid);
  145. }
  146. }
  147. }
  148. // 如果没有提供messages,则根据system_prompt、content和images构建
  149. if (empty($messages)) {
  150. $messages = [];
  151. // 添加系统提示词
  152. if (!empty($systemPrompt)) {
  153. $messages[] = [
  154. 'role' => 'system',
  155. 'content' => $systemPrompt
  156. ];
  157. }
  158. // 构建用户消息内容(支持文本+图片)
  159. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  160. $userMessage = [
  161. 'role' => 'user',
  162. 'content' => []
  163. ];
  164. // 添加文本内容
  165. if (!empty($prompt)) {
  166. $userMessage['content'][] = [
  167. 'type' => 'text',
  168. 'text' => $prompt
  169. ];
  170. }
  171. // 处理上传的图片文件
  172. if (!empty($images)) {
  173. if (!is_array($images)) {
  174. $images = [$images];
  175. }
  176. foreach ($images as $image) {
  177. $imageBase64 = $this->processImageToBase64($image);
  178. if ($imageBase64) {
  179. $userMessage['content'][] = [
  180. 'type' => 'image_url',
  181. 'image_url' => [
  182. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  183. ]
  184. ];
  185. }
  186. }
  187. }
  188. // 处理图片URL
  189. if (!empty($imageUrls)) {
  190. if (!is_array($imageUrls)) {
  191. $imageUrls = [$imageUrls];
  192. }
  193. foreach ($imageUrls as $url) {
  194. if (!empty($url)) {
  195. $userMessage['content'][] = [
  196. 'type' => 'image_url',
  197. 'image_url' => [
  198. 'url' => $url
  199. ]
  200. ];
  201. }
  202. }
  203. }
  204. // 处理上传的视频文件(仅 Gemini)
  205. if (!empty($videos) && $isGeminiModel) {
  206. if (!is_array($videos)) {
  207. $videos = [$videos];
  208. }
  209. foreach ($videos as $video) {
  210. $inlineData = $this->processMediaToInlineData($video);
  211. if ($inlineData) {
  212. $userMessage['content'][] = [
  213. 'type' => 'video',
  214. 'inline_data' => $inlineData
  215. ];
  216. }
  217. }
  218. }
  219. // 处理视频URL(仅 Gemini)
  220. if (!empty($videoUrls) && $isGeminiModel) {
  221. if (!is_array($videoUrls)) {
  222. $videoUrls = [$videoUrls];
  223. }
  224. foreach ($videoUrls as $url) {
  225. if (!empty($url)) {
  226. $userMessage['content'][] = [
  227. 'type' => 'video_url',
  228. 'video_url' => ['url' => $url]
  229. ];
  230. }
  231. }
  232. }
  233. // 如果只有文本内容,简化为字符串格式
  234. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  235. $userMessage['content'] = $userMessage['content'][0]['text'];
  236. }
  237. $messages[] = $userMessage;
  238. }
  239. }
  240. // 验证messages不为空
  241. if (empty($messages)) {
  242. Utils::throwError('20003:请提供有效的对话内容');
  243. }
  244. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  245. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  246. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  247. if ($model === 'deepseek-chat') {
  248. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  249. $model = 'deepseek-v4-flash';
  250. $thinkingMode = 'disabled';
  251. } elseif ($model === 'deepseek-reasoner') {
  252. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  253. $model = 'deepseek-v4-flash';
  254. $thinkingMode = 'enabled';
  255. }
  256. // 构建请求参数
  257. $post_data = [
  258. 'model' => $model,
  259. 'messages' => $messages,
  260. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  261. 'temperature' => getProp($data, 'temperature', 1),
  262. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  263. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  264. 'thinking' => ['type' => $thinkingMode],
  265. 'stream' => true // 启用流式输出
  266. ];
  267. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  268. // 添加可选参数
  269. if (isset($data['top_p'])) {
  270. $post_data['top_p'] = $data['top_p'];
  271. }
  272. if (isset($data['response_format'])) {
  273. $post_data['response_format'] = $data['response_format'];
  274. }
  275. // 根据模型类型选择调用方法
  276. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  277. // DeepSeek 官方模型使用 DeepSeek API
  278. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  279. } else if (in_array($model, $this->gpt_text_models)) {
  280. // GPT 模型使用 TokenRouter API
  281. $streamGenerator = $this->gpt54StreamResponse($post_data);
  282. } else if (in_array($model, $this->gemini_text_models)) {
  283. // Gemini 模型使用 Gemini API
  284. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  285. } else if (in_array($model, $this->valid_text_models)) {
  286. // 火山引擎支持的模型使用火山引擎 API
  287. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  288. } else {
  289. Utils::throwError('20003:不支持的模型: ' . $model);
  290. }
  291. if ($chargePoints > 0) {
  292. return $this->wrapGenerateTextCharge($streamGenerator, $uid, $model, $chargePoints, $chargeModality);
  293. }
  294. return $streamGenerator;
  295. }
  296. /**
  297. * 流式生成成功后再按 Gemini 多模态规则扣费
  298. *
  299. * @param \Generator $generator
  300. * @param int $uid
  301. * @param string $model
  302. * @param int $points
  303. * @param string $modality
  304. * @return \Generator
  305. */
  306. private function wrapGenerateTextCharge(\Generator $generator, int $uid, string $model, int $points, string $modality): \Generator
  307. {
  308. $charged = false;
  309. foreach ($generator as $chunk) {
  310. if (!$charged && isset($chunk['type']) && $chunk['type'] === 'done') {
  311. $fullContent = (string)getProp($chunk, 'full_content', getProp($chunk, 'answer', ''));
  312. if ($fullContent !== '') {
  313. $this->chargeGeminiMultimodal($uid, $model, $points, $modality, getProp($chunk, 'usage', []));
  314. $charged = true;
  315. }
  316. }
  317. yield $chunk;
  318. }
  319. }
  320. /**
  321. * Gemini 多模态(图片/视频 -> 文本)成功后扣费并记录 token 明细
  322. *
  323. * @param int $uid
  324. * @param string $model
  325. * @param int $points
  326. * @param string $modality
  327. * @param mixed $usage
  328. * @return void
  329. */
  330. private function chargeGeminiMultimodal(int $uid, string $model, int $points, string $modality, $usage): void
  331. {
  332. $result = $this->pointsService->recordChatCharge(
  333. $uid,
  334. $points,
  335. $this->pointsService->getTokensFromUsage($usage),
  336. [
  337. 'model' => $model,
  338. 'modality' => $modality,
  339. 'source' => 'generateText',
  340. ],
  341. $modality === 'video' ? 'Gemini视频理解成功计费' : 'Gemini图片理解成功计费',
  342. $model
  343. );
  344. if (empty($result['charged'])) {
  345. throw new \Exception('Gemini多模态计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  346. }
  347. }
  348. /**
  349. * Gemini 文本模型 ID 转 mp_video_models 中的按次计费模型 ID
  350. *
  351. * @param string $model
  352. * @return string
  353. */
  354. private function geminiMultimodalPricingModel(string $model): string
  355. {
  356. $map = [
  357. 'gemini-3.1-flash-image-preview-t' => 'gemini-3.1-flash',
  358. 'gemini-3.1-pro-preview' => 'gemini-3.1-pro',
  359. 'gemini-3-flash-preview' => 'gemini-3.0-flash',
  360. 'gemini-3-pro-preview' => 'gemini-3.0-pro',
  361. 'gemini-3.6-flash' => 'gemini-3.6-flash',
  362. ];
  363. return $map[$model] ?? '';
  364. }
  365. /**
  366. * 检查 OpenAI 风格消息中是否包含指定媒体类型
  367. *
  368. * @param array $messages
  369. * @param array $mediaTypes
  370. * @return bool
  371. */
  372. private function messagesContainMedia(array $messages, array $mediaTypes): bool
  373. {
  374. foreach ($messages as $message) {
  375. $content = getProp($message, 'content', '');
  376. if (!is_array($content)) {
  377. continue;
  378. }
  379. foreach ($content as $part) {
  380. if (is_array($part) && in_array(getProp($part, 'type', ''), $mediaTypes, true)) {
  381. return true;
  382. }
  383. }
  384. }
  385. return false;
  386. }
  387. public function createGenerateText($data) {
  388. $file = getProp($data, 'file');
  389. $uid = Site::getUid();
  390. $cpid = Site::getCpid();
  391. if (!$file) {
  392. Utils::throwError('20003:请上传文件');
  393. }
  394. // 提取文件内容
  395. $content = $this->extractFileContent($file);
  396. if (!$content) {
  397. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  398. }
  399. // 获取原始文件名(不含扩展名)作为script_name
  400. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  401. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  402. // 字节安全剥离,不依赖服务器locale设置
  403. $originalName = $file->getClientOriginalName();
  404. $extension = $file->getClientOriginalExtension();
  405. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  406. ? substr($originalName, 0, -strlen($extension) - 1)
  407. : $originalName;
  408. if ($script_name === '') {
  409. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  410. }
  411. // 如果同一用户的剧本名存在则提示
  412. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  413. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  414. }
  415. // 插入数据到mp_scripts表
  416. $script_id = DB::table('mp_scripts')->insertGetId([
  417. 'script_name' => $script_name,
  418. 'user_id' => $uid,
  419. 'cpid' => $cpid,
  420. 'content' => $content,
  421. 'created_at' => date('Y-m-d H:i:s'),
  422. 'updated_at' => date('Y-m-d H:i:s')
  423. ]);
  424. return [
  425. 'script_id' => $script_id,
  426. 'script_name' => $script_name
  427. ];
  428. }
  429. /**
  430. * AI对话调用成功后的积分扣费(返回结果前调用)
  431. *
  432. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  433. *
  434. * @param int $uid
  435. * @param int $tokens
  436. * @param array $chargeInfo
  437. * @return void
  438. */
  439. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo): void
  440. {
  441. $result = $this->pointsService->recordChatCharge(
  442. $uid,
  443. PointsService::CHAT_CHARGE_POINTS,
  444. $tokens,
  445. $chargeInfo
  446. );
  447. if (empty($result['charged'])) {
  448. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  449. }
  450. }
  451. /**
  452. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  453. *
  454. * @param array $data 请求参数
  455. * @return array 返回结果数组
  456. */
  457. public function newGenerateText($data) {
  458. // 获取请求参数
  459. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  460. $messages = getProp($data, 'messages', []);
  461. $systemPrompt = getProp($data, 'system_prompt', '');
  462. $prompt = getProp($data, 'prompt', '');
  463. $images = getProp($data, 'images', []); // 支持多张图片
  464. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  465. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  466. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  467. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  468. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  469. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  470. $generateTaskId = 0;
  471. $uid = Site::getUid();
  472. if ($script_id > 0) {
  473. $existingTask = DB::table('mp_script_generate_tasks')
  474. ->where('uid', $uid)
  475. ->where('script_id', $script_id)
  476. ->orderByDesc('id')
  477. ->first();
  478. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  479. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  480. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  481. }
  482. }
  483. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  484. $originalContent = '';
  485. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  486. if ($script_id > 0) {
  487. $script = DB::table('mp_scripts')
  488. ->where('id', $script_id)
  489. ->where('is_deleted', 0)
  490. ->first();
  491. if (!$script) {
  492. Utils::throwError('20003:剧本不存在或已删除');
  493. }
  494. $originalContent = $script->content ?? '';
  495. if (empty($originalContent)) {
  496. Utils::throwError('20003:剧本内容为空');
  497. }
  498. $hasValidScript = true;
  499. // 将剧本内容添加到提示词前面
  500. if (!empty($originalContent)) {
  501. if (!empty($prompt)) {
  502. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  503. } else {
  504. $prompt = "原文内容:\n" . $originalContent;
  505. }
  506. }
  507. }
  508. // 新增: 如果提供了template_id,从数据库获取template_prompt
  509. if ($templateId > 0) {
  510. $template = DB::table('mp_prompt_templates')
  511. ->where('id', $templateId)
  512. ->where('is_deleted', 0)
  513. ->first();
  514. if (!$template) {
  515. Utils::throwError('20003:模板不存在或已删除');
  516. }
  517. $templatePrompt = $template->template_prompt ?? '';
  518. // 将模板提示词和用户输入的prompt组合
  519. // 模板为准,用户输入作为补充要求
  520. if (!empty($templatePrompt)) {
  521. if (!empty($prompt)) {
  522. $prompt = $templatePrompt . "\n\n" . $prompt;
  523. } else {
  524. $prompt = $templatePrompt;
  525. }
  526. }
  527. }
  528. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  529. if (empty($messages)) {
  530. $messages = [];
  531. // 添加系统提示词
  532. if (!empty($systemPrompt)) {
  533. $messages[] = [
  534. 'role' => 'system',
  535. 'content' => $systemPrompt
  536. ];
  537. }
  538. // 构建用户消息内容(支持文本+图片)
  539. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  540. $userMessage = [
  541. 'role' => 'user',
  542. 'content' => []
  543. ];
  544. // 添加文本内容
  545. if (!empty($prompt)) {
  546. $userMessage['content'][] = [
  547. 'type' => 'text',
  548. 'text' => $prompt
  549. ];
  550. }
  551. // 处理上传的图片文件
  552. if (!empty($images)) {
  553. if (!is_array($images)) {
  554. $images = [$images];
  555. }
  556. foreach ($images as $image) {
  557. $imageBase64 = $this->processImageToBase64($image);
  558. if ($imageBase64) {
  559. $userMessage['content'][] = [
  560. 'type' => 'image_url',
  561. 'image_url' => [
  562. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  563. ]
  564. ];
  565. }
  566. }
  567. }
  568. // 处理图片URL
  569. if (!empty($imageUrls)) {
  570. if (!is_array($imageUrls)) {
  571. $imageUrls = [$imageUrls];
  572. }
  573. foreach ($imageUrls as $url) {
  574. if (!empty($url)) {
  575. $userMessage['content'][] = [
  576. 'type' => 'image_url',
  577. 'image_url' => [
  578. 'url' => $url
  579. ]
  580. ];
  581. }
  582. }
  583. }
  584. // 如果只有文本内容,简化为字符串格式
  585. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  586. $userMessage['content'] = $userMessage['content'][0]['text'];
  587. }
  588. $messages[] = $userMessage;
  589. }
  590. }
  591. // 验证messages不为空
  592. if (empty($messages)) {
  593. Utils::throwError('20003:请提供有效的对话内容');
  594. }
  595. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  596. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  597. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  598. if ($model === 'deepseek-chat') {
  599. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  600. $model = 'deepseek-v4-flash';
  601. $thinkingMode = 'disabled';
  602. } elseif ($model === 'deepseek-reasoner') {
  603. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  604. $model = 'deepseek-v4-flash';
  605. $thinkingMode = 'enabled';
  606. }
  607. // 构建请求参数(非流式)
  608. $post_data = [
  609. 'model' => $model,
  610. 'messages' => $messages,
  611. 'temperature' => getProp($data, 'temperature', 1),
  612. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  613. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  614. 'thinking' => ['type' => $thinkingMode],
  615. 'stream' => false // 非流式输出
  616. ];
  617. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  618. // 添加可选参数
  619. if (isset($data['top_p'])) {
  620. $post_data['top_p'] = $data['top_p'];
  621. }
  622. // 新增: 根据response_format设置响应格式
  623. if ($responseFormat === 'json') {
  624. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  625. $hasJsonKeyword = false;
  626. foreach ($post_data['messages'] as $message) {
  627. if (isset($message['content'])) {
  628. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  629. if (stripos($content, 'json') !== false) {
  630. $hasJsonKeyword = true;
  631. break;
  632. }
  633. }
  634. }
  635. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  636. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  637. if (!$hasJsonKeyword) {
  638. $lastMessageIndex = count($post_data['messages']) - 1;
  639. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  640. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  641. // 如果content是字符串,直接追加
  642. if (is_string($lastContent)) {
  643. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  644. }
  645. // 如果content是数组(包含文本和图片),在文本部分追加
  646. else if (is_array($lastContent)) {
  647. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  648. if ($contentPart['type'] === 'text') {
  649. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  650. break;
  651. }
  652. }
  653. }
  654. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  655. }
  656. }
  657. // 设置response_format参数(所有支持的模型)
  658. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  659. // DeepSeek模型
  660. $post_data['response_format'] = ['type' => 'json_object'];
  661. } else if (in_array($model, $this->gpt_text_models)) {
  662. // GPT模型
  663. $post_data['response_format'] = ['type' => 'json_object'];
  664. } else if (in_array($model, $this->valid_text_models)) {
  665. // 火山引擎模型
  666. $post_data['response_format'] = ['type' => 'json_object'];
  667. }
  668. }
  669. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  670. if ($script_id > 0) {
  671. $uid = Site::getUid();
  672. // 创建新的生成任务
  673. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  674. 'uid' => $uid,
  675. 'script_id' => $script_id,
  676. 'sequence' => $sequence,
  677. 'status' => 'processing',
  678. 'prompt' => getProp($data, 'prompt', ''),
  679. 'started_at' => date('Y-m-d H:i:s'),
  680. 'created_at' => date('Y-m-d H:i:s'),
  681. 'updated_at' => date('Y-m-d H:i:s')
  682. ]);
  683. }
  684. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  685. if ($hasValidScript) {
  686. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  687. }
  688. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  689. try {
  690. $aiResult = null;
  691. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  692. // DeepSeek 官方模型使用现有的 chatOnly 方法
  693. $result = $this->chatOnly($post_data);
  694. // 记录实际使用的模型
  695. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  696. $aiResult = [
  697. 'content' => $result['fullContent'],
  698. 'reasoning_content' => $result['fullReasoningContent'],
  699. 'usage' => $result['usage'],
  700. 'model' => $model,
  701. 'finish_reason' => 'stop'
  702. ];
  703. } else if (in_array($model, $this->gpt_text_models)) {
  704. // GPT 模型使用现有的 gpt54ChatOnly 方法
  705. $result = $this->gpt54ChatOnly($post_data);
  706. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  707. $aiResult = [
  708. 'content' => $result['fullContent'],
  709. 'reasoning_content' => '',
  710. 'usage' => $result['usage'],
  711. 'model' => $model,
  712. 'finish_reason' => 'stop'
  713. ];
  714. } else if (in_array($model, $this->gemini_text_models)) {
  715. // Gemini 模型使用 Gemini API(非流式)
  716. $result = $this->geminiChatOnly($post_data, $model);
  717. dLog('deepseek')->info('newGenerateText使用Gemini模型', ['requested_model' => $model]);
  718. $aiResult = [
  719. 'content' => $result['fullContent'],
  720. 'reasoning_content' => $result['fullReasoningContent'] ?? '',
  721. 'usage' => $result['usage'],
  722. 'model' => $model,
  723. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  724. ];
  725. } else if (in_array($model, $this->valid_text_models)) {
  726. // 火山引擎支持的模型使用火山引擎 API(非流式)
  727. $post_data['stream'] = false;
  728. $result = $this->volcEngineChatCompletion($post_data);
  729. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  730. 'requested_model' => $model,
  731. 'result_keys' => array_keys($result),
  732. 'has_fullContent' => isset($result['fullContent']),
  733. 'has_content' => isset($result['content'])
  734. ]);
  735. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  736. $aiResult = [
  737. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  738. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  739. 'usage' => $result['usage'] ?? [],
  740. 'model' => $model,
  741. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  742. ];
  743. } else {
  744. Utils::throwError('20003:不支持的模型: ' . $model);
  745. }
  746. } catch (\Exception $e) {
  747. // 生成失败,更新任务状态
  748. if ($generateTaskId) {
  749. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  750. 'status' => 'failed',
  751. 'error_message' => $e->getMessage(),
  752. 'completed_at' => date('Y-m-d H:i:s'),
  753. 'updated_at' => date('Y-m-d H:i:s')
  754. ]);
  755. }
  756. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  757. }
  758. // 生成成功,更新任务状态
  759. if ($generateTaskId && $aiResult) {
  760. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  761. 'status' => 'success',
  762. 'result' => getProp($aiResult, 'content', ''),
  763. 'completed_at' => date('Y-m-d H:i:s'),
  764. 'updated_at' => date('Y-m-d H:i:s')
  765. ]);
  766. $aiResult['generate_task_id'] = $generateTaskId;
  767. }
  768. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  769. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  770. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  771. 'model' => $model,
  772. 'script_id' => $script_id,
  773. 'sequence' => $sequence,
  774. 'source' => 'newGenerateText',
  775. ]);
  776. }
  777. // 新增: 如果提供了script_id,保存对话记录
  778. if ($script_id > 0 && $aiResult) {
  779. try {
  780. $uid = Site::getUid();
  781. $now = now();
  782. // 获取用户原始的prompt(不包含剧本内容)
  783. $originalPrompt = getProp($data, 'prompt', '');
  784. $recordsToInsert = [
  785. [
  786. 'uid' => $uid,
  787. 'script_id' => $script_id,
  788. 'sequence' => $sequence,
  789. 'role' => 'user',
  790. 'content' => $originalPrompt,
  791. 'created_at' => $now,
  792. 'updated_at' => $now,
  793. ],
  794. [
  795. 'uid' => $uid,
  796. 'script_id' => $script_id,
  797. 'sequence' => $sequence,
  798. 'role' => 'assistant',
  799. 'content' => $aiResult['content'],
  800. 'created_at' => $now,
  801. 'updated_at' => $now,
  802. ]
  803. ];
  804. DB::table('mp_script_records')->insert($recordsToInsert);
  805. // 获取刚插入的记录ID(假设按插入顺序返回)
  806. $insertedRecords = DB::table('mp_script_records')
  807. ->where('uid', $uid)
  808. ->where('script_id', $script_id)
  809. ->where('sequence', $sequence)
  810. ->orderBy('id', 'desc')
  811. ->limit(2)
  812. ->get()
  813. ->map(function ($record) {
  814. return [
  815. 'rid' => $record->id,
  816. 'script_id' => $record->script_id,
  817. 'sequence' => $record->sequence,
  818. 'role' => $record->role,
  819. 'content' => $record->content,
  820. 'created_at' => $record->created_at,
  821. ];
  822. })
  823. ->reverse()
  824. ->values()
  825. ->toArray();
  826. // 将记录信息添加到返回结果中
  827. $aiResult['records'] = $insertedRecords;
  828. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  829. } catch (\Exception $e) {
  830. // 记录错误但不影响主流程
  831. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  832. }
  833. }
  834. return $aiResult;
  835. }
  836. /**
  837. * 通用 Gemini 文生文方法(支持流式和非流式)
  838. *
  839. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  840. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  841. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  842. * system_prompt 系统提示词(可选)
  843. * prompt 用户提示词(可选)
  844. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  845. * image_urls 图片/视频URL列表(可选,同上)
  846. * temperature 温度(可选,默认 1)
  847. * top_p 核采样(可选)
  848. * max_tokens 最大输出 token(可选,默认 8192)
  849. * response_format text/json(可选)
  850. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  851. * thinking_budget 思考预算(可选,默认 20)
  852. * stream 是否流式(可选,默认 false)
  853. *
  854. * @param array $data 请求参数
  855. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  856. */
  857. public function geminiGenerateText($data) {
  858. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  859. $isStream = (bool)getProp($data, 'stream', false);
  860. if (!in_array($model, $this->gemini_text_models)) {
  861. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  862. }
  863. $requestData = $this->buildGeminiRequestBody($data, $model);
  864. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  865. if ($isStream) {
  866. // 流式返回生成器
  867. return $this->geminiStreamResponse($requestData, $model);
  868. }
  869. // 非流式
  870. return $this->geminiChatOnly($requestData, $model);
  871. }
  872. /**
  873. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  874. */
  875. private function geminiMediaMaxBytes() {
  876. return 14 * 1024 * 1024;
  877. }
  878. /**
  879. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  880. */
  881. private function buildGeminiRequestBody($data, $model) {
  882. $messages = getProp($data, 'messages', []);
  883. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  884. if (empty($messages)) {
  885. $systemPrompt = getProp($data, 'system_prompt', '');
  886. $prompt = getProp($data, 'prompt', '');
  887. $images = getProp($data, 'images', []);
  888. $imageUrls = getProp($data, 'image_urls', []);
  889. $messages = [];
  890. if (!empty($systemPrompt)) {
  891. $messages[] = [
  892. 'role' => 'system',
  893. 'content' => $systemPrompt
  894. ];
  895. }
  896. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  897. $userMessage = ['role' => 'user', 'content' => []];
  898. if (!empty($prompt)) {
  899. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  900. }
  901. if (!empty($images)) {
  902. if (!is_array($images)) {
  903. $images = [$images];
  904. }
  905. foreach ($images as $image) {
  906. $inlineData = $this->processMediaToInlineData($image);
  907. if ($inlineData) {
  908. $userMessage['content'][] = [
  909. 'type' => 'image',
  910. 'inline_data' => $inlineData
  911. ];
  912. }
  913. }
  914. }
  915. if (!empty($imageUrls)) {
  916. if (!is_array($imageUrls)) {
  917. $imageUrls = [$imageUrls];
  918. }
  919. foreach ($imageUrls as $url) {
  920. if (!empty($url)) {
  921. $inlineData = $this->processMediaToInlineData($url);
  922. if ($inlineData) {
  923. $userMessage['content'][] = [
  924. 'type' => 'image',
  925. 'inline_data' => $inlineData
  926. ];
  927. }
  928. }
  929. }
  930. }
  931. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  932. $userMessage['content'] = $userMessage['content'][0]['text'];
  933. }
  934. $messages[] = $userMessage;
  935. }
  936. }
  937. if (empty($messages)) {
  938. Utils::throwError('20003:请提供有效的对话内容');
  939. }
  940. // 转换为 Gemini contents 格式
  941. $systemInstruction = '';
  942. $contents = [];
  943. foreach ($messages as $message) {
  944. $role = getProp($message, 'role', 'user');
  945. $content = getProp($message, 'content', '');
  946. if ($role === 'system') {
  947. if (is_array($content)) {
  948. $systemInstruction = $this->extractGeminiTextFromParts($content);
  949. } else {
  950. $systemInstruction = (string)$content;
  951. }
  952. continue;
  953. }
  954. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  955. $parts = [];
  956. if (is_array($content)) {
  957. foreach ($content as $part) {
  958. $partType = getProp($part, 'type', 'text');
  959. if ($partType === 'text') {
  960. $text = (string)getProp($part, 'text', '');
  961. if ($text !== '') {
  962. $parts[] = ['text' => $text];
  963. }
  964. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  965. if (in_array($partType, ['image_url', 'video_url'])) {
  966. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  967. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  968. } elseif (isset($part['inline_data'])) {
  969. // 已处理过的 inline_data 直接使用
  970. $parts[] = ['inline_data' => $part['inline_data']];
  971. continue;
  972. } else {
  973. $url = '';
  974. }
  975. $inlineData = $this->processMediaToInlineData($url);
  976. if ($inlineData) {
  977. $parts[] = ['inline_data' => $inlineData];
  978. }
  979. }
  980. }
  981. } else {
  982. $text = (string)$content;
  983. if ($text !== '') {
  984. $parts[] = ['text' => $text];
  985. }
  986. }
  987. if (!empty($parts)) {
  988. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  989. }
  990. }
  991. if (empty($contents)) {
  992. Utils::throwError('20003:请提供有效的对话内容');
  993. }
  994. // 构建生成配置
  995. $generationConfig = [];
  996. if (getProp($data, 'temperature', null) !== null) {
  997. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  998. }
  999. if (getProp($data, 'top_p', null) !== null) {
  1000. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  1001. }
  1002. if (getProp($data, 'frequency_penalty', null) !== null) {
  1003. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  1004. }
  1005. if (getProp($data, 'presence_penalty', null) !== null) {
  1006. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  1007. }
  1008. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  1009. if ($maxOutputTokens <= 0) {
  1010. $maxOutputTokens = 8192;
  1011. }
  1012. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  1013. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  1014. $maxOutputTokens = 32768;
  1015. }
  1016. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  1017. // response_format 映射:text -> text/plain,json -> application/json
  1018. $responseFormat = getProp($data, 'response_format', 'text');
  1019. if (is_array($responseFormat)) {
  1020. $responseFormat = getProp($responseFormat, 'type', 'text');
  1021. }
  1022. if (in_array($responseFormat, ['json', 'json_object'])) {
  1023. $generationConfig['responseMimeType'] = 'application/json';
  1024. } else {
  1025. $generationConfig['responseMimeType'] = 'text/plain';
  1026. }
  1027. $requestData = [
  1028. 'contents' => $contents,
  1029. 'generationConfig' => $generationConfig,
  1030. ];
  1031. if ($systemInstruction !== '') {
  1032. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  1033. }
  1034. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  1035. $thinkingMode = getProp($data, 'thinking', null);
  1036. if (is_array($thinkingMode)) {
  1037. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  1038. }
  1039. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  1040. if ($thinkingMode === null) {
  1041. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  1042. }
  1043. if ($thinkingMode === 'enabled') {
  1044. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  1045. if ($thinkingBudget <= 0) {
  1046. $thinkingBudget = 20;
  1047. }
  1048. $requestData['generationConfig']['thinkingConfig'] = [
  1049. 'thinkingBudget' => $thinkingBudget
  1050. ];
  1051. } elseif ($defaultThinking) {
  1052. // 该模型仅支持思考模式,传 0 会返回 400
  1053. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  1054. } else {
  1055. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  1056. }
  1057. return $requestData;
  1058. }
  1059. /**
  1060. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  1061. *
  1062. * 模型名 -> env 变量名映射:
  1063. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  1064. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  1065. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  1066. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  1067. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  1068. */
  1069. private function getGeminiApiKey($model) {
  1070. $map = [
  1071. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  1072. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  1073. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  1074. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  1075. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  1076. ];
  1077. if (isset($map[$model])) {
  1078. $key = env($map[$model]);
  1079. if (!empty($key)) {
  1080. return $key;
  1081. }
  1082. }
  1083. return env('GEMINI_API_KEY', '');
  1084. }
  1085. /**
  1086. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  1087. */
  1088. private function geminiChatOnly($requestData, $model) {
  1089. $apiKey = $this->getGeminiApiKey($model);
  1090. if (empty($apiKey)) {
  1091. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1092. }
  1093. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1094. if (isset($requestData['messages'])) {
  1095. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1096. }
  1097. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1098. . '/models/' . $model . ':generateContent';
  1099. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1100. $headers = [
  1101. 'Authorization' => 'Bearer ' . $apiKey,
  1102. 'Content-Type' => 'application/json'
  1103. ];
  1104. $maxRetries = $this->gptRetryTimes();
  1105. $interval = $this->gptRetryInterval();
  1106. $attempt = 0;
  1107. while (true) {
  1108. try {
  1109. $response = $client->post($url, [
  1110. 'json' => $requestData,
  1111. 'headers' => $headers
  1112. ]);
  1113. $responseArr = json_decode($response->getBody()->getContents(), true);
  1114. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  1115. $fullContent = $this->extractGeminiContent($responseArr);
  1116. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  1117. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  1118. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  1119. ? $responseArr['candidates'][0]['finishReason']
  1120. : '';
  1121. return [
  1122. 'fullContent' => $fullContent,
  1123. 'fullReasoningContent' => $fullReasoningContent,
  1124. 'usage' => $usage,
  1125. 'finish_reason' => $finishReason
  1126. ];
  1127. } catch (\Exception $e) {
  1128. $retryable = true;
  1129. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1130. $status = $e->getResponse()->getStatusCode();
  1131. $retryable = $status >= 500 || $status == 429;
  1132. }
  1133. if (!$retryable || $attempt >= $maxRetries) {
  1134. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  1135. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  1136. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  1137. }
  1138. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  1139. 'retry' => $attempt + 1,
  1140. 'max_retries' => $maxRetries,
  1141. 'error' => $e->getMessage()
  1142. ]);
  1143. sleep($interval);
  1144. $attempt++;
  1145. }
  1146. }
  1147. }
  1148. /**
  1149. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  1150. */
  1151. private function geminiStreamResponse($requestData, $model) {
  1152. $apiKey = $this->getGeminiApiKey($model);
  1153. if (empty($apiKey)) {
  1154. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1155. }
  1156. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1157. if (isset($requestData['messages'])) {
  1158. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1159. }
  1160. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1161. . '/models/' . $model . ':generateContent?alt=sse';
  1162. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1163. $headers = [
  1164. 'Authorization' => 'Bearer ' . $apiKey,
  1165. 'Content-Type' => 'application/json'
  1166. ];
  1167. try {
  1168. $response = $client->post($url, [
  1169. 'json' => $requestData,
  1170. 'headers' => $headers,
  1171. 'stream' => true
  1172. ]);
  1173. $body = $response->getBody();
  1174. $fullContent = '';
  1175. $fullReasoningContent = '';
  1176. $usage = [];
  1177. $buffer = '';
  1178. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1179. while (!$body->eof()) {
  1180. $chunk = $body->read(1024);
  1181. $buffer .= $chunk;
  1182. $lines = explode("\n", $buffer);
  1183. $buffer = array_pop($lines);
  1184. foreach ($lines as $line) {
  1185. $line = trim($line);
  1186. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1187. continue;
  1188. }
  1189. $data = substr($line, 6);
  1190. if ($data === '[DONE]') {
  1191. break 2;
  1192. }
  1193. try {
  1194. $json = json_decode($data, true);
  1195. if (json_last_error() !== JSON_ERROR_NONE) {
  1196. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1197. continue;
  1198. }
  1199. // 思考内容(thoughts)
  1200. $thoughts = $this->extractGeminiThoughts($json);
  1201. if ($thoughts !== '') {
  1202. $fullReasoningContent .= $thoughts;
  1203. yield [
  1204. 'type' => 'reasoning',
  1205. 'content' => $thoughts,
  1206. 'full_reasoning' => $fullReasoningContent
  1207. ];
  1208. }
  1209. // 回答内容
  1210. $partText = $this->extractGeminiContent($json);
  1211. if ($partText !== '') {
  1212. $fullContent .= $partText;
  1213. yield [
  1214. 'type' => 'content',
  1215. 'content' => $partText,
  1216. ];
  1217. }
  1218. // 使用统计
  1219. if (isset($json['usageMetadata'])) {
  1220. $usage = $json['usageMetadata'];
  1221. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  1222. }
  1223. } catch (\Exception $e) {
  1224. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1225. continue;
  1226. }
  1227. }
  1228. }
  1229. dLog('deepseek')->info('Gemini流式读取完成', [
  1230. 'content_length' => strlen($fullContent),
  1231. 'reasoning_length' => strlen($fullReasoningContent)
  1232. ]);
  1233. yield [
  1234. 'type' => 'done',
  1235. 'full_content' => $fullContent,
  1236. 'full_reasoning' => $fullReasoningContent,
  1237. 'usage' => $usage
  1238. ];
  1239. } catch (\Exception $e) {
  1240. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  1241. yield [
  1242. 'type' => 'error',
  1243. 'msg' => $e->getMessage(),
  1244. 'code' => $e->getCode()
  1245. ];
  1246. }
  1247. }
  1248. /**
  1249. * 从 Gemini 响应中提取回答文本
  1250. */
  1251. private function extractGeminiContent($responseArr) {
  1252. $text = '';
  1253. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  1254. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  1255. if (isset($part['text'])) {
  1256. $text .= $part['text'];
  1257. }
  1258. }
  1259. }
  1260. return $text;
  1261. }
  1262. /**
  1263. * 从 Gemini 响应中提取思考内容
  1264. */
  1265. private function extractGeminiReasoningContent($responseArr) {
  1266. $reasoning = '';
  1267. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1268. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1269. if (isset($thought['text'])) {
  1270. $reasoning .= $thought['text'];
  1271. }
  1272. }
  1273. }
  1274. return $reasoning;
  1275. }
  1276. /**
  1277. * 从 Gemini 流式响应中提取本次增量思考内容
  1278. */
  1279. private function extractGeminiThoughts($responseArr) {
  1280. $thoughts = '';
  1281. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1282. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1283. if (isset($thought['text'])) {
  1284. $thoughts .= $thought['text'];
  1285. }
  1286. }
  1287. }
  1288. return $thoughts;
  1289. }
  1290. /**
  1291. * 提取消息数组中的纯文本
  1292. */
  1293. private function extractGeminiTextFromParts($parts) {
  1294. $text = '';
  1295. if (is_array($parts)) {
  1296. foreach ($parts as $part) {
  1297. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  1298. $text .= (string)getProp($part, 'text', '');
  1299. }
  1300. }
  1301. }
  1302. return $text;
  1303. }
  1304. /**
  1305. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  1306. *
  1307. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  1308. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  1309. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  1310. *
  1311. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  1312. * @return array|null ['mime_type' => string, 'data' => string]
  1313. */
  1314. private function processMediaToInlineData($media) {
  1315. if (empty($media)) {
  1316. return null;
  1317. }
  1318. $localPath = null;
  1319. $isTempFile = false;
  1320. try {
  1321. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  1322. if (is_string($media) && strpos($media, 'data:') === 0) {
  1323. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  1324. return [
  1325. 'mime_type' => $matches[1],
  1326. 'data' => $matches[2]
  1327. ];
  1328. }
  1329. return null;
  1330. }
  1331. // 2. 获取本地文件路径
  1332. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  1333. $localPath = $this->downloadMediaToTemp($media);
  1334. $isTempFile = true;
  1335. } elseif (is_string($media)) {
  1336. $localPath = $media;
  1337. } else {
  1338. // Laravel UploadedFile 对象
  1339. $localPath = $media->getRealPath();
  1340. }
  1341. if (!$localPath || !file_exists($localPath)) {
  1342. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  1343. return null;
  1344. }
  1345. $fileSize = filesize($localPath);
  1346. $maxBytes = $this->geminiMediaMaxBytes();
  1347. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  1348. $mimeType = $this->detectMediaMime($localPath);
  1349. $isVideo = strpos($mimeType, 'video/') === 0;
  1350. $needCompress = $fileSize > $maxBytes;
  1351. $duration = 0;
  1352. if ($isVideo) {
  1353. $duration = $this->getMediaDuration($localPath);
  1354. if ($duration > 300) {
  1355. $needCompress = true;
  1356. }
  1357. }
  1358. $finalPath = $localPath;
  1359. $compressedPath = null;
  1360. if ($needCompress && $this->ffmpegAvailable()) {
  1361. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  1362. if ($compressed && file_exists($compressed)) {
  1363. $compressedPath = $compressed;
  1364. if (filesize($compressed) < $fileSize || $isVideo) {
  1365. $finalPath = $compressed;
  1366. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  1367. } else {
  1368. @unlink($compressed);
  1369. $compressedPath = null;
  1370. }
  1371. }
  1372. }
  1373. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  1374. $finalSize = filesize($finalPath);
  1375. if ($finalSize > $maxBytes) {
  1376. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  1377. 'path' => $localPath,
  1378. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  1379. 'limit_mb' => 14
  1380. ]);
  1381. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  1382. }
  1383. // 兜底校验:视频时长超过5分钟且未能压缩成功
  1384. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  1385. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  1386. }
  1387. $data = base64_encode(file_get_contents($finalPath));
  1388. return [
  1389. 'mime_type' => $mimeType,
  1390. 'data' => $data
  1391. ];
  1392. } catch (\App\Exceptions\ApiException $e) {
  1393. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  1394. throw $e;
  1395. } catch (\Exception $e) {
  1396. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  1397. return null;
  1398. } finally {
  1399. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  1400. @unlink($compressedPath);
  1401. }
  1402. if ($isTempFile && $localPath && file_exists($localPath)) {
  1403. @unlink($localPath);
  1404. }
  1405. }
  1406. }
  1407. /**
  1408. * 下载远程多媒体到临时目录
  1409. *
  1410. * @return string|null 本地临时文件路径
  1411. */
  1412. private function downloadMediaToTemp($url) {
  1413. try {
  1414. $tempDir = storage_path('app/temp/gemini');
  1415. if (!is_dir($tempDir)) {
  1416. mkdir($tempDir, 0775, true);
  1417. }
  1418. $extension = 'tmp';
  1419. $pathInfo = parse_url($url, PHP_URL_PATH);
  1420. if ($pathInfo) {
  1421. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  1422. if ($ext && strlen($ext) <= 10) {
  1423. $extension = strtolower($ext);
  1424. }
  1425. }
  1426. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  1427. $client = new Client(['timeout' => 300, 'verify' => false]);
  1428. $response = $client->get($url, ['sink' => $tmpFile]);
  1429. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  1430. @unlink($tmpFile);
  1431. return null;
  1432. }
  1433. return $tmpFile;
  1434. } catch (\Exception $e) {
  1435. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  1436. return null;
  1437. }
  1438. }
  1439. /**
  1440. * 检测多媒体文件 MIME 类型
  1441. */
  1442. private function detectMediaMime($filePath) {
  1443. $imageInfo = @getimagesize($filePath);
  1444. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  1445. return $imageInfo['mime'];
  1446. }
  1447. // 视频按扩展名粗略判断
  1448. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  1449. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  1450. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  1451. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  1452. if (isset($videoExts[$ext])) {
  1453. return $videoExts[$ext];
  1454. }
  1455. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  1456. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  1457. if (isset($imageExts[$ext])) {
  1458. return $imageExts[$ext];
  1459. }
  1460. return 'application/octet-stream';
  1461. }
  1462. /**
  1463. * 获取多媒体时长(秒),非视频或失败返回 0
  1464. */
  1465. private function getMediaDuration($filePath) {
  1466. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  1467. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  1468. $output = trim((string)shell_exec($cmd));
  1469. $duration = (float)$output;
  1470. return $duration > 0 ? $duration : 0;
  1471. }
  1472. /**
  1473. * 检查 ffmpeg 是否可用
  1474. */
  1475. private function ffmpegAvailable() {
  1476. static $available = null;
  1477. if ($available !== null) {
  1478. return $available;
  1479. }
  1480. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1481. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  1482. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  1483. $available = false;
  1484. return $available;
  1485. }
  1486. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  1487. $output = shell_exec($cmd);
  1488. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  1489. return $available;
  1490. }
  1491. /**
  1492. * 使用 ffmpeg 压缩多媒体文件
  1493. *
  1494. * @param string $inputFile 输入文件路径
  1495. * @param bool $isVideo 是否为视频
  1496. * @param float $duration 视频时长(秒),非视频传 0
  1497. * @return string|null 压缩后的文件路径,失败返回 null
  1498. */
  1499. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  1500. try {
  1501. $tempDir = storage_path('app/temp/gemini');
  1502. if (!is_dir($tempDir)) {
  1503. mkdir($tempDir, 0775, true);
  1504. }
  1505. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1506. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  1507. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  1508. if ($isVideo) {
  1509. // 视频:时长超过5分钟则加速压缩到5分钟以内
  1510. $speedFactor = 1.0;
  1511. if ($duration > 300) {
  1512. $speedFactor = $duration / 300;
  1513. }
  1514. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  1515. $finalDuration = $duration / max(1.0, $speedFactor);
  1516. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  1517. $targetBitrate = max(300, min(6000, $targetBitrate));
  1518. $filters = [];
  1519. $filters[] = 'scale=min(1280,iw):-2';
  1520. $filters[] = 'fps=24';
  1521. if ($speedFactor > 1.0) {
  1522. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  1523. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  1524. $fullCount = (int)ceil($speedFactor / 2.0);
  1525. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1526. if ($lastTempo < 0.5) {
  1527. $fullCount++;
  1528. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1529. }
  1530. for ($i = 0; $i < $fullCount; $i++) {
  1531. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  1532. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  1533. }
  1534. }
  1535. $filterStr = implode(',', $filters);
  1536. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  1537. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  1538. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  1539. } else {
  1540. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  1541. $imageInfo = @getimagesize($inputFile);
  1542. $scaleW = 2048;
  1543. $scaleH = 2048;
  1544. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  1545. if ($imageInfo[0] >= $imageInfo[1]) {
  1546. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  1547. $scaleW = 2048;
  1548. } else {
  1549. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  1550. $scaleH = 2048;
  1551. }
  1552. }
  1553. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  1554. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  1555. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  1556. }
  1557. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  1558. $output = shell_exec($cmd);
  1559. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  1560. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  1561. 'input' => $inputFile,
  1562. 'output' => $output
  1563. ]);
  1564. @unlink($outputFile);
  1565. return null;
  1566. }
  1567. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  1568. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  1569. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  1570. ]);
  1571. return $outputFile;
  1572. } catch (\Exception $e) {
  1573. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  1574. return null;
  1575. }
  1576. }
  1577. /**
  1578. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  1579. *
  1580. * @param array $data
  1581. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  1582. */
  1583. public function getScriptGenerateTasks($data) {
  1584. $uid = Site::getUid();
  1585. return DB::table('mp_script_generate_tasks as t')
  1586. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  1587. ->where('t.uid', $uid)
  1588. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  1589. ->orderByDesc('t.id')
  1590. ->paginate(15);
  1591. }
  1592. public function saveScriptChatHistory($data) {
  1593. $uid = Site::getUid();
  1594. $rid = getProp($data, 'rid');
  1595. $script_id = getProp($data, 'script_id');
  1596. $sequence = getProp($data, 'sequence', 0);
  1597. $content = getProp($data, 'content');
  1598. if (!$rid) {
  1599. Utils::throwError('20003:请选择对话记录ID');
  1600. }
  1601. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  1602. if (!$record) {
  1603. Utils::throwError('20003:对话记录不存在');
  1604. }
  1605. if (!$script_id) {
  1606. Utils::throwError('20003:请选择剧本');
  1607. }
  1608. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  1609. if (!$script) {
  1610. Utils::throwError('20003:剧本不存在');
  1611. }
  1612. // 批量插入数据
  1613. return DB::table('mp_script_records')->where('id', $rid)->update([
  1614. 'content' => $content,
  1615. 'updated_at' => date('Y-m-d H:i:s')
  1616. ]);
  1617. }
  1618. /**
  1619. * 获取剧本的历史对话记录
  1620. *
  1621. * @param array $data 请求参数
  1622. * @return array 返回历史记录数组
  1623. */
  1624. public function getScriptChatHistory($data) {
  1625. $uid = Site::getUid();
  1626. $script_id = getProp($data, 'script_id');
  1627. $rid = getProp($data, 'rid');
  1628. $sequence = getProp($data, 'sequence', null);
  1629. if (!$script_id) {
  1630. Utils::throwError('20003:请提供剧本ID');
  1631. }
  1632. // 验证剧本是否存在
  1633. $script = DB::table('mp_scripts')
  1634. ->where('id', $script_id)
  1635. ->where('is_deleted', 0)
  1636. ->first();
  1637. if (!$script) {
  1638. Utils::throwError('20003:剧本不存在');
  1639. }
  1640. // 构建查询
  1641. $query = DB::table('mp_script_records')
  1642. ->where('script_id', $script_id);
  1643. // ->where('uid', $uid);
  1644. // 如果提供了 sequence,则过滤指定剧集
  1645. if ($sequence !== null) {
  1646. $query->where('sequence', $sequence);
  1647. }
  1648. // 记录ID筛选
  1649. if ($rid) {
  1650. $query->where('id', $rid);
  1651. }
  1652. // 查询记录并按 id 正序排序
  1653. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  1654. ->orderBy('created_at', 'asc')
  1655. ->orderBy('id', 'asc')
  1656. ->get()
  1657. ->map(function ($record) {
  1658. return [
  1659. 'rid' => $record->id,
  1660. 'script_id' => $record->script_id,
  1661. 'sequence' => $record->sequence,
  1662. 'role' => $record->role,
  1663. 'content' => $record->content,
  1664. 'products' => $record->products ? json_decode($record->products) : [],
  1665. 'created_at' => $record->created_at,
  1666. ];
  1667. })
  1668. ->toArray();
  1669. return $records;
  1670. }
  1671. /**
  1672. * 处理图片转换为base64
  1673. *
  1674. * @param mixed $image 图片文件对象或文件路径
  1675. * @return string|null base64编码的图片数据
  1676. */
  1677. private function processImageToBase64($image) {
  1678. try {
  1679. // 获取文件路径
  1680. if (is_string($image)) {
  1681. $filePath = $image;
  1682. } else {
  1683. // Laravel UploadedFile 对象
  1684. $filePath = $image->getRealPath();
  1685. }
  1686. if (!file_exists($filePath)) {
  1687. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  1688. return null;
  1689. }
  1690. // 验证是否为图片文件
  1691. $imageInfo = @getimagesize($filePath);
  1692. if ($imageInfo === false) {
  1693. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  1694. return null;
  1695. }
  1696. // 读取图片并转换为base64
  1697. $imageData = file_get_contents($filePath);
  1698. $base64Image = base64_encode($imageData);
  1699. dLog('deepseek')->info('图片转换成功', [
  1700. 'size' => strlen($imageData),
  1701. 'type' => $imageInfo['mime']
  1702. ]);
  1703. return $base64Image;
  1704. } catch (\Exception $e) {
  1705. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  1706. return null;
  1707. }
  1708. }
  1709. private function getArtStylePromptMappings($art_style='')
  1710. {
  1711. $arr = [
  1712. '唯美真人风格' => [
  1713. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  1714. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  1715. ],
  1716. '真人古风风格' => [
  1717. 'aliases' => ['真人古风风格', '真人古风'],
  1718. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  1719. ],
  1720. '日系动漫风格' => [
  1721. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  1722. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  1723. ],
  1724. '国漫风格' => [
  1725. 'aliases' => ['国漫风格', '国漫'],
  1726. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  1727. ],
  1728. 'Q版卡通风格' => [
  1729. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  1730. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  1731. ],
  1732. '简约扁平风格' => [
  1733. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  1734. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  1735. ],
  1736. '武侠风格' => [
  1737. 'aliases' => ['武侠风格', '武侠'],
  1738. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  1739. ],
  1740. '古风仙侠风格' => [
  1741. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  1742. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  1743. ],
  1744. '新中式水墨风格' => [
  1745. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  1746. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  1747. ],
  1748. '写实插画风格' => [
  1749. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  1750. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  1751. ],
  1752. '3D卡通风格' => [
  1753. 'aliases' => ['3D卡通风格', '3D卡通'],
  1754. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  1755. ],
  1756. '条漫风格' => [
  1757. 'aliases' => ['条漫风格', '条漫'],
  1758. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  1759. ],
  1760. '赛博朋克风格' => [
  1761. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  1762. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  1763. ],
  1764. '暗黑悬疑风格' => [
  1765. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  1766. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  1767. ],
  1768. '治愈清新风格' => [
  1769. 'aliases' => ['治愈清新风格', '治愈清新'],
  1770. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  1771. ],
  1772. '3D真人风格' => [
  1773. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  1774. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  1775. ],
  1776. ];
  1777. if($art_style) {
  1778. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  1779. }
  1780. return $arr;
  1781. $arr = [
  1782. '唯美真人风格' => [
  1783. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  1784. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  1785. 2. 色彩色调
  1786. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  1787. 3. 画质精度
  1788. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  1789. 4. 画面观感
  1790. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  1791. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  1792. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  1793. ],
  1794. '真人古风风格' => [
  1795. 'aliases' => ['真人古风风格', '真人古风'],
  1796. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  1797. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  1798. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  1799. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  1800. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  1801. ],
  1802. '日系动漫风格' => [
  1803. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  1804. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  1805. 正向提示词(中文)
  1806. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  1807. 必须遵守规则
  1808. • 全程保持日系动漫风格,不混入其他画风
  1809. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  1810. • 画面适配所选画面比例,构图居中,主体突出
  1811. • 线条干净、色彩统一,不杂乱、不突兀
  1812. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  1813. ],
  1814. '国漫风格' => [
  1815. 'aliases' => ['国漫风格', '国漫'],
  1816. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  1817. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  1818. 必须遵守规则
  1819. • 严格保持国漫画风,不串风格、不混画风
  1820. • 角色形象统一,不随意改变五官、身材、服饰
  1821. • 画面构图稳定,适合漫剧叙事展示
  1822. • 色调统一,不出现脏色、杂色
  1823. 禁止/避免词汇
  1824. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  1825. ],
  1826. 'Q版卡通风格' => [
  1827. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  1828. 'prompt' => "风格说明
  1829. 头大身小,造型可爱圆润,简约干净
  1830. 正向提示词(中文)
  1831. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  1832. 必须遵守规则
  1833. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  1834. • 角色造型统一,表情可爱,不诡异
  1835. • 画面简洁清爽,无多余复杂元素
  1836. • 色彩明亮柔和,不刺眼
  1837. 禁止/避免词汇
  1838. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  1839. ],
  1840. '简约扁平风格' => [
  1841. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  1842. 'prompt' => "风格说明
  1843. 色块简洁、无复杂渐变,现代极简风
  1844. 正向提示词(中文)
  1845. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  1846. 必须遵守规则
  1847. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  1848. • 构图简洁,主体突出,无多余装饰
  1849. • 色彩统一、干净,不杂乱
  1850. 禁止/避免词汇
  1851. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  1852. ],
  1853. '武侠风格' => [
  1854. 'aliases' => ['武侠风格', '武侠'],
  1855. 'prompt' => "风格说明
  1856. 江湖气息,线条硬朗,动作感强
  1857. 正向提示词(中文)
  1858. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  1859. 必须遵守规则
  1860. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  1861. • 角色形象、服饰、身材比例统一
  1862. • 画面动作自然,不扭曲、不畸形
  1863. 禁止/避免词汇
  1864. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  1865. ],
  1866. '古风仙侠风格' => [
  1867. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  1868. 'prompt' => "风格说明
  1869. 飘逸汉服、云雾仙气、唯美空灵
  1870. 正向提示词(中文)
  1871. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  1872. 必须遵守规则
  1873. • 保持古风仙侠统一画风,不混入现代、科幻元素
  1874. • 角色服饰、发型、形象前后一致
  1875. • 场景仙气飘逸,色调清雅统一
  1876. • 画面唯美柔和,不阴暗、不诡异
  1877. 禁止/避免词汇
  1878. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  1879. ],
  1880. '新中式水墨风格' => [
  1881. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  1882. 'prompt' => "风格说明
  1883. 淡墨渲染,毛笔笔触,留白意境
  1884. 正向提示词(中文)
  1885. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  1886. 必须遵守规则
  1887. • 严格保持水墨质感,不混入厚涂、写实、卡通
  1888. • 色调淡雅统一,不浓艳杂乱
  1889. • 画面干净有意境,不堆砌元素
  1890. 禁止/避免词汇
  1891. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  1892. ],
  1893. '写实插画风格' => [
  1894. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  1895. 'prompt' => "风格说明
  1896. 接近真人比例,光影真实,质感细腻
  1897. 正向提示词(中文)
  1898. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  1899. 必须遵守规则
  1900. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  1901. • 角色五官、身材、服饰高度统一
  1902. • 画面清晰、光影自然、不扭曲
  1903. 禁止/避免词汇
  1904. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  1905. ],
  1906. '3D卡通风格' => [
  1907. 'aliases' => ['3D卡通风格', '3D卡通'],
  1908. 'prompt' => "风格说明
  1909. 3D建模质感,柔和渲染,圆润可爱
  1910. 正向提示词(中文)
  1911. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  1912. 必须遵守规则
  1913. • 保持3D卡通统一质感,不出现2D杂乱线条
  1914. • 角色模型、比例、形象前后一致
  1915. • 画面干净,不模糊、不穿模
  1916. 禁止/避免词汇
  1917. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  1918. ],
  1919. '条漫风格' => [
  1920. 'aliases' => ['条漫风格', '条漫'],
  1921. 'prompt' => "风格说明
  1922. 纵向分镜,上下滑动阅读,轻量化
  1923. 正向提示词(中文)
  1924. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  1925. 必须遵守规则
  1926. • 保持条漫纵向阅读逻辑,构图简洁
  1927. • 画风统一,不混写实、3D、水墨
  1928. • 画面干净,不杂乱
  1929. 禁止/避免词汇
  1930. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  1931. ],
  1932. '赛博朋克风格' => [
  1933. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  1934. 'prompt' => "风格说明
  1935. 霓虹灯光、未来都市、暗色调、科技机械
  1936. 正向提示词(中文)
  1937. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  1938. 必须遵守规则
  1939. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  1940. • 色调以暗调+霓虹为主,色彩统一
  1941. • 画面科技感强,不杂乱
  1942. 禁止/避免词汇
  1943. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  1944. ],
  1945. '暗黑悬疑风格' => [
  1946. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  1947. 'prompt' => "风格说明
  1948. 低饱和、冷色调、阴影重、神秘压抑
  1949. 正向提示词(中文)
  1950. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  1951. 必须遵守规则
  1952. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  1953. • 画面氛围压抑神秘,但不低俗、不血腥
  1954. • 角色形象统一,不崩坏
  1955. 禁止/避免词汇
  1956. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  1957. ],
  1958. '治愈清新风格' => [
  1959. 'aliases' => ['治愈清新风格', '治愈清新'],
  1960. 'prompt' => "风格说明
  1961. 马卡龙色系、柔光、温暖干净
  1962. 正向提示词(中文)
  1963. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  1964. 必须遵守规则
  1965. • 保持治愈清新统一色调,不阴暗、不诡异
  1966. • 画面柔和干净,无杂乱元素
  1967. • 角色形象柔和可爱,不狰狞
  1968. 禁止/避免词汇
  1969. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  1970. ],
  1971. ];
  1972. return $arr;
  1973. }
  1974. public function getArtStylePromptByInput($inputArtStyle): string
  1975. {
  1976. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  1977. if ($normalizedInput === '') {
  1978. return '';
  1979. }
  1980. return $this->getArtStylePromptMappings($normalizedInput);
  1981. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  1982. // foreach ($mapping['aliases'] as $alias) {
  1983. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  1984. // if ($normalizedAlias === '') {
  1985. // continue;
  1986. // }
  1987. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  1988. // return $mapping['prompt'];
  1989. // }
  1990. // }
  1991. // }
  1992. return '';
  1993. }
  1994. public function getArtStyleShortPromptByInput($inputArtStyle) {
  1995. $stylePrefixes = [
  1996. '唯美真人风格' => [
  1997. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  1998. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  1999. ],
  2000. '真人古风风格' => [
  2001. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  2002. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  2003. ],
  2004. '日系动漫风格' => [
  2005. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  2006. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  2007. ],
  2008. '国漫风格' => [
  2009. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  2010. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  2011. ],
  2012. 'Q版卡通风格' => [
  2013. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  2014. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  2015. ],
  2016. '简约扁平风格' => [
  2017. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  2018. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  2019. ],
  2020. '武侠风格' => [
  2021. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  2022. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  2023. ],
  2024. '古风仙侠风格' => [
  2025. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  2026. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  2027. ],
  2028. '新中式水墨风格' => [
  2029. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  2030. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  2031. ],
  2032. '写实插画风格' => [
  2033. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  2034. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  2035. ],
  2036. '3D卡通风格' => [
  2037. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  2038. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  2039. ],
  2040. '条漫风格' => [
  2041. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  2042. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  2043. ],
  2044. '赛博朋克风格' => [
  2045. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  2046. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  2047. ],
  2048. '暗黑悬疑风格' => [
  2049. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  2050. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  2051. ],
  2052. '治愈清新风格' => [
  2053. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  2054. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  2055. ]
  2056. ];
  2057. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  2058. }
  2059. private function normalizeArtStyleInput($value): string
  2060. {
  2061. $value = trim((string)$value);
  2062. if ($value === '') {
  2063. return '';
  2064. }
  2065. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  2066. return mb_strtolower($value, 'UTF-8');
  2067. }
  2068. private function replaceArtStyleSection(string $content, string $artStyle): string
  2069. {
  2070. if ($content === '' || $artStyle === '') {
  2071. return $content;
  2072. }
  2073. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  2074. if (!preg_match($pattern, $content)) {
  2075. return $content;
  2076. }
  2077. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  2078. }
  2079. /**
  2080. * DeepSeek流式输出处理方法
  2081. *
  2082. * @param array $post_data DeepSeek API请求参数
  2083. * @return \Generator 返回生成器,用于流式输出
  2084. */
  2085. private function deepSeekStreamResponse($post_data) {
  2086. // 设置最大输出tokens
  2087. $post_data['max_tokens'] = 300000;
  2088. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2089. $post_data['stream_options'] = ['include_usage' => true];
  2090. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2091. $response = $client->post($this->url, [
  2092. 'json' => $post_data,
  2093. 'headers' => $this->headers,
  2094. 'stream' => true // 启用流式响应
  2095. ]);
  2096. $body = $response->getBody();
  2097. $fullContent = '';
  2098. $fullReasoningContent = '';
  2099. $usage = [];
  2100. $buffer = '';
  2101. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  2102. // 逐行读取流式响应
  2103. while (!$body->eof()) {
  2104. $chunk = $body->read(1024); // 每次读取 1KB
  2105. $buffer .= $chunk;
  2106. // 按行分割
  2107. $lines = explode("\n", $buffer);
  2108. // 保留最后一个不完整的行
  2109. $buffer = array_pop($lines);
  2110. foreach ($lines as $line) {
  2111. $line = trim($line);
  2112. // 跳过空行
  2113. if (empty($line)) {
  2114. continue;
  2115. }
  2116. // 检查是否是 SSE 数据行
  2117. if (strpos($line, 'data: ') !== 0) {
  2118. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2119. continue;
  2120. }
  2121. $data = substr($line, 6); // 移除 "data: " 前缀
  2122. if ($data === '[DONE]') {
  2123. dLog('deepseek')->info('收到结束标记');
  2124. break 2; // 跳出两层循环
  2125. }
  2126. try {
  2127. $json = json_decode($data, true);
  2128. if (json_last_error() !== JSON_ERROR_NONE) {
  2129. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2130. continue;
  2131. }
  2132. if (isset($json['choices'][0]['delta'])) {
  2133. $delta = $json['choices'][0]['delta'];
  2134. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2135. if (isset($delta['reasoning_content'])) {
  2136. $fullReasoningContent .= $delta['reasoning_content'];
  2137. yield [
  2138. 'type' => 'reasoning',
  2139. 'content' => $delta['reasoning_content'],
  2140. 'full_reasoning' => $fullReasoningContent
  2141. ];
  2142. }
  2143. // 处理最终回答内容
  2144. if (isset($delta['content'])) {
  2145. $fullContent .= $delta['content'];
  2146. yield [
  2147. 'type' => 'content',
  2148. 'content' => $delta['content'],
  2149. ];
  2150. }
  2151. }
  2152. // 获取使用统计信息
  2153. if (isset($json['usage'])) {
  2154. $usage = $json['usage'];
  2155. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2156. }
  2157. } catch (\Exception $e) {
  2158. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2159. continue;
  2160. }
  2161. }
  2162. }
  2163. dLog('deepseek')->info('流式读取完成', [
  2164. 'content_length' => strlen($fullContent),
  2165. 'reasoning_length' => strlen($fullReasoningContent)
  2166. ]);
  2167. yield [
  2168. 'type' => 'done',
  2169. 'full_content' => $fullContent,
  2170. 'full_reasoning' => $fullReasoningContent,
  2171. 'usage' => $usage
  2172. ];
  2173. }
  2174. /**
  2175. * GPT 重试次数(env 可配置,默认 5 次)
  2176. */
  2177. private function gptRetryTimes()
  2178. {
  2179. return (int)env('GPT_RETRY_TIMES', 5);
  2180. }
  2181. /**
  2182. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  2183. */
  2184. private function gptRetryInterval()
  2185. {
  2186. return (int)env('GPT_RETRY_INTERVAL', 10);
  2187. }
  2188. /**
  2189. * 判断 GPT 请求异常是否可重试
  2190. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  2191. */
  2192. private function isGptRetryableException(\Exception $e)
  2193. {
  2194. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  2195. return false;
  2196. }
  2197. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  2198. $status = $e->getResponse()->getStatusCode();
  2199. return $status >= 500 || $status == 429;
  2200. }
  2201. return true;
  2202. }
  2203. /**
  2204. * GPT 中转站探活:GET /v1/models,5 秒短超时
  2205. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  2206. */
  2207. private function checkGptServiceAvailable()
  2208. {
  2209. $apiKey = env('GPT_54_API_KEY');
  2210. if (empty($apiKey)) {
  2211. return false;
  2212. }
  2213. try {
  2214. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  2215. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  2216. 'headers' => [
  2217. 'Authorization' => 'Bearer ' . $apiKey,
  2218. 'Content-Type' => 'application/json'
  2219. ]
  2220. ]);
  2221. $status = $response->getStatusCode();
  2222. return $status < 500 && $status != 429;
  2223. } catch (\Exception $e) {
  2224. return false;
  2225. }
  2226. }
  2227. /**
  2228. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  2229. * 全部失败抛出友好错误
  2230. */
  2231. private function ensureGptServiceAvailable()
  2232. {
  2233. $maxRetries = $this->gptRetryTimes();
  2234. $interval = $this->gptRetryInterval();
  2235. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  2236. if ($this->checkGptServiceAvailable()) {
  2237. return;
  2238. }
  2239. if ($attempt < $maxRetries) {
  2240. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  2241. 'retry' => $attempt + 1,
  2242. 'max_retries' => $maxRetries
  2243. ]);
  2244. sleep($interval);
  2245. }
  2246. }
  2247. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  2248. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  2249. 'max_retries' => $maxRetries,
  2250. 'interval' => $interval
  2251. ]);
  2252. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  2253. }
  2254. /**
  2255. * GPT 流式输出处理方法
  2256. *
  2257. * @param array $post_data GPT API请求参数
  2258. * @return \Generator 返回生成器,用于流式输出
  2259. */
  2260. private function gpt54StreamResponse($post_data) {
  2261. $apiKey = env('GPT_54_API_KEY');
  2262. if (empty($apiKey)) {
  2263. Utils::throwError('20003:GPT API Key未配置');
  2264. }
  2265. // 先探活,服务不可用时自动重试
  2266. $this->ensureGptServiceAvailable();
  2267. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2268. $headers = [
  2269. 'Authorization' => 'Bearer ' . $apiKey,
  2270. 'Content-Type' => 'application/json'
  2271. ];
  2272. // 移除 thinking 参数,GPT-5.4 不支持
  2273. if (isset($post_data['thinking'])) {
  2274. unset($post_data['thinking']);
  2275. }
  2276. if (isset($post_data['reasoning_effort'])) {
  2277. unset($post_data['reasoning_effort']);
  2278. }
  2279. $post_data['max_completion_tokens'] = 100000;
  2280. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2281. $post_data['stream_options'] = ['include_usage' => true];
  2282. $maxRetries = $this->gptRetryTimes();
  2283. $interval = $this->gptRetryInterval();
  2284. $attempt = 0;
  2285. while (true) {
  2286. $fullContent = '';
  2287. $usage = [];
  2288. $buffer = '';
  2289. try {
  2290. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  2291. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  2292. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  2293. 'json' => $post_data,
  2294. 'headers' => $headers,
  2295. 'stream' => true // 启用流式响应
  2296. ]);
  2297. $body = $response->getBody();
  2298. dLog('deepseek')->info('开始读取 GPT 流式响应');
  2299. // 逐行读取流式响应
  2300. while (!$body->eof()) {
  2301. $chunk = $body->read(1024); // 每次读取 1KB
  2302. $buffer .= $chunk;
  2303. // 按行分割
  2304. $lines = explode("\n", $buffer);
  2305. // 保留最后一个不完整的行
  2306. $buffer = array_pop($lines);
  2307. foreach ($lines as $line) {
  2308. $line = trim($line);
  2309. // 跳过空行
  2310. if (empty($line)) {
  2311. continue;
  2312. }
  2313. // 检查是否是 SSE 数据行
  2314. if (strpos($line, 'data: ') !== 0) {
  2315. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2316. continue;
  2317. }
  2318. $data = substr($line, 6); // 移除 "data: " 前缀
  2319. if ($data === '[DONE]') {
  2320. dLog('deepseek')->info('收到结束标记');
  2321. break 2; // 跳出 foreach 和流读取循环
  2322. }
  2323. try {
  2324. $json = json_decode($data, true);
  2325. if (json_last_error() !== JSON_ERROR_NONE) {
  2326. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2327. continue;
  2328. }
  2329. if (isset($json['choices'][0]['delta'])) {
  2330. $delta = $json['choices'][0]['delta'];
  2331. // 处理回答内容
  2332. if (isset($delta['content'])) {
  2333. $fullContent .= $delta['content'];
  2334. yield [
  2335. 'type' => 'content',
  2336. 'content' => $delta['content'],
  2337. ];
  2338. }
  2339. }
  2340. // 获取使用统计信息
  2341. if (isset($json['usage'])) {
  2342. $usage = $json['usage'];
  2343. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2344. }
  2345. } catch (\Exception $e) {
  2346. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2347. continue;
  2348. }
  2349. }
  2350. }
  2351. dLog('deepseek')->info('流式读取完成', [
  2352. 'content_length' => strlen($fullContent)
  2353. ]);
  2354. yield [
  2355. 'type' => 'done',
  2356. 'full_content' => $fullContent,
  2357. 'full_reasoning' => '',
  2358. 'usage' => $usage
  2359. ];
  2360. return;
  2361. } catch (\Exception $e) {
  2362. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  2363. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  2364. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  2365. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  2366. throw $e;
  2367. }
  2368. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  2369. 'retry' => $attempt + 1,
  2370. 'max_retries' => $maxRetries,
  2371. 'error' => $e->getMessage()
  2372. ]);
  2373. sleep($interval);
  2374. $attempt++;
  2375. }
  2376. }
  2377. }
  2378. // 与推理模型对话
  2379. public function chatWithReasoner($data) {
  2380. $content = getProp($data, 'content');
  2381. $model = getProp($data, 'model', 'r1');
  2382. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2383. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2384. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2385. if ($model == 'r1') {
  2386. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  2387. $thinkingMode = 'disabled';
  2388. } else {
  2389. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  2390. $thinkingMode = 'disabled';
  2391. }
  2392. // 获取可选情感(根据音色可支持情感选)
  2393. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  2394. $emotion_list = [];
  2395. foreach ($timbre_emotion as $emotion) {
  2396. $tmp = explode(',', $emotion);
  2397. $emotion_list = array_merge($emotion_list, $tmp);
  2398. }
  2399. $emotion_list = array_unique($emotion_list);
  2400. $emotion_str = implode('、', $emotion_list);
  2401. // // 获取可选情感
  2402. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  2403. // $emotion_str = implode('、', $emotion_list);
  2404. // 是否启用情感
  2405. $enable_emotion = getProp($data, 'enable_emotion', 0);
  2406. if ($enable_emotion) {
  2407. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  2408. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2409. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  2410. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  2411. }else {
  2412. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  2413. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2414. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  2415. }
  2416. $messages = [
  2417. [
  2418. 'role' => 'system',
  2419. 'content' => $sys_content
  2420. ],
  2421. [
  2422. 'role' => 'user',
  2423. 'content' => $content
  2424. ]
  2425. ];
  2426. $post_data = [
  2427. 'model' => $model,
  2428. 'messages' => $messages,
  2429. // 'max_tokens' => 8192,
  2430. 'temperature' => 1,
  2431. 'frequency_penalty' => 0,
  2432. 'presence_penalty' => 0,
  2433. 'thinking' => ['type' => $thinkingMode],
  2434. 'response_format' => [
  2435. 'type' => 'text'
  2436. ],
  2437. 'stream' => false
  2438. ];
  2439. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2440. // 根据模型类型选择调用方法
  2441. $fullContent = '';
  2442. $usage = [];
  2443. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2444. // DeepSeek 官方模型使用 DeepSeek API
  2445. $chatResult = $this->chatOnly($post_data);
  2446. } else if (in_array($model, $this->gpt_text_models)) {
  2447. // GPT-5.4 模型使用 TokenRouter API
  2448. $chatResult = $this->gpt54ChatOnly($post_data);
  2449. } else {
  2450. // 其他模型使用火山引擎API
  2451. $chatResult = $this->volcEngineChatCompletion($post_data);
  2452. }
  2453. if (is_array($chatResult)) {
  2454. $fullContent = $chatResult['fullContent'];
  2455. $usage = $chatResult['usage'];
  2456. }
  2457. // 处理获取到的剧本数据
  2458. $script_content = handleScriptWords($fullContent, $enable_emotion);
  2459. $result = [
  2460. 'origin_content' => $fullContent,
  2461. 'roles' => getProp($script_content, 'roles'),
  2462. 'words' => getProp($script_content, 'words'),
  2463. ];
  2464. return $result;
  2465. }
  2466. public function resetParagraphAudio($data) {
  2467. $bid = getProp($data, 'bid');
  2468. $cid = getProp($data, 'cid');
  2469. $version_id = getProp($data, 'version_id');
  2470. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  2471. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  2472. 'generate_status' => '待制作',
  2473. 'updated_at' => date('Y-m-d H:i:s')
  2474. ]);
  2475. }
  2476. public function saveParagraphAudio($data) {
  2477. $bid = getProp($data, 'bid');
  2478. $cid = getProp($data, 'cid');
  2479. $version_id = getProp($data, 'version_id');
  2480. $sequence = getProp($data, 'sequence');
  2481. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  2482. // 获取所有情感
  2483. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  2484. $emotion_list = array_flip($emotion_list);
  2485. // 获取音色支持情感
  2486. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  2487. $timbre_emotion = explode(',', $timbre_emotion);
  2488. $emotion = getProp($data, 'emotion');
  2489. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  2490. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  2491. $list = [
  2492. 'bid' => $bid,
  2493. 'cid' => $cid,
  2494. 'version_id' => $version_id,
  2495. 'sequence' => $sequence,
  2496. 'role' => getProp($data, 'role'),
  2497. 'gender' => getProp($data, 'gender'),
  2498. 'text' => trim(getProp($data, 'text')),
  2499. 'emotion' => $emotion,
  2500. 'emotion_type' => $emotion_type,
  2501. 'voice_type' => getProp($data, 'voice_type'),
  2502. 'voice_name' => getProp($data, 'voice_name'),
  2503. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  2504. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  2505. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  2506. 'pitch' => getProp($data, 'pitch', 0),
  2507. // 'paragraph_audio_url' => '',
  2508. 'generate_status' => '制作中',
  2509. 'error_msg' => '',
  2510. 'updated_at' => date('Y-m-d H:i:s')
  2511. ];
  2512. $continue = false;
  2513. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  2514. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  2515. $list['generate_status'] = '制作成功';
  2516. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2517. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  2518. $continue = true;
  2519. }
  2520. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  2521. if ($id) {
  2522. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  2523. }else {
  2524. $list['created_at'] = date('Y-m-d H:i:s');
  2525. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  2526. $boolen = $id ? true : false;
  2527. }
  2528. // 如果更新成功则加入查询队列
  2529. if ($boolen) {
  2530. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  2531. Redis::sadd($redis_key, $id);
  2532. }
  2533. if ($boolen && !$continue) {
  2534. $boolen = false;
  2535. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2536. // 根据ID通过API通知合成音频
  2537. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  2538. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  2539. $response = $result->getBody()->getContents();
  2540. $response_arr = json_decode($response, true);
  2541. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2542. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2543. Log::info('通知火山生成段落音频失败: '.$error_msg);
  2544. Utils::throwError('20003:通知火山生成段落音频失败');
  2545. }
  2546. $boolen = true;
  2547. }
  2548. return $boolen;
  2549. }
  2550. public function insertAudioEffect($data) {
  2551. $audio_id = getProp($data, 'audio_id');
  2552. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2553. $bid = getProp($chapter_audio, 'bid');
  2554. $version_id = getProp($chapter_audio, 'version_id');
  2555. $cid = getProp($chapter_audio, 'cid');
  2556. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2557. $audio_effect_json = getProp($data, 'audio_effect_json');
  2558. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  2559. try {
  2560. DB::beginTransaction();
  2561. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2562. if (!$count) {
  2563. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2564. }else {
  2565. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2566. }
  2567. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2568. 'audio_effect_status' => '添加中',
  2569. 'audio_effect_json' => $audio_effect_json,
  2570. 'updated_at' => date('Y-m-d H:i:s')
  2571. ]);
  2572. if (!$boolen1) {
  2573. DB::rollBack();
  2574. Utils::throwError('20003:更新生成数据失败');
  2575. }
  2576. $id = DB::table('mp_audio_tasks')->insertGetId([
  2577. 'audio_id' => $audio_id,
  2578. 'generate_status' => '执行中',
  2579. 'generate_json' => json_encode([], 256),
  2580. 'bid' => $bid,
  2581. 'book_name' => getProp($chapter_audio, 'book_name'),
  2582. 'version_id' => $version_id,
  2583. 'version_name' => getProp($chapter_audio, 'version_name'),
  2584. 'cid' => $cid,
  2585. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2586. 'task_name' => $task_name,
  2587. 'created_at' => date('Y-m-d H:i:s'),
  2588. 'updated_at' => date('Y-m-d H:i:s')
  2589. ]);
  2590. if (!$id) {
  2591. DB::rollBack();
  2592. Utils::throwError('20003:创建任务失败');
  2593. }
  2594. }catch (\Exception $e) {
  2595. DB::rollBack();
  2596. Utils::throwError('20003:'.$e->getMessage());
  2597. }
  2598. DB::commit();
  2599. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2600. // 根据ID通过API通知合成音频
  2601. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2602. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2603. $response = $result->getBody()->getContents();
  2604. $response_arr = json_decode($response, true);
  2605. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2606. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2607. Log::info('通知火山插入音效失败: '.$error_msg);
  2608. Utils::throwError('20003:通知火山插入音效失败');
  2609. }
  2610. return true;
  2611. }
  2612. public function insertBgm($data) {
  2613. $audio_id = getProp($data, 'audio_id');
  2614. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2615. $bid = getProp($chapter_audio, 'bid');
  2616. $version_id = getProp($chapter_audio, 'version_id');
  2617. $cid = getProp($chapter_audio, 'cid');
  2618. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2619. $bgm_json = getProp($data, 'bgm_json');
  2620. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2621. if (!$bgm_json) {
  2622. $bgm_json = getProp($data, 'audio_effect_json');
  2623. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2624. }
  2625. try {
  2626. DB::beginTransaction();
  2627. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2628. if (!$count) {
  2629. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2630. }else {
  2631. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2632. }
  2633. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2634. 'bgm_status' => '添加中',
  2635. 'bgm_json' => $bgm_json,
  2636. 'updated_at' => date('Y-m-d H:i:s')
  2637. ]);
  2638. if (!$boolen1) {
  2639. DB::rollBack();
  2640. Utils::throwError('20003:更新生成数据失败');
  2641. }
  2642. $id = DB::table('mp_audio_tasks')->insertGetId([
  2643. 'audio_id' => $audio_id,
  2644. 'generate_status' => '执行中',
  2645. 'generate_json' => json_encode([], 256),
  2646. 'bid' => $bid,
  2647. 'book_name' => getProp($chapter_audio, 'book_name'),
  2648. 'version_id' => $version_id,
  2649. 'version_name' => getProp($chapter_audio, 'version_name'),
  2650. 'cid' => $cid,
  2651. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2652. 'task_name' => $task_name,
  2653. 'created_at' => date('Y-m-d H:i:s'),
  2654. 'updated_at' => date('Y-m-d H:i:s')
  2655. ]);
  2656. if (!$id) {
  2657. DB::rollBack();
  2658. Utils::throwError('20003:创建任务失败');
  2659. }
  2660. }catch (\Exception $e) {
  2661. DB::rollBack();
  2662. Utils::throwError('20003:'.$e->getMessage());
  2663. }
  2664. DB::commit();
  2665. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2666. // 根据ID通过API通知合成音频
  2667. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2668. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2669. $response = $result->getBody()->getContents();
  2670. $response_arr = json_decode($response, true);
  2671. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2672. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2673. Log::info('通知火山插入bgm失败: '.$error_msg);
  2674. Utils::throwError('20003:通知火山插入bgm失败');
  2675. }
  2676. return true;
  2677. }
  2678. public function getParagraphAudios($data) {
  2679. $bid = getProp($data, 'bid');
  2680. $cid = getProp($data, 'cid');
  2681. $version_id = getProp($data, 'version_id');
  2682. $sequence = getProp($data, 'sequence');
  2683. // 获取已生成的音频
  2684. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  2685. if ($sequence) $query->where('sequence', $sequence);
  2686. $paragraph_audios = $query->orderBy('sequence')->get();
  2687. $result = [];
  2688. foreach($paragraph_audios as $item) {
  2689. $result[] = [
  2690. 'sequence' => getProp($item, 'sequence'),
  2691. 'role' => getProp($item, 'role'),
  2692. 'gender' => getProp($item, 'gender'),
  2693. 'text' => trim(getProp($item, 'text')),
  2694. 'emotion' => getProp($item, 'emotion'),
  2695. 'emotion_type' => getProp($item, 'emotion_type'),
  2696. 'voice_type' => getProp($item, 'voice_type'),
  2697. 'voice_name' => getProp($item, 'voice_name'),
  2698. 'speed_ratio' => getProp($item, 'speed_ratio'),
  2699. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  2700. 'emotion_scale' => getProp($item, 'emotion_scale'),
  2701. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  2702. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  2703. ];
  2704. }
  2705. return $result;
  2706. }
  2707. // 新增合成任务
  2708. public function addGenerateTask($data) {
  2709. $bid = getProp($data, 'bid');
  2710. $cid = getProp($data, 'cid');
  2711. $version_id = getProp($data, 'version_id');
  2712. $generate_json = getProp($data, 'generate_json');
  2713. // 获取已生成的音频
  2714. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  2715. $paragraph_list = [];
  2716. foreach($paragraph_audios as $item) {
  2717. $paragraph_list[getProp($item, 'sequence')] = [
  2718. 'role' => getProp($item, 'role'),
  2719. 'gender' => getProp($item, 'gender'),
  2720. 'text' => trim(getProp($item, 'text')),
  2721. 'emotion' => getProp($item, 'emotion'),
  2722. 'emotion_type' => getProp($item, 'emotion_type'),
  2723. 'voice_type' => getProp($item, 'voice_type'),
  2724. 'voice_name' => getProp($item, 'voice_name'),
  2725. 'speed_ratio' => getProp($item, 'speed_ratio'),
  2726. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  2727. 'emotion_scale' => getProp($item, 'emotion_scale'),
  2728. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  2729. ];
  2730. }
  2731. // 更新角色-音色信息
  2732. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  2733. $existed_role_info = json_decode($existed_role_info, true);
  2734. if (!$existed_role_info) $existed_role_info = [];
  2735. // 获取情感信息
  2736. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  2737. $emotion_list = array_flip($emotion_list);
  2738. // 获取音色对应情感组
  2739. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  2740. $timbre_emotion_list = [];
  2741. foreach($timbre_emotions as $item) {
  2742. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  2743. }
  2744. // 构造生成音频的json
  2745. $words = json_decode($generate_json, true);
  2746. // 最终合成前的参数组
  2747. $mp_chapter_paragraph_audios = [];
  2748. $sequence = 1;
  2749. $complete_paragraph_sequences = [];
  2750. foreach($words as &$word) {
  2751. 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:参数格式有误');
  2752. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  2753. $role = getProp($word, 'role');
  2754. $word['gender'] = (int)$word['gender'];
  2755. // 判断音色对应情感是否支持,不支持则调整为中性
  2756. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  2757. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  2758. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  2759. if (isset($emotion_list[getProp($word, 'emotion')])) {
  2760. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  2761. }else {
  2762. $word['emotion'] = '中性';
  2763. $word['emotion_type'] = 'neutral';
  2764. }
  2765. $existed_role_info[$role] = [
  2766. 'timbre_type' => $word['voice_type'],
  2767. 'timbre_name' => $word['voice_name'],
  2768. 'emotion' => $word['emotion'],
  2769. 'emotion_type' => $word['emotion_type'],
  2770. 'speed_ratio' => $word['speed_ratio'],
  2771. 'loudness_ratio'=> $word['loudness_ratio'],
  2772. 'emotion_scale' => $word['emotion_scale'],
  2773. 'pitch' => $word['pitch']
  2774. ];
  2775. $word['paragraph_audio_url'] = '';
  2776. // 判断生成参数是否相同,相同则直接使用已生成的音频
  2777. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  2778. // 如果音频存在并且参数都未改变则使用已生成的音频
  2779. if (getProp($paragraph, 'paragraph_audio_url')) {
  2780. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  2781. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  2782. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  2783. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  2784. // {
  2785. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  2786. // }
  2787. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  2788. }
  2789. $tmp = $word;
  2790. // 组装章节分句音频数据
  2791. // $tmp['sequence'] = getProp($word, 'sequence');
  2792. // $tmp['text'] = getProp($word, 'text');
  2793. // $tmp['emotion'] = getProp($word, 'emotion');
  2794. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  2795. // $tmp['voice_name'] = getProp($word, 'voice_name');
  2796. // $tmp['voice_type'] = getProp($word, 'voice_type');
  2797. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  2798. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  2799. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  2800. $tmp['bid'] = $bid;
  2801. $tmp['version_id'] = $version_id;
  2802. $tmp['cid'] = $cid;
  2803. $tmp['sequence'] = $sequence;
  2804. $tmp['created_at'] = date('Y-m-d H:i:s');
  2805. $tmp['updated_at'] = date('Y-m-d H:i:s');
  2806. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  2807. $mp_chapter_paragraph_audios[] = $tmp;
  2808. $complete_paragraph_sequences[] = $sequence;
  2809. $sequence++;
  2810. }
  2811. $generate_json = json_encode($words, 256);
  2812. // 判断是否有未生成字幕的段落
  2813. $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();
  2814. if ($no_subtitle_sequences) {
  2815. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  2816. }
  2817. try {
  2818. DB::beginTransaction();
  2819. $role_info = json_encode($existed_role_info, 256);
  2820. $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')]);
  2821. if (!$boolen) {
  2822. DB::rollBack();
  2823. Utils::throwError('20003:更新角色信息失败');
  2824. }
  2825. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  2826. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  2827. if (!$count) {
  2828. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2829. }else {
  2830. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2831. }
  2832. $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')]);
  2833. if (!$boolen1) {
  2834. DB::rollBack();
  2835. Utils::throwError('20003:更新生成数据失败');
  2836. }
  2837. $id = DB::table('mp_audio_tasks')->insertGetId([
  2838. 'audio_id' => getProp($chapter_audio, 'id'),
  2839. 'generate_status' => '执行中',
  2840. 'generate_json' => $generate_json,
  2841. 'bid' => $bid,
  2842. 'book_name' => getProp($chapter_audio, 'book_name'),
  2843. 'version_id' => $version_id,
  2844. 'version_name' => getProp($chapter_audio, 'version_name'),
  2845. 'cid' => $cid,
  2846. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2847. 'task_name' => $task_name,
  2848. 'created_at' => date('Y-m-d H:i:s'),
  2849. 'updated_at' => date('Y-m-d H:i:s')
  2850. ]);
  2851. if (!$id) {
  2852. DB::rollBack();
  2853. Utils::throwError('20003:创建任务失败');
  2854. }
  2855. // 删除不在段落序号范围内的其他数据
  2856. if ($complete_paragraph_sequences) {
  2857. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  2858. }
  2859. // // 删除章节分句音频数据并重新插入
  2860. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  2861. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  2862. // if (!$boolen3) {
  2863. // DB::rollBack();
  2864. // Utils::throwError('20003:更新章节分句音频失败');
  2865. // }
  2866. } catch (\Exception $e) {
  2867. DB::rollBack();
  2868. Utils::throwError('20003:'.$e->getMessage());
  2869. }
  2870. DB::commit();
  2871. // 通知火山生成音频
  2872. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2873. // 根据ID通过API通知合成音频
  2874. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  2875. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  2876. $response = $result->getBody()->getContents();
  2877. $response_arr = json_decode($response, true);
  2878. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2879. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2880. Log::info('通知火山生成音频失败: '.$error_msg);
  2881. Utils::throwError('20003:通知火山生成音频失败');
  2882. }
  2883. return true;
  2884. }
  2885. public function timbreList($data) {
  2886. $gender = getProp($data, 'gender');
  2887. $timbre_name = getProp($data, 'voice_name');
  2888. $category_id = getProp($data, 'category_id');
  2889. $age_stage = getProp($data, 'age_stage');
  2890. $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');
  2891. if ($gender) {
  2892. $query->where('gender', $gender);
  2893. }
  2894. if ($timbre_name) {
  2895. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  2896. }
  2897. if ($category_id) {
  2898. $query->where(function ($query) use ($category_id) {
  2899. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  2900. });
  2901. }
  2902. if ($age_stage) {
  2903. $query->where('age_stage', $age_stage);
  2904. }
  2905. $list = $query->get()->map(function ($value) {
  2906. $value = (array)$value;
  2907. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  2908. return $value;
  2909. })->toArray();
  2910. return $list;
  2911. }
  2912. // 生成火山临时token
  2913. public function setStsToken() {
  2914. // ************* 配置参数 *************
  2915. $method = 'GET';
  2916. $service = 'sts';
  2917. $host = 'open.volcengineapi.com';
  2918. $region = env('VOLC_REGION');
  2919. $endpoint = 'https://open.volcengineapi.com';
  2920. // $endpoint = 'https://tos-cn-beijing.volces.com';
  2921. $access_key = env('VOLC_AK');
  2922. $secret_key = env('VOLC_SK');
  2923. // 获取缓存中的token,如果没有则请求接口
  2924. $token = Redis::get('volc_sts_token');
  2925. if (!$token) {
  2926. // 查询参数
  2927. $query_parameters = [
  2928. 'Action' => 'AssumeRole',
  2929. 'RoleSessionName' => 'user@zw',
  2930. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  2931. 'Version' => '2018-01-01'
  2932. ];
  2933. // 生成URL编码的查询字符串
  2934. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  2935. // 获取签名头信息
  2936. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  2937. // 构建完整URL
  2938. $request_url = $endpoint . '?' . $request_parameters;
  2939. $client = new Client(['verify' => false]);
  2940. $response = $client->get($request_url, ['headers' => $headers]);
  2941. $response_arr = json_decode($response->getBody()->getContents(), true);
  2942. $result = [
  2943. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  2944. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  2945. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  2946. 'Region' => env('VOLC_REGION'),
  2947. 'Endpoint' => env('VOLC_END_POINT'),
  2948. 'Bucket' => env('VOLC_BUCKET'),
  2949. ];
  2950. // 缓存token
  2951. Redis::setex('volc_sts_token', 3000, json_encode($result));
  2952. return $result;
  2953. } else {
  2954. return json_decode($token, true);
  2955. }
  2956. // $response = $response['Response'];
  2957. // $access_key = $response['Credentials']['AccessKeyId'];
  2958. // $secret_key = $response['Credentials']['AccessKeySecret'];
  2959. // $security_token = $response['Credentials']['SecurityToken'];
  2960. // $expiration = $response['Credentials']['Expiration'];
  2961. // dd($response_arr);
  2962. }
  2963. public function emotionGroups($data) {
  2964. $id = getProp($data, 'group_id');
  2965. $group_name = getProp($data, 'group_name');
  2966. $voice_type = getProp($data, 'voice_type');
  2967. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  2968. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  2969. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  2970. if ($group_name) {
  2971. $query->where('group_name', 'like', "%{$group_name}%");
  2972. }
  2973. if ($id) {
  2974. $query->where('id', $id);
  2975. }
  2976. if ($voice_type) {
  2977. $query->where('voice_type', $voice_type);
  2978. }
  2979. return $query->orderBy('id')->get()->map(function ($value) {
  2980. return (array)$value;
  2981. })->toArray();
  2982. }
  2983. private function sign($key, $msg) {
  2984. return hash_hmac('sha256', $msg, $key, true);
  2985. }
  2986. // 生成签名密钥
  2987. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  2988. $kDate = $this->sign($key, $dateStamp);
  2989. $kRegion = $this->sign($kDate, $regionName);
  2990. $kService = $this->sign($kRegion, $serviceName);
  2991. $kSigning = $this->sign($kService, 'request');
  2992. return $kSigning;
  2993. }
  2994. // 获取签名头信息
  2995. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  2996. $contenttype = 'application/x-www-form-urlencoded';
  2997. $accept = 'application/json';
  2998. // 获取当前UTC时间
  2999. $t = new DateTime('now', new DateTimeZone('UTC'));
  3000. $xdate = $t->format('Ymd\THis\Z');
  3001. $datestamp = $t->format('Ymd');
  3002. // 1. 拼接规范请求串
  3003. $canonical_uri = '/';
  3004. $canonical_querystring = $request_parameters;
  3005. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  3006. $signed_headers = 'content-type;host;x-date';
  3007. // 空请求体的SHA256哈希
  3008. $payload_hash = hash('sha256', '');
  3009. $canonical_request = implode("\n", [
  3010. $method,
  3011. $canonical_uri,
  3012. $canonical_querystring,
  3013. $canonical_headers,
  3014. $signed_headers,
  3015. $payload_hash
  3016. ]);
  3017. // 2. 拼接待签名字符串
  3018. $algorithm = 'HMAC-SHA256';
  3019. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  3020. $hashed_canonical_request = hash('sha256', $canonical_request);
  3021. $string_to_sign = implode("\n", [
  3022. $algorithm,
  3023. $xdate,
  3024. $credential_scope,
  3025. $hashed_canonical_request
  3026. ]);
  3027. // 3. 计算签名
  3028. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  3029. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  3030. // 4. 添加签名到请求头
  3031. $authorization_header = sprintf(
  3032. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  3033. $algorithm,
  3034. $access_key,
  3035. $credential_scope,
  3036. $signed_headers,
  3037. $signature
  3038. );
  3039. return [
  3040. 'Accept' => $accept,
  3041. 'Content-Type' => $contenttype,
  3042. 'X-Date' => $xdate,
  3043. 'Authorization' => $authorization_header
  3044. ];
  3045. }
  3046. // 文字合成语音(火山引擎)
  3047. public function tts($data) {
  3048. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  3049. $headers = [
  3050. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  3051. 'Content-Type' => 'application/json; charset=UTF-8'
  3052. ];
  3053. $post_data = [
  3054. 'app' => [
  3055. 'appid' => env('VOLC_APPID'),
  3056. 'token' => env('VOLC_TOKEN'),
  3057. 'cluster' => 'volcano_tts'
  3058. ],
  3059. 'user' => [
  3060. 'uid' => 'mp_audio'
  3061. ],
  3062. // 'audio' => [
  3063. // 'voice_type' =>
  3064. // ],
  3065. ];
  3066. }
  3067. public function scriptList($data) {
  3068. $uid = Site::getUid();
  3069. $script_id = getProp($data, 'script_id');
  3070. $script_name = getProp($data, 'script_name');
  3071. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  3072. if ($script_id) {
  3073. $query->where('id', $script_id);
  3074. }
  3075. if ($script_name) {
  3076. $query->where('script_name', 'like', "%{$script_name}%");
  3077. }
  3078. return $query->orderBy('created_at', 'desc')->paginate(12);
  3079. }
  3080. public function scripts($data) {
  3081. $uid = Site::getUid();
  3082. $script_id = getProp($data, 'script_id');
  3083. $script_name = getProp($data, 'script_name');
  3084. $is_products = getProp($data, 'is_products');
  3085. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  3086. if ($script_id) {
  3087. $query->where('id', $script_id);
  3088. }
  3089. if ($is_products !== '') {
  3090. $query->where('is_products', $is_products);
  3091. }
  3092. if ($script_name) {
  3093. $query->where('script_name', 'like', "%{$script_name}%");
  3094. }
  3095. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  3096. return (array)$value;
  3097. })->toArray();
  3098. }
  3099. public function scriptInfo($data) {
  3100. $uid = Site::getUid();
  3101. $script_id = getProp($data, 'script_id');
  3102. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  3103. // ->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();
  3104. ->selectRaw('id as script_id, script_name')->first();
  3105. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3106. $script = (array)$script;
  3107. // 获取分集组信息
  3108. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  3109. ->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')
  3110. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  3111. $value = (array)$value;
  3112. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  3113. return (array)$value;
  3114. })->toArray();
  3115. $script['group'] = $groups;
  3116. return $script;
  3117. }
  3118. public function createScript($data) {
  3119. $script_name = getProp($data, 'script_name');
  3120. $uid = Site::getUid(); // 获取当前用户ID
  3121. $cpid = Site::getCpid(); // 获取当前公司组ID
  3122. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  3123. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  3124. $script_name .= '_'.date('YmdHis');
  3125. }
  3126. return DB::table('mp_scripts')->insertGetId([
  3127. 'script_name' => $script_name,
  3128. 'user_id' => $uid,
  3129. 'cpid' => $cpid,
  3130. 'created_at' => date('Y-m-d H:i:s'),
  3131. 'updated_at' => date('Y-m-d H:i:s')
  3132. ]);
  3133. }
  3134. public function editScript($data) {
  3135. $script_id = getProp($data, 'script_id');
  3136. $script_name = getProp($data, 'script_name');
  3137. $uid = Site::getUid(); // 获取当前用户ID
  3138. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  3139. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  3140. if ($id && (int)$id !== (int)$script_id) {
  3141. $script_name .= '_'.date('YmdHis');
  3142. }
  3143. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3144. 'script_name' => $script_name,
  3145. 'updated_at' => date('Y-m-d H:i:s')
  3146. ]);
  3147. }
  3148. public function delScript($data) {
  3149. $script_id = getProp($data, 'script_id');
  3150. $uid = Site::getUid(); // 获取当前用户ID
  3151. if (!$script_id) Utils::throwError('20003:请选择剧本');
  3152. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3153. 'is_deleted' => 1,
  3154. 'updated_at' => date('Y-m-d H:i:s')
  3155. ]);
  3156. }
  3157. public function createEpisode($data) {
  3158. $script_id = getProp($data, 'script_id');
  3159. $group_name = getProp($data, 'group_name');
  3160. $remark = getProp($data, 'remark');
  3161. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  3162. $uid = Site::getUid(); // 获取当前用户ID
  3163. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  3164. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  3165. $group_name .= '_'.date('YmdHis');
  3166. }
  3167. return DB::table('mp_script_episode_group')->insertGetId([
  3168. 'script_id' => $script_id,
  3169. 'group_name' => $group_name,
  3170. 'user_id' => $uid,
  3171. 'remark' => $remark,
  3172. 'created_at' => date('Y-m-d H:i:s'),
  3173. 'updated_at' => date('Y-m-d H:i:s')
  3174. ]);
  3175. }
  3176. public function editEpisode($data) {
  3177. $group_id = getProp($data, 'group_id');
  3178. $start_episode_number = getProp($data, 'start_episode_number');
  3179. $end_episode_number = getProp($data, 'end_episode_number');
  3180. $group_name = getProp($data, 'group_name');
  3181. $uid = Site::getUid(); // 获取当前用户ID
  3182. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  3183. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  3184. if ($id && (int)$id !== (int)$group_id) {
  3185. $group_name .= '_'.date('YmdHis');
  3186. }
  3187. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3188. 'group_name' => $group_name,
  3189. 'start_episode_number' => $start_episode_number,
  3190. 'end_episode_number' => $end_episode_number,
  3191. 'updated_at' => date('Y-m-d H:i:s')
  3192. ]);
  3193. }
  3194. public function delEpisode($data) {
  3195. $group_id = getProp($data, 'group_id');
  3196. $uid = Site::getUid(); // 获取当前用户ID
  3197. if (!$group_id) Utils::throwError('20003:请选择分集');
  3198. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3199. 'is_deleted' => 1,
  3200. 'updated_at' => date('Y-m-d H:i:s')
  3201. ]);
  3202. }
  3203. /**
  3204. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3205. *
  3206. * @param array $data 包含以下参数:
  3207. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3208. * - question: 用户问题(可选)
  3209. * - model: 使用的模型(r1 或 v3,默认 v3)
  3210. * @return \Generator 返回生成器,用于流式输出
  3211. */
  3212. public function generateEpisodes($data) {
  3213. $script_id = getProp($data, 'script_id');
  3214. $group_id = getProp($data, 'group_id');
  3215. // $file = getProp($data, 'file');
  3216. $file = '';
  3217. $content = getProp($data, 'content', '');
  3218. // $bid = getProp($data, 'bid', 0);
  3219. $bid = 0;
  3220. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3221. if (!$group) {
  3222. Utils::throwError('20003:剧本分集不存在');
  3223. }
  3224. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  3225. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  3226. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  3227. $prompt = getProp($data, 'prompt');
  3228. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  3229. $model = getProp($data, 'model');
  3230. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3231. Utils::throwError('20003:该模型不存在!');
  3232. }
  3233. // 检查是否存在重叠的剧集序号范围
  3234. $exists_groups = DB::table('mp_script_episode_group')
  3235. ->where('script_id', $script_id)
  3236. ->where('id', '<>', $group_id) // 排除当前组
  3237. ->where('is_deleted', 0)
  3238. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3239. // 检查新范围是否与现有范围重叠
  3240. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3241. // 新范围的开始在现有范围内
  3242. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3243. ->where('end_episode_number', '>=', $start_episode_sequence);
  3244. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3245. // 新范围的结束在现有范围内
  3246. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3247. ->where('end_episode_number', '>=', $end_episode_sequence);
  3248. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3249. // 新范围完全包含现有范围
  3250. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3251. ->where('end_episode_number', '<=', $end_episode_sequence);
  3252. });
  3253. })
  3254. ->select('start_episode_number', 'end_episode_number')
  3255. ->get();
  3256. if ($exists_groups->isNotEmpty()) {
  3257. $conflict_ranges = [];
  3258. foreach ($exists_groups as $group) {
  3259. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3260. }
  3261. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3262. }
  3263. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3264. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3265. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3266. if ($model === 'deepseek-chat') {
  3267. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3268. $model = 'deepseek-v4-flash';
  3269. $thinkingMode = 'disabled';
  3270. } elseif ($model === 'deepseek-reasoner') {
  3271. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3272. $model = 'deepseek-v4-flash';
  3273. $thinkingMode = 'enabled';
  3274. }
  3275. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3276. if (!$script) {
  3277. Utils::throwError('20003:剧本不存在');
  3278. }
  3279. $content = getProp($group, 'content');
  3280. if (!$file && !$content && !$bid) {
  3281. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3282. }
  3283. // 提取文件内容
  3284. if ($file) {
  3285. $content = $this->extractFileContent($file);
  3286. if (!$content) {
  3287. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3288. }
  3289. } elseif ($bid) {
  3290. $content = $this->getContentByBid($bid);
  3291. if (!$content) {
  3292. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3293. }
  3294. } elseif ($content) {
  3295. $content = filterContent($content);
  3296. } elseif ($prompt) {
  3297. $content = filterContent($prompt);
  3298. } else {
  3299. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3300. }
  3301. // 构建消息
  3302. $messages = [
  3303. $this->sys_message,
  3304. [
  3305. 'role' => 'user',
  3306. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3307. ]
  3308. ];
  3309. $post_data = [
  3310. 'model' => $model,
  3311. 'messages' => $messages,
  3312. // 'max_tokens' => 8192,
  3313. 'temperature' => 0.7,
  3314. 'frequency_penalty' => 0,
  3315. 'presence_penalty' => 0,
  3316. 'thinking' => ['type' => $thinkingMode],
  3317. 'response_format' => ['type' => 'text'],
  3318. 'stream' => true
  3319. ];
  3320. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3321. // 根据模型类型选择调用方法
  3322. $fullContent = '';
  3323. $fullReasoningContent = '';
  3324. $usage = [];
  3325. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3326. // DeepSeek 官方模型使用 DeepSeek API
  3327. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3328. } else if (in_array($model, $this->gpt_text_models)) {
  3329. // GPT-5.4 模型使用 TokenRouter API
  3330. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3331. } else if (in_array($model, $this->gemini_text_models)) {
  3332. // Gemini 模型使用 Gemini API
  3333. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3334. } else {
  3335. // 其他模型使用火山引擎API
  3336. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3337. }
  3338. // 处理流式输出
  3339. foreach ($streamGenerator as $chunk) {
  3340. if (isset($chunk['type'])) {
  3341. if ($chunk['type'] === 'done') {
  3342. // 最终结果
  3343. $fullContent = $chunk['full_content'];
  3344. $fullReasoningContent = $chunk['full_reasoning'];
  3345. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3346. } else {
  3347. // 逐块yield数据
  3348. yield $chunk;
  3349. }
  3350. }
  3351. }
  3352. dLog('deepseek')->info('完整内容: '.$fullContent);
  3353. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3354. // 处理完整内容并返回最终结果
  3355. $script_arr = [];
  3356. if ($fullContent) {
  3357. $script_arr = extractScriptContent($fullContent);
  3358. }
  3359. logDB('deepseek', 'info', '解析内容', $script_arr);
  3360. if (!$script_arr['episodes']) {
  3361. Utils::throwError('20003:未生成剧本相关信息');
  3362. // yield [
  3363. // 'type' => 'done',
  3364. // 'script' => $script_arr,
  3365. // 'msg' => '未生成剧本相关信息',
  3366. // 'answer' => $fullContent,
  3367. // 'reasoning' => $fullReasoningContent,
  3368. // 'usage' => $usage
  3369. // ];
  3370. // return ;
  3371. }
  3372. try {
  3373. DB::beginTransaction();
  3374. // // 返回前保存剧本内容
  3375. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3376. // 'content' => $content,
  3377. // 'updated_at' => date('Y-m-d H:i:s')
  3378. // ]);
  3379. // if (!$boolen) {
  3380. // Utils::throwError('20003:保存剧本内容失败');
  3381. // }
  3382. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3383. // 'start_episode_number' => $start_episode_sequence,
  3384. // 'end_episode_number' => $end_episode_sequence,
  3385. // 'updated_at' => date('Y-m-d H:i:s')
  3386. // ]);
  3387. // if (!$boolen1) {
  3388. // Utils::throwError('20003:保存分集失败');
  3389. // }
  3390. $episode_content = '';
  3391. $episodes = [];
  3392. foreach ($script_arr['episodes'] as $item) {
  3393. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  3394. // $episodes[] = [
  3395. // 'script_id' => $script_id,
  3396. // 'episode_number' => $item['episode_number'],
  3397. // 'episode_name' => $item['episode_name'],
  3398. // 'episode_content' => $item['episode_content'],
  3399. // 'created_at' => date('Y-m-d H:i:s'),
  3400. // 'updated_at' => date('Y-m-d H:i:s'),
  3401. // ];
  3402. }
  3403. if ($episode_content) {
  3404. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3405. 'episode_content' => $episode_content,
  3406. 'updated_at' => date('Y-m-d H:i:s')
  3407. ]);
  3408. if (!$boolen2) {
  3409. Utils::throwError('20003:保存分集内容失败');
  3410. }
  3411. }else {
  3412. Utils::throwError('20003:分集剧本解析失败');
  3413. }
  3414. }catch (\Exception $e) {
  3415. DB::rollBack();
  3416. Utils::throwError('20003:'.$e->getMessage());
  3417. }
  3418. DB::commit();
  3419. yield [
  3420. 'type' => 'done',
  3421. 'script' => $script_arr,
  3422. 'episode_content' => $episode_content,
  3423. 'answer' => $fullContent,
  3424. 'reasoning' => $fullReasoningContent,
  3425. 'usage' => $usage
  3426. ];
  3427. }
  3428. public function chatWithFileStream($data) {
  3429. $script_id = getProp($data, 'script_id');
  3430. $group_id = getProp($data, 'group_id');
  3431. $file = getProp($data, 'file');
  3432. $content = getProp($data, 'content', '');
  3433. $bid = getProp($data, 'bid', 0);
  3434. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3435. $total_episode_num = getProp($data, 'total_episode_num', 30);
  3436. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  3437. $prompt = getProp($data, 'prompt');
  3438. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  3439. if (!empty($prompt)) {
  3440. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  3441. }
  3442. $question = getProp($data, 'question', $baseQuestion);
  3443. $model = getProp($data, 'model');
  3444. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3445. Utils::throwError('20003:该模型不存在!');
  3446. }
  3447. // 检查是否存在重叠的剧集序号范围
  3448. $exists_groups = DB::table('mp_script_episode_group')
  3449. ->where('script_id', $script_id)
  3450. ->where('id', '<>', $group_id)
  3451. ->where('is_deleted', 0)
  3452. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3453. // 检查新范围是否与现有范围重叠
  3454. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3455. // 新范围的开始在现有范围内
  3456. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3457. ->where('end_episode_number', '>=', $start_episode_sequence);
  3458. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3459. // 新范围的结束在现有范围内
  3460. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3461. ->where('end_episode_number', '>=', $end_episode_sequence);
  3462. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3463. // 新范围完全包含现有范围
  3464. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3465. ->where('end_episode_number', '<=', $end_episode_sequence);
  3466. });
  3467. })
  3468. ->select('start_episode_number', 'end_episode_number')
  3469. ->get();
  3470. if ($exists_groups->isNotEmpty()) {
  3471. $conflict_ranges = [];
  3472. foreach ($exists_groups as $group) {
  3473. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3474. }
  3475. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3476. }
  3477. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3478. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3479. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3480. if ($model === 'deepseek-chat') {
  3481. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3482. $model = 'deepseek-v4-flash';
  3483. $thinkingMode = 'disabled';
  3484. } elseif ($model === 'deepseek-reasoner') {
  3485. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3486. $model = 'deepseek-v4-flash';
  3487. $thinkingMode = 'enabled';
  3488. }
  3489. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3490. if (!$script) {
  3491. Utils::throwError('20003:剧本不存在');
  3492. }
  3493. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3494. if (!$group) {
  3495. Utils::throwError('20003:剧本分集不存在');
  3496. }
  3497. if (!$file && !$content && !$bid) {
  3498. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3499. }
  3500. // 提取文件内容
  3501. if ($file) {
  3502. $content = $this->extractFileContent($file);
  3503. if (!$content) {
  3504. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3505. }
  3506. } elseif ($bid) {
  3507. $content = $this->getContentByBid($bid);
  3508. if (!$content) {
  3509. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3510. }
  3511. } elseif ($content) {
  3512. $content = filterContent($content);
  3513. } elseif ($prompt) {
  3514. $content = filterContent($prompt);
  3515. } else {
  3516. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3517. }
  3518. // 构建消息
  3519. $messages = [
  3520. [
  3521. 'role' => 'system',
  3522. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3523. 强制要求:\n
  3524. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3525. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  3526. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  3527. 普通要求:\n
  3528. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  3529. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  3530. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  3531. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  3532. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  3533. 示例如下:\n
  3534. ###剧本名:西昆仑
  3535. ###故事梗概
  3536. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3537. ###剧本亮点
  3538. 亮点1:绝境奇药,生死一线
  3539. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3540. 亮点2:结拜兄妹,化解尴尬
  3541. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3542. 亮点3:纤发夺命,情愫暗涌
  3543. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3544. ###人物关系
  3545. 阿雪与梁萧之间存在兄妹之情。
  3546. ###核心矛盾
  3547. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3548. ###主体列表
  3549. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  3550. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  3551. 阴阳球:天地异宝,能化生精气,救人于危难。
  3552. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  3553. ###美术风格
  3554. 基础画风风格词:厚涂古风
  3555. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3556. ###场景列表
  3557. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  3558. [
  3559. 'role' => 'user',
  3560. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3561. ]
  3562. ];
  3563. $post_data = [
  3564. 'model' => $model,
  3565. 'messages' => $messages,
  3566. // 'max_tokens' => 8192,
  3567. 'temperature' => 0.7,
  3568. 'frequency_penalty' => 0,
  3569. 'presence_penalty' => 0,
  3570. 'thinking' => ['type' => $thinkingMode],
  3571. 'response_format' => ['type' => 'text'],
  3572. 'stream' => true
  3573. ];
  3574. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3575. // 根据模型类型选择调用方法
  3576. $fullContent = '';
  3577. $fullReasoningContent = '';
  3578. $usage = [];
  3579. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3580. // DeepSeek 官方模型使用 DeepSeek API
  3581. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3582. } else if (in_array($model, $this->gpt_text_models)) {
  3583. // GPT-5.4 模型使用 TokenRouter API
  3584. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3585. } else if (in_array($model, $this->gemini_text_models)) {
  3586. // Gemini 模型使用 Gemini API
  3587. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3588. } else {
  3589. // 其他模型使用火山引擎API
  3590. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3591. }
  3592. // 处理流式输出
  3593. foreach ($streamGenerator as $chunk) {
  3594. if (isset($chunk['type'])) {
  3595. if ($chunk['type'] === 'done') {
  3596. // 最终结果
  3597. $fullContent = $chunk['full_content'];
  3598. $fullReasoningContent = $chunk['full_reasoning'];
  3599. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3600. } else {
  3601. // 逐块yield数据
  3602. yield $chunk;
  3603. }
  3604. }
  3605. }
  3606. dLog('deepseek')->info('完整内容: '.$fullContent);
  3607. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3608. // 处理完整内容并返回最终结果
  3609. $script_arr = [];
  3610. if ($fullContent) {
  3611. $script_arr = extractScriptContent($fullContent);
  3612. }
  3613. logDB('deepseek', 'info', '解析内容', $script_arr);
  3614. if (!$script_arr['roles']) {
  3615. Utils::throwError('20003:未生成剧本相关信息');
  3616. // yield [
  3617. // 'type' => 'done',
  3618. // 'script' => $script_arr,
  3619. // 'msg' => '未生成剧本相关信息',
  3620. // 'answer' => $fullContent,
  3621. // 'reasoning' => $fullReasoningContent,
  3622. // 'usage' => $usage
  3623. // ];
  3624. }
  3625. try {
  3626. DB::beginTransaction();
  3627. // // 返回前保存剧本内容
  3628. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3629. // 'content' => $content,
  3630. // 'status' => '解析完成',
  3631. // 'updated_at' => date('Y-m-d H:i:s')
  3632. // ]);
  3633. // if (!$boolen) {
  3634. // Utils::throwError('20003:保存剧本内容失败');
  3635. // }
  3636. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3637. 'start_episode_number' => $start_episode_sequence,
  3638. 'end_episode_number' => $end_episode_sequence,
  3639. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3640. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3641. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3642. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3643. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3644. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3645. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3646. 'status' => '解析完成',
  3647. 'content' => $content,
  3648. 'updated_at' => date('Y-m-d H:i:s')
  3649. ]);
  3650. if (!$boolen1) {
  3651. Utils::throwError('20003:保存分集失败');
  3652. }
  3653. // $episodes = [];
  3654. // foreach ($script_arr['episodes'] as $item) {
  3655. // $episodes[] = [
  3656. // 'script_id' => $script_id,
  3657. // 'episode_number' => $item['episode_number'],
  3658. // 'episode_name' => $item['episode_name'],
  3659. // 'episode_content' => $item['episode_content'],
  3660. // 'created_at' => date('Y-m-d H:i:s'),
  3661. // 'updated_at' => date('Y-m-d H:i:s'),
  3662. // ];
  3663. // }
  3664. // if ($episodes) {
  3665. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  3666. // if (!$boolen2) {
  3667. // Utils::throwError('20003:保存分集内容失败');
  3668. // }
  3669. // }else {
  3670. // Utils::throwError('20003:分集剧本解析失败');
  3671. // }
  3672. }catch (\Exception $e) {
  3673. DB::rollBack();
  3674. Utils::throwError('20003:'.$e->getMessage());
  3675. }
  3676. DB::commit();
  3677. yield [
  3678. 'type' => 'done',
  3679. 'script' => $script_arr,
  3680. 'answer' => $fullContent,
  3681. 'reasoning' => $fullReasoningContent,
  3682. 'usage' => $usage
  3683. ];
  3684. }
  3685. /**
  3686. * 上传文件识别文字内容并与 DeepSeek 进行对话
  3687. *
  3688. * @param array $data 包含以下参数:
  3689. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3690. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  3691. * - model: 使用的模型(r1 或 v3,默认 v3)
  3692. * @return array
  3693. */
  3694. public function chatWithFile($data) {
  3695. $script_id = getProp($data, 'script_id');
  3696. $file = getProp($data, 'file');
  3697. $content = getProp($data, 'content', '');
  3698. $bid = getProp($data, 'bid', 0);
  3699. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3700. $total_episode_num = getProp($data, 'total_episode_num', 30);
  3701. $prompt = getProp($data, 'prompt');
  3702. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  3703. if (!empty($prompt)) {
  3704. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  3705. }
  3706. $question = getProp($data, 'question', $baseQuestion);
  3707. // 处理文本模型
  3708. $model = getProp($data, 'model');
  3709. if (!$model) {
  3710. // 用户没有输入,使用默认值
  3711. $model = 'doubao-seed-2-0-mini-260215';
  3712. }
  3713. // 验证模型是否在可用模型表中
  3714. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3715. $model = 'doubao-seed-2-0-mini-260215';
  3716. }
  3717. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3718. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3719. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3720. if ($model === 'deepseek-chat') {
  3721. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3722. $model = 'deepseek-v4-flash';
  3723. $thinkingMode = 'disabled';
  3724. } elseif ($model === 'deepseek-reasoner') {
  3725. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3726. $model = 'deepseek-v4-flash';
  3727. $thinkingMode = 'enabled';
  3728. }
  3729. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3730. if (!$script) {
  3731. Utils::throwError('20003:剧本不存在');
  3732. }
  3733. if (!$file && !$content && !$bid) {
  3734. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3735. }
  3736. // 提取文件内容
  3737. if ($file) {
  3738. $content = $this->extractFileContent($file);
  3739. if (!$content) {
  3740. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3741. }
  3742. } elseif ($bid) {
  3743. $content = $this->getContentByBid($bid);
  3744. if (!$content) {
  3745. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3746. }
  3747. } elseif ($content) {
  3748. $content = filterContent($content);
  3749. } elseif ($prompt) {
  3750. $content = filterContent($prompt);
  3751. } else {
  3752. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3753. }
  3754. // 构建消息
  3755. $messages = [
  3756. $this->sys_message,
  3757. [
  3758. 'role' => 'user',
  3759. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3760. ]
  3761. ];
  3762. $post_data = [
  3763. 'model' => $model,
  3764. 'messages' => $messages,
  3765. // 'max_tokens' => 8192,
  3766. 'temperature' => 0.7,
  3767. 'frequency_penalty' => 0,
  3768. 'presence_penalty' => 0,
  3769. 'thinking' => ['type' => $thinkingMode],
  3770. 'response_format' => ['type' => 'text'],
  3771. 'stream' => false
  3772. ];
  3773. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3774. // 根据模型类型选择调用方法
  3775. $fullContent = '';
  3776. $usage = [];
  3777. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3778. // DeepSeek 官方模型使用 DeepSeek API
  3779. $chatResult = $this->chatOnly($post_data);
  3780. } else if (in_array($model, $this->gpt_text_models)) {
  3781. // GPT-5.4 模型使用 TokenRouter API
  3782. $chatResult = $this->gpt54ChatOnly($post_data);
  3783. } else {
  3784. // 其他模型使用火山引擎API
  3785. $chatResult = $this->volcEngineChatCompletion($post_data);
  3786. }
  3787. if (is_array($chatResult)) {
  3788. $fullContent = $chatResult['fullContent'];
  3789. $usage = $chatResult['usage'];
  3790. }
  3791. $script_arr = [];
  3792. // 处理结果
  3793. if ($fullContent) {
  3794. $script_arr = extractScriptContent($fullContent);
  3795. }
  3796. // 返回前保存剧本内容
  3797. DB::table('mp_scripts')->where('id', $script_id)->update([
  3798. 'content' => $content,
  3799. 'updated_at' => date('Y-m-d H:i:s')
  3800. ]);
  3801. return [
  3802. 'script' => $script_arr,
  3803. 'answer' => $fullContent,
  3804. 'usage' => $usage
  3805. ];
  3806. }
  3807. public function getEpisodeContent($data) {
  3808. $group_id = getProp($data, 'group_id');
  3809. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  3810. }
  3811. public function saveEpisodeContent($data) {
  3812. $script_id = getProp($data, 'script_id');
  3813. $group_id = getProp($data, 'group_id');
  3814. $start_episode_sequence = getProp($data, 'start_episode_number');
  3815. $end_episode_sequence = getProp($data, 'end_episode_number');
  3816. // 检查是否存在重叠的剧集序号范围
  3817. $exists_groups = DB::table('mp_script_episode_group')
  3818. ->where('script_id', $script_id)
  3819. ->where('id', '<>', $group_id) // 排除当前组
  3820. ->where('is_deleted', 0)
  3821. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3822. // 检查新范围是否与现有范围重叠
  3823. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3824. // 新范围的开始在现有范围内
  3825. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3826. ->where('end_episode_number', '>=', $start_episode_sequence);
  3827. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3828. // 新范围的结束在现有范围内
  3829. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3830. ->where('end_episode_number', '>=', $end_episode_sequence);
  3831. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3832. // 新范围完全包含现有范围
  3833. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3834. ->where('end_episode_number', '<=', $end_episode_sequence);
  3835. });
  3836. })
  3837. ->select('start_episode_number', 'end_episode_number')
  3838. ->get();
  3839. if ($exists_groups->isNotEmpty()) {
  3840. $conflict_ranges = [];
  3841. foreach ($exists_groups as $group) {
  3842. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3843. }
  3844. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3845. }
  3846. $episode_content = getProp($data, 'episode_content');
  3847. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  3848. 'content' => $episode_content,
  3849. 'start_episode_number' => $start_episode_sequence,
  3850. 'end_episode_number' => $end_episode_sequence,
  3851. 'updated_at' => date('Y-m-d H:i:s')
  3852. ]);
  3853. $script_arr =getProp($data, 'script', []);
  3854. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  3855. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3856. $script_id = getProp($data, 'script_id');
  3857. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  3858. try {
  3859. DB::beginTransaction();
  3860. $update_data = [
  3861. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3862. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3863. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3864. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3865. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3866. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3867. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3868. 'status' => 3,
  3869. 'start_episode_sequence' => $start_episode_sequence,
  3870. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  3871. 'episode_num' => count($script_arr['episodes']),
  3872. 'updated_at' => date('Y-m-d H:i:s')
  3873. ];
  3874. // 保存剧本内容
  3875. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  3876. if (!$boolen) {
  3877. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  3878. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  3879. Utils::throwError('20003:剧本内容保存失败');
  3880. }
  3881. // 保存分集内容
  3882. // 删除历史分集内容
  3883. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  3884. $episodes = [];
  3885. $sequence = 1;
  3886. foreach ($script_arr['episodes'] as $episode) {
  3887. $segment_number = 1;
  3888. foreach($episode['segments'] as $segment) {
  3889. $episodes[] = [
  3890. 'script_id' => $script_id,
  3891. 'episode_number' => $episode['episode_number'],
  3892. 'title' => $episode['title'],
  3893. // 'content' => $episode['content'],
  3894. 'content' => '',
  3895. 'segment_number' => $segment_number,
  3896. 'segment_content' => $segment['segment_content'],
  3897. 'sequence' => $sequence,
  3898. 'created_at' => date('Y-m-d H:i:s'),
  3899. 'updated_at' => date('Y-m-d H:i:s')
  3900. ];
  3901. $sequence++;
  3902. $segment_number++;
  3903. }
  3904. }
  3905. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  3906. if (!$boolen2) {
  3907. dLog('deepseek')->info('分集内容保存失败', $episodes);
  3908. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  3909. Utils::throwError('20003:分集内容保存失败');
  3910. }
  3911. } catch (\Exception $e) {
  3912. DB::rollBack();
  3913. Utils::throwError('20003:'.$e->getMessage());
  3914. }
  3915. DB::commit();
  3916. return true;
  3917. }
  3918. public function getBookContent($data) {
  3919. $bid = getProp($data, 'bid');
  3920. $start_sequence = getProp($data, 'start_sequence');
  3921. $end_sequence = getProp($data, 'end_sequence');
  3922. $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])
  3923. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  3924. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  3925. return $return_content;
  3926. }
  3927. public function exportScript($data) {
  3928. $filename = getProp($data, 'filename');
  3929. $script_id = getProp($data, 'script_id');
  3930. $group_id = getProp($data, 'group_id');
  3931. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  3932. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  3933. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3934. $script = (array)$script;
  3935. // 获取分集组信息
  3936. if ($group_id) {
  3937. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  3938. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  3939. ->get()->map(function($value) {
  3940. return (array)$value;
  3941. })->toArray();
  3942. }else {
  3943. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  3944. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  3945. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  3946. return (array)$value;
  3947. })->toArray();
  3948. }
  3949. if (!$groups) Utils::throwError('20003:分集不存在');
  3950. $script['group'] = $groups;
  3951. $export_type = getProp($data, 'export_type', 'txt');
  3952. // 生成文件名
  3953. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  3954. // 根据导出类型生成不同格式的文件
  3955. switch ($export_type) {
  3956. case 'txt':
  3957. return $this->exportScriptAsTxt($script, $filename);
  3958. case 'pdf':
  3959. return $this->exportScriptAsPdf($script, $filename);
  3960. default:
  3961. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  3962. }
  3963. }
  3964. /**
  3965. * 导出剧本为TXT格式
  3966. */
  3967. private function exportScriptAsTxt($script, $filename) {
  3968. // 构建TXT内容
  3969. $content = $this->buildScriptContent($script);
  3970. // 设置响应头,直接下载
  3971. header('Content-Type: text/plain; charset=utf-8');
  3972. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  3973. header('Content-Length: ' . strlen($content));
  3974. // 输出内容并结束
  3975. echo $content;
  3976. exit();
  3977. }
  3978. /**
  3979. * 导出剧本为PDF格式
  3980. */
  3981. private function exportScriptAsPdf($script, $filename) {
  3982. // 使用HTML转PDF的方式来更好地支持中文
  3983. $htmlContent = $this->buildScriptHtmlForPdf($script);
  3984. // 创建PDF实例
  3985. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  3986. // 设置文档信息
  3987. $pdf->SetCreator('剧本导出系统');
  3988. $pdf->SetAuthor('系统');
  3989. $pdf->SetTitle($script['script_name']);
  3990. $pdf->SetSubject('剧本导出');
  3991. // 设置边距
  3992. $pdf->SetMargins(15, 15, 15);
  3993. $pdf->SetAutoPageBreak(TRUE, 15);
  3994. // 添加页面
  3995. $pdf->AddPage();
  3996. // 注册并使用 simsun.ttf 字体
  3997. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  3998. // 使用HTML内容生成PDF
  3999. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  4000. // 直接输出PDF文件供下载
  4001. header('Content-Type: application/pdf');
  4002. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  4003. // 直接输出PDF内容
  4004. $pdf->Output($filename . '.pdf', 'D');
  4005. exit();
  4006. }
  4007. /**
  4008. * 构建用于PDF的HTML内容
  4009. */
  4010. private function buildScriptHtmlForPdf($script) {
  4011. $html = '<style>
  4012. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  4013. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  4014. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  4015. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  4016. .info { margin-bottom: 8px; }
  4017. .group { margin-bottom: 30px; page-break-inside: avoid; }
  4018. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  4019. .segment { margin-bottom: 10px; margin-left: 20px; }
  4020. .episode-content { white-space: pre-wrap; }
  4021. </style>';
  4022. // 标题
  4023. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  4024. // 处理分组数据
  4025. if (!empty($script['group']) && is_array($script['group'])) {
  4026. $groups = (array)$script['group'];
  4027. foreach ($groups as $group) {
  4028. $html .= '<div class="group">';
  4029. // 分组标题
  4030. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  4031. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  4032. // 故事梗概
  4033. if (!empty($group['intro'])) {
  4034. $html .= '<h3>故事梗概</h3>';
  4035. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  4036. }
  4037. // 剧本亮点
  4038. if (!empty($group['highlights'])) {
  4039. $html .= '<h3>剧本亮点</h3>';
  4040. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  4041. }
  4042. // 人物关系
  4043. if (!empty($group['role_relationship'])) {
  4044. $html .= '<h3>人物关系</h3>';
  4045. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  4046. }
  4047. // 核心矛盾
  4048. if (!empty($group['core_contradiction'])) {
  4049. $html .= '<h3>核心矛盾</h3>';
  4050. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  4051. }
  4052. // 主体列表
  4053. if (!empty($group['roles']) && is_array($group['roles'])) {
  4054. $html .= '<h3>主体列表</h3>';
  4055. $html .= '<ul>';
  4056. foreach ($group['roles'] as $role) {
  4057. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  4058. }
  4059. $html .= '</ul>';
  4060. }
  4061. // 美术风格
  4062. if (!empty($group['art_style'])) {
  4063. $html .= '<h3>美术风格</h3>';
  4064. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  4065. }
  4066. // 场景列表
  4067. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4068. $html .= '<h3>场景列表</h3>';
  4069. $html .= '<ul>';
  4070. foreach ($group['scenes'] as $scene) {
  4071. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  4072. }
  4073. $html .= '</ul>';
  4074. }
  4075. // 分集剧本
  4076. if (!empty($group['episode_content'])) {
  4077. $html .= '<h3>分集剧本</h3>';
  4078. // 去除零宽字符和其他不可见字符
  4079. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  4080. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  4081. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  4082. }
  4083. $html .= '</div>';
  4084. }
  4085. }
  4086. return $html;
  4087. }
  4088. /**
  4089. * 构建PDF内容
  4090. */
  4091. private function buildPdfContent($pdf, $script) {
  4092. // 标题
  4093. $pdf->SetFont('dejavusans', 'B', 18);
  4094. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  4095. $pdf->Ln(5);
  4096. // 基本信息
  4097. $pdf->SetFont('dejavusans', '', 12);
  4098. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  4099. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  4100. $pdf->Ln(5);
  4101. // 剧本简介
  4102. if (!empty($script['intro'])) {
  4103. $pdf->SetFont('dejavusans', 'B', 14);
  4104. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  4105. $pdf->SetFont('dejavusans', '', 12);
  4106. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  4107. $pdf->Ln(3);
  4108. }
  4109. // 亮点
  4110. if (!empty($script['highlights'])) {
  4111. $pdf->SetFont('dejavusans', 'B', 14);
  4112. $pdf->Cell(0, 10, '亮点', 0, 1);
  4113. $pdf->SetFont('dejavusans', '', 12);
  4114. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  4115. $pdf->Ln(3);
  4116. }
  4117. // 核心矛盾
  4118. if (!empty($script['core_contradiction'])) {
  4119. $pdf->SetFont('dejavusans', 'B', 14);
  4120. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  4121. $pdf->SetFont('dejavusans', '', 12);
  4122. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  4123. $pdf->Ln(3);
  4124. }
  4125. // 艺术风格
  4126. if (!empty($script['art_style'])) {
  4127. $pdf->SetFont('dejavusans', 'B', 14);
  4128. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  4129. $pdf->SetFont('dejavusans', '', 12);
  4130. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  4131. $pdf->Ln(3);
  4132. }
  4133. // 备注
  4134. if (!empty($script['remark'])) {
  4135. $pdf->SetFont('dejavusans', 'B', 14);
  4136. $pdf->Cell(0, 10, '备注', 0, 1);
  4137. $pdf->SetFont('dejavusans', '', 12);
  4138. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  4139. $pdf->Ln(3);
  4140. }
  4141. // 角色列表
  4142. if (!empty($script['roles']) && is_array($script['roles'])) {
  4143. $pdf->SetFont('dejavusans', 'B', 14);
  4144. $pdf->Cell(0, 10, '角色列表', 0, 1);
  4145. $pdf->SetFont('dejavusans', '', 12);
  4146. foreach ($script['roles'] as $index => $role) {
  4147. if (is_array($role) || is_object($role)) {
  4148. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  4149. } else {
  4150. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  4151. }
  4152. }
  4153. $pdf->Ln(3);
  4154. }
  4155. // 角色关系
  4156. if (!empty($script['role_relationship'])) {
  4157. $pdf->SetFont('dejavusans', 'B', 14);
  4158. $pdf->Cell(0, 10, '角色关系', 0, 1);
  4159. $pdf->SetFont('dejavusans', '', 12);
  4160. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  4161. $pdf->Ln(3);
  4162. }
  4163. // 场景列表
  4164. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  4165. $pdf->SetFont('dejavusans', 'B', 14);
  4166. $pdf->Cell(0, 10, '场景列表', 0, 1);
  4167. $pdf->SetFont('dejavusans', '', 12);
  4168. foreach ($script['scenes'] as $index => $scene) {
  4169. if (is_array($scene) || is_object($scene)) {
  4170. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  4171. } else {
  4172. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  4173. }
  4174. }
  4175. $pdf->Ln(5);
  4176. }
  4177. // 分集内容
  4178. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  4179. $pdf->SetFont('dejavusans', 'B', 16);
  4180. $pdf->Cell(0, 12, '分集内容', 0, 1);
  4181. $pdf->Ln(3);
  4182. foreach ($script['episodes'] as $episode) {
  4183. // 检查是否需要新页面
  4184. if ($pdf->GetY() > 250) {
  4185. $pdf->AddPage();
  4186. }
  4187. $pdf->SetFont('dejavusans', 'B', 14);
  4188. $episodeTitle = '第' . $episode['episode_number'] . '集';
  4189. if (!empty($episode['title'])) {
  4190. $episodeTitle .= ':' . $episode['title'];
  4191. }
  4192. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  4193. // 处理分段内容
  4194. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  4195. $pdf->SetFont('dejavusans', '', 12);
  4196. foreach ($episode['segments'] as $segment) {
  4197. if (!empty($segment['segment_content'])) {
  4198. // 如果有分段编号,显示分段标题
  4199. if (!empty($segment['segment_number'])) {
  4200. $pdf->SetFont('dejavusans', 'B', 12);
  4201. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  4202. $pdf->SetFont('dejavusans', '', 12);
  4203. }
  4204. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  4205. $pdf->Ln(2);
  4206. }
  4207. }
  4208. }
  4209. $pdf->Ln(5);
  4210. }
  4211. }
  4212. }
  4213. /**
  4214. * 构建剧本文本内容
  4215. */
  4216. private function buildScriptContent($script) {
  4217. $content = '';
  4218. $groups = $script['group'];
  4219. $groups = (array)$groups;
  4220. foreach ($groups as $group) {
  4221. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  4222. // 剧本基本信息
  4223. if (!empty($group['intro'])) {
  4224. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  4225. }
  4226. if (!empty($group['highlights'])) {
  4227. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  4228. }
  4229. if (!empty($group['role_relationship'])) {
  4230. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  4231. }
  4232. if (!empty($group['core_contradiction'])) {
  4233. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  4234. }
  4235. if (!empty($group['roles']) && is_array($group['roles'])) {
  4236. $content .= "###主体列表\n";
  4237. foreach ($group['roles'] as $role) {
  4238. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  4239. }
  4240. $content .= "\n\n";
  4241. }
  4242. if (!empty($group['art_style'])) {
  4243. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  4244. }
  4245. // 场景信息
  4246. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4247. $content .= "###场景列表\n";
  4248. foreach ($group['scenes'] as $scene) {
  4249. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  4250. }
  4251. $content .= "\n\n";
  4252. }
  4253. // 分集内容
  4254. if (!empty($group['episode_content'])) {
  4255. $content .= "###分集剧本\n";
  4256. $content .= $group['episode_content'];
  4257. // foreach ($script['episodes'] as $episode) {
  4258. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  4259. // // if (!empty($episode['episode_name'])) {
  4260. // // $content .= ":" . $episode['episode_name'];
  4261. // // }
  4262. // // $content .= "\n";
  4263. // $content .= $episode['episode_content'] . "\n\n";
  4264. // }
  4265. }
  4266. }
  4267. return $content;
  4268. }
  4269. /**
  4270. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4271. *
  4272. * @param array $data 包含以下参数:
  4273. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4274. * - question: 用户问题(可选)
  4275. * - model: 使用的模型(r1 或 v3,默认 v3)
  4276. * @return \Generator 返回生成器,用于流式输出
  4277. */
  4278. public function addChat($data) {
  4279. $uid = Site::getUid();
  4280. $anime_id = getProp($data, 'anime_id');
  4281. if (!$anime_id) Utils::throwError('20003:请选择对话');
  4282. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4283. if (!$anime) Utils::throwError('20003:对话不存在');
  4284. $file = getProp($data, 'file');
  4285. $content = getProp($data, 'content', '');
  4286. $bid = getProp($data, 'bid', 0);
  4287. $script_id = getProp($data, 'script_id', 0);
  4288. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  4289. $prompt = getProp($data, 'prompt');
  4290. $user_anime_name = getProp($anime, 'anime_name');
  4291. // 处理文本模型
  4292. $model = getProp($data, 'model');
  4293. if (!$model) {
  4294. // 用户没有输入,从anime表获取
  4295. $model = getProp($anime, 'model');
  4296. if (!$model) {
  4297. // anime表也没有,使用默认值
  4298. $model = 'doubao-seed-2-0-mini-260215';
  4299. }
  4300. }
  4301. // 验证模型是否在可用模型表中
  4302. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4303. $model = 'doubao-seed-2-0-mini-260215';
  4304. }
  4305. $is_multi = getProp($anime, 'is_multi');
  4306. $is_single = (int)$is_multi !== 1;
  4307. // 积分余额预检(仅单剧集模式收费)
  4308. if ($is_single) {
  4309. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  4310. }
  4311. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4312. if ($prompt) {
  4313. $question .= "本次修改要求如下:\n{$prompt}";
  4314. }
  4315. // if (!$file && !$content && !$bid) {
  4316. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4317. // }
  4318. // 提取文件内容
  4319. if ($file) {
  4320. $content = $this->extractFileContent($file);
  4321. if (!$content) {
  4322. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4323. }
  4324. } elseif ($script_id) {
  4325. $content = $this->getContentByScriptId($script_id);
  4326. if (!$content) {
  4327. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4328. }
  4329. } elseif ($bid) {
  4330. $content = $this->getContentByBid($bid);
  4331. if (!$content) {
  4332. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4333. }
  4334. } elseif ($content) {
  4335. $content = filterContent($content);
  4336. } else {
  4337. $content = getProp($anime, 'content');
  4338. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4339. $need_generate_content = true;
  4340. }
  4341. }
  4342. // 美术风格
  4343. $input_art_style = getProp($data, 'art_style');
  4344. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4345. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4346. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4347. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4348. 中年女:邻居阿姨
  4349. 老年男:幽默大爷
  4350. 老年女:婆婆
  4351. 萌娃:奶气萌娃";
  4352. // 判断是否需要生成原文内容
  4353. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4354. // 如果需要生成原文内容,添加额外的要求
  4355. $content_generation_requirement = $need_generate_content
  4356. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4357. : "";
  4358. // 美术风格
  4359. if (!$mappedArtStyle) {
  4360. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4361. }else {
  4362. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4363. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4364. }else {
  4365. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4366. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4367. }
  4368. }
  4369. $systemPrompt = $is_single
  4370. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4371. 强制要求:
  4372. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4373. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4374. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4375. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4376. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4377. 普通要求:
  4378. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4379. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4380. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  4381. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4382. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4383. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4384. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4385. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4386. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4387. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4388. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4389. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4390. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4391. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4392. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4393. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4394. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4395. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4396. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4397. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4398. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4399. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4400. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4401. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4402. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4403. 5.{$mappedArtStyle_prompt}\n\n
  4404. 示例如下:\n
  4405. ###剧本名:西昆仑
  4406. ###故事梗概
  4407. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4408. ###剧本亮点
  4409. 亮点1:绝境奇药,生死一线
  4410. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4411. 亮点2:结拜兄妹,化解尴尬
  4412. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4413. 亮点3:纤发夺命,情愫暗涌
  4414. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4415. ###人物关系
  4416. 阿雪与梁萧之间存在兄妹之情。
  4417. ###核心矛盾
  4418. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4419. ###主体列表
  4420. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4421. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4422. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4423. 姿态:站立。}{{甜心小美}}
  4424. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4425. 全景,正面拍摄,青年女性,亚洲人。
  4426. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4427. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4428. 姿态:站立。}{{阳光青年}}
  4429. ###美术风格
  4430. 基础画风风格词:厚涂古风
  4431. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4432. ###场景列表
  4433. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4434. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4435. 无人物。}
  4436. ###分镜剧本
  4437. ##第1幕:徐家老旧厨房 白天 室内
  4438. 分镜1
  4439. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4440. 场景:徐家老旧厨房
  4441. 构图设计:全景,低角度仰视
  4442. 运镜调度:手持拍摄
  4443. 配音角色:旁白
  4444. 出镜角色:许芸-校服装、徐母
  4445. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4446. 画面类型:普通画面
  4447. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4448. 分镜2
  4449. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4450. 场景:徐家老旧厨房
  4451. 构图设计:近景,徐母面部特写
  4452. 运镜调度:固定镜头
  4453. 配音角色:徐母
  4454. 出镜角色:徐母
  4455. 台词内容:问我夜不归宿死哪儿去了。
  4456. 画面类型:对口型
  4457. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4458. ##第2幕:徐家简陋客厅 黄昏 室内
  4459. 分镜3
  4460. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4461. 场景:徐家简陋客厅
  4462. 构图设计:全景,景深虚化
  4463. 运镜调度:固定镜头
  4464. 配音角色:旁白
  4465. 出镜角色:无
  4466. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4467. 画面类型:普通画面
  4468. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4469. 分镜4
  4470. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4471. 场景:徐家简陋客厅
  4472. 构图设计:特写,火车票
  4473. 运镜调度:固定镜头
  4474. 配音角色:旁白
  4475. 出镜角色:无
  4476. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4477. 画面类型:普通画面
  4478. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4479. "
  4480. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4481. 强制要求:\n
  4482. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4483. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4484. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4485. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4486. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4487. 普通要求:\n
  4488. 1.剧本名(必须生成)必须与文档内容高度相关
  4489. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4490. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4491. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4492. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4493. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4494. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4495. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4496. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4497. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4498. 4.{$mappedArtStyle_prompt}\n\n
  4499. 示例如下:\n
  4500. ###剧本名:西昆仑
  4501. ###故事梗概
  4502. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4503. ###剧本亮点
  4504. 亮点1:绝境奇药,生死一线
  4505. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4506. 亮点2:结拜兄妹,化解尴尬
  4507. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4508. 亮点3:纤发夺命,情愫暗涌
  4509. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4510. ###人物关系
  4511. 阿雪与梁萧之间存在兄妹之情。
  4512. ###核心矛盾
  4513. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4514. ###主体列表
  4515. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4516. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4517. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4518. 姿态:站立。}{{甜心小美}}
  4519. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4520. 全景,正面拍摄,青年女性,亚洲人。
  4521. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4522. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4523. 姿态:站立。}{{阳光青年}}
  4524. ###美术风格
  4525. 基础画风风格词:厚涂古风
  4526. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4527. ###场景列表
  4528. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4529. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4530. 无人物。}";
  4531. // 构建消息
  4532. $messages = [
  4533. [
  4534. 'role' => 'system',
  4535. 'content' => $systemPrompt
  4536. ],
  4537. [
  4538. 'role' => 'user',
  4539. 'content' => "以下是文档内容:
  4540. {$content}
  4541. 用户问题:
  4542. {$question}"
  4543. ]
  4544. ];
  4545. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4546. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4547. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4548. if ($model === 'deepseek-chat') {
  4549. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4550. $model = 'deepseek-v4-flash';
  4551. $thinkingMode = 'disabled';
  4552. } elseif ($model === 'deepseek-reasoner') {
  4553. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4554. $model = 'deepseek-v4-flash';
  4555. $thinkingMode = 'enabled';
  4556. }
  4557. $post_data = [
  4558. 'model' => $model,
  4559. 'messages' => $messages,
  4560. // 'max_tokens' => 8192,
  4561. 'temperature' => 0.7,
  4562. 'frequency_penalty' => 0,
  4563. 'presence_penalty' => 0,
  4564. 'response_format' => ['type' => 'text'],
  4565. 'thinking' => ['type'=>$thinkingMode],
  4566. 'stream' => true // 启用流式输出
  4567. ];
  4568. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4569. // 根据模型类型选择调用方法
  4570. $fullContent = '';
  4571. $fullReasoningContent = '';
  4572. $usage = [];
  4573. try {
  4574. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4575. // DeepSeek 官方模型使用 DeepSeek API
  4576. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4577. } else if (in_array($model, $this->gpt_text_models)) {
  4578. // GPT-5.4 模型使用 TokenRouter API
  4579. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4580. } else if (in_array($model, $this->gemini_text_models)) {
  4581. // Gemini 模型使用 Gemini API
  4582. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4583. } else {
  4584. // 其他模型使用火山引擎API
  4585. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4586. }
  4587. // 验证返回值类型
  4588. if (!is_iterable($streamGenerator)) {
  4589. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4590. dLog('deepseek')->error('addChat流式生成器无效', [
  4591. 'generator_type' => $errorType,
  4592. 'model' => $model,
  4593. 'anime_id' => $anime_id
  4594. ]);
  4595. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  4596. 'type' => $errorType,
  4597. 'model' => $model
  4598. ]);
  4599. yield [
  4600. 'type' => 'error',
  4601. 'script' => [],
  4602. 'episode' => [],
  4603. 'answer' => '',
  4604. 'reasoning' => '',
  4605. 'usage' => [],
  4606. 'error' => '接口返回数据异常,请重新请求'
  4607. ];
  4608. return;
  4609. }
  4610. // 处理流式输出
  4611. foreach ($streamGenerator as $chunk) {
  4612. if (isset($chunk['type'])) {
  4613. if ($chunk['type'] === 'done') {
  4614. // 最终结果
  4615. $fullContent = $chunk['full_content'];
  4616. $fullReasoningContent = $chunk['full_reasoning'];
  4617. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4618. } else {
  4619. // 逐块yield数据
  4620. yield $chunk;
  4621. }
  4622. }
  4623. }
  4624. } catch (\Exception $e) {
  4625. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  4626. 'model' => $model,
  4627. 'anime_id' => $anime_id,
  4628. 'trace' => $e->getTraceAsString()
  4629. ]);
  4630. logDB('deepseek', 'error', 'addChat流式处理失败', [
  4631. 'error' => $e->getMessage(),
  4632. 'model' => $model
  4633. ]);
  4634. yield [
  4635. 'type' => 'error',
  4636. 'script' => [],
  4637. 'episode' => [],
  4638. 'answer' => '',
  4639. 'reasoning' => '',
  4640. 'usage' => [],
  4641. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4642. ];
  4643. return;
  4644. }
  4645. dLog('deepseek')->info('完整内容: '.$fullContent);
  4646. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4647. // 处理完整内容并返回最终结果
  4648. $script_arr = [];
  4649. if ($fullContent) {
  4650. $script_arr = handleScriptContent($fullContent);
  4651. dLog('deepseek')->info('解析内容', $script_arr);
  4652. logDB('deepseek', 'info', '解析内容', $script_arr);
  4653. }
  4654. if (empty($script_arr['roles'])) {
  4655. // 未生成剧本相关内容,保存对话记录并返回提示
  4656. dLog('deepseek')->info('未生成剧本相关的内容');
  4657. try {
  4658. DB::beginTransaction();
  4659. $now = date('Y-m-d H:i:s');
  4660. // 保存对话记录
  4661. $records = [
  4662. [
  4663. 'uid' => $uid,
  4664. 'anime_id' => $anime_id,
  4665. 'sequence' => 0,
  4666. 'role' => 'user',
  4667. 'content' => $prompt,
  4668. 'created_at' => $now,
  4669. 'updated_at' => $now
  4670. ],
  4671. [
  4672. 'uid' => $uid,
  4673. 'anime_id' => $anime_id,
  4674. 'sequence' => 0,
  4675. 'role' => 'assistant',
  4676. // 'content' => $fullContent,
  4677. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  4678. 'created_at' => $now,
  4679. 'updated_at' => $now
  4680. ]
  4681. ];
  4682. DB::table('mp_anime_records')->insert($records);
  4683. DB::commit();
  4684. } catch (\Exception $e) {
  4685. DB::rollBack();
  4686. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4687. }
  4688. yield [
  4689. 'type' => 'done',
  4690. 'script' => [],
  4691. 'episode' => [],
  4692. 'answer' => $fullContent,
  4693. 'reasoning' => $fullReasoningContent,
  4694. 'usage' => $usage,
  4695. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4696. ];
  4697. return;
  4698. }
  4699. // 如果需要生成原文内容,从script_arr中提取
  4700. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4701. $content = $script_arr['content'];
  4702. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  4703. if (!$content) {
  4704. yield [
  4705. 'type' => 'done',
  4706. 'script' => [],
  4707. 'episode' => [],
  4708. 'answer' => $fullContent,
  4709. 'reasoning' => $fullReasoningContent,
  4710. 'usage' => $usage,
  4711. 'error' => '未生成剧本内容,请调整提示词再试'
  4712. ];
  4713. return;
  4714. }
  4715. }
  4716. // 替换美术风格
  4717. if ($mappedArtStyle !== '') {
  4718. $script_arr['art_style'] = $mappedArtStyle;
  4719. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4720. }
  4721. // 新建动漫
  4722. if ($user_anime_name == '新剧本策划') {
  4723. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  4724. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  4725. // if (!$anime_name) {
  4726. // // 未识别到剧本名,保存对话记录并返回提示
  4727. // dLog('deepseek')->info('未能识别到剧本名称');
  4728. // try {
  4729. // DB::beginTransaction();
  4730. // $now = date('Y-m-d H:i:s');
  4731. // // 保存对话记录
  4732. // $records = [
  4733. // [
  4734. // 'uid' => $uid,
  4735. // 'anime_id' => $anime_id,
  4736. // 'sequence' => 0,
  4737. // 'role' => 'user',
  4738. // 'content' => $prompt,
  4739. // 'created_at' => $now,
  4740. // 'updated_at' => $now
  4741. // ],
  4742. // [
  4743. // 'uid' => $uid,
  4744. // 'anime_id' => $anime_id,
  4745. // 'sequence' => 0,
  4746. // 'role' => 'assistant',
  4747. // 'content' => '未能生成剧本名称,请重试',
  4748. // 'created_at' => $now,
  4749. // 'updated_at' => $now
  4750. // ]
  4751. // ];
  4752. // DB::table('mp_anime_records')->insert($records);
  4753. // DB::commit();
  4754. // } catch (\Exception $e) {
  4755. // DB::rollBack();
  4756. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4757. // }
  4758. // yield [
  4759. // 'type' => 'done',
  4760. // 'script' => [],
  4761. // 'episode' => [],
  4762. // 'answer' => $fullContent,
  4763. // 'reasoning' => $fullReasoningContent,
  4764. // 'usage' => $usage,
  4765. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  4766. // ];
  4767. // return;
  4768. // }
  4769. // 确认对话名称唯一性
  4770. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4771. $anime_name = $anime_name . '_' . date('YmdHis');
  4772. }
  4773. }else {
  4774. $anime_name = $user_anime_name;
  4775. }
  4776. $table_data = [
  4777. 'user_id' => $uid,
  4778. 'anime_name' => $anime_name,
  4779. 'model' => $model,
  4780. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4781. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4782. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4783. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4784. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4785. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4786. 'art_style_type' => $input_art_style,
  4787. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4788. 'status' => '解析完成',
  4789. 'content' => $content,
  4790. 'is_multi' => $is_multi,
  4791. 'ace_mode' => $ace_mode,
  4792. 'generate_status' => '待执行',
  4793. 'updated_at' => date('Y-m-d H:i:s')
  4794. ];
  4795. if ($table_data['content']) {
  4796. $chapters = splitContent($table_data['content']);
  4797. $chapter_count = count($chapters);
  4798. if ($chapter_count > 0) {
  4799. $table_data['start_episode_sequence'] = 1;
  4800. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4801. }
  4802. }
  4803. // 如果有剧本ID则进行绑定
  4804. if ($script_id) {
  4805. $table_data['script_id'] = $script_id;
  4806. }
  4807. $single_episode = [];
  4808. try {
  4809. DB::beginTransaction();
  4810. $now = date('Y-m-d H:i:s');
  4811. // 更新动漫大纲
  4812. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4813. if (!$boolen) {
  4814. dLog('deepseek')->info('动漫保存失败', $table_data);
  4815. Utils::throwError('20003:动漫保存失败');
  4816. }
  4817. // 保存对话记录
  4818. $records = [
  4819. [
  4820. 'uid' => $uid,
  4821. 'anime_id' => $anime_id,
  4822. 'sequence' => 0,
  4823. 'role' => 'user',
  4824. 'content' => $prompt,
  4825. 'created_at' => date('Y-m-d H:i:s'),
  4826. 'updated_at' => date('Y-m-d H:i:s')
  4827. ],
  4828. [
  4829. 'uid' => $uid,
  4830. 'anime_id' => $anime_id,
  4831. 'sequence' => 0,
  4832. 'role' => 'assistant',
  4833. 'content' => $fullContent,
  4834. 'created_at' => date('Y-m-d H:i:s'),
  4835. 'updated_at' => date('Y-m-d H:i:s')
  4836. ]
  4837. ];
  4838. // 保存对话记录
  4839. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4840. if (!$boolen3) {
  4841. Utils::throwError('20003:对话记录保存失败');
  4842. }
  4843. if ($is_single) {
  4844. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4845. if (empty($episode_arr['acts'])) {
  4846. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4847. }
  4848. $saveResult = $this->saveEpisodeVersionData(
  4849. $anime_id,
  4850. 1,
  4851. $episode_arr,
  4852. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4853. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4854. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  4855. null,
  4856. null,
  4857. false,
  4858. $content,
  4859. $now
  4860. );
  4861. $single_episode = $saveResult['episode'];
  4862. $episode_id = $saveResult['episode_id'];
  4863. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4864. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4865. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4866. 'props' => json_encode($saveResult['merged_props'], 256),
  4867. 'updated_at' => $now
  4868. ]);
  4869. if ($boolen5 === false) {
  4870. Utils::throwError('20003:单剧集主表资源同步失败');
  4871. }
  4872. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4873. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4874. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  4875. $episode_record_content = '确认分镜大纲';
  4876. if ($content !== '') {
  4877. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4878. }
  4879. $episode_records = [
  4880. [
  4881. 'uid' => $uid,
  4882. 'anime_id' => $anime_id,
  4883. 'role' => 'user',
  4884. 'content' => $episode_record_content,
  4885. 'sequence' => 1,
  4886. 'episode_id' => $episode_id,
  4887. 'created_at' => $now,
  4888. 'updated_at' => $now
  4889. ],
  4890. [
  4891. 'uid' => $uid,
  4892. 'anime_id' => $anime_id,
  4893. 'role' => 'assistant',
  4894. 'content' => $fullContent,
  4895. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4896. 'sequence' => 1,
  4897. 'episode_id' => $episode_id,
  4898. 'created_at' => $now,
  4899. 'updated_at' => $now
  4900. ]
  4901. ];
  4902. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4903. if (!$boolen4) {
  4904. Utils::throwError('20003:单剧集分镜记录保存失败');
  4905. }
  4906. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  4907. if ($is_single && !empty($single_episode)) {
  4908. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  4909. 'anime_id' => $anime_id,
  4910. 'episode_id' => $episode_id ?? 0,
  4911. ]);
  4912. }
  4913. }
  4914. }catch (\Exception $e) {
  4915. DB::rollBack();
  4916. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  4917. yield [
  4918. 'type' => 'done',
  4919. 'answer' => $fullContent,
  4920. 'reasoning' => $fullReasoningContent,
  4921. 'usage' => $usage,
  4922. 'error' => $e->getMessage(),
  4923. ];
  4924. return;
  4925. }
  4926. DB::commit();
  4927. dLog('deepseek')->info('保存完毕');
  4928. if ($is_single && !empty($single_episode)) {
  4929. // $this->batchSetGlobalRoleImg([
  4930. // 'anime_id' => $anime_id,
  4931. // ]);
  4932. // $this->batchSetGlobalSceneImg([
  4933. // 'anime_id' => $anime_id,
  4934. // ]);
  4935. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4936. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4937. }
  4938. $table_data['anime_id'] = $anime_id;
  4939. $table_data['roles'] = json_decode($table_data['roles'], true);
  4940. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4941. // $table_data['episodes'] = $script_arr['episodes'];
  4942. unset($table_data['created_at']);
  4943. unset($table_data['updated_at']);
  4944. unset($table_data['status']);
  4945. dLog('deepseek')->info('开始返回');
  4946. yield [
  4947. 'type' => 'done',
  4948. 'script' => $table_data,
  4949. 'episode' => $single_episode,
  4950. 'answer' => $fullContent,
  4951. 'reasoning' => $fullReasoningContent,
  4952. 'usage' => $usage
  4953. ];
  4954. }
  4955. public function reGenerateAnime($data) {
  4956. $uid = Site::getUid();
  4957. $file = getProp($data, 'file');
  4958. $content = getProp($data, 'content', '');
  4959. $bid = getProp($data, 'bid', 0);
  4960. $script_id = getProp($data, 'script_id', 0);
  4961. $anime_id = getProp($data, 'anime_id');
  4962. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4963. if (!$anime) {
  4964. Utils::throwError('20003:该对话不存在');
  4965. }
  4966. $user_anime_name = getProp($anime, 'anime_name');
  4967. $prompt = getProp($data, 'prompt');
  4968. // 处理文本模型
  4969. $model = getProp($data, 'model');
  4970. if (!$model) {
  4971. // 用户没有输入,从anime表获取
  4972. $model = getProp($anime, 'model');
  4973. if (!$model) {
  4974. // anime表也没有,使用默认值
  4975. $model = 'doubao-seed-2-0-mini-260215';
  4976. }
  4977. }
  4978. // 验证模型是否在可用模型表中
  4979. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4980. $model = 'doubao-seed-2-0-mini-260215';
  4981. }
  4982. $is_multi = getProp($anime, 'is_multi', 1);
  4983. $is_single = (int)$is_multi !== 1;
  4984. // 积分余额预检(仅单剧集模式收费)
  4985. if ($is_single) {
  4986. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  4987. }
  4988. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  4989. if ($is_single) {
  4990. $episode_exists = DB::table('mp_anime_episodes')
  4991. ->where('anime_id', $anime_id)
  4992. ->where('sequence', 1)
  4993. ->exists();
  4994. if ($episode_exists) {
  4995. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  4996. }
  4997. }
  4998. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4999. if ($prompt) {
  5000. $question .= "本次修改要求如下:\n{$prompt}";
  5001. }
  5002. // 提取文件内容
  5003. if ($file) {
  5004. $content = $this->extractFileContent($file);
  5005. if (!$content) {
  5006. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5007. }
  5008. } elseif ($script_id) {
  5009. $content = $this->getContentByScriptId($script_id);
  5010. if (!$content) {
  5011. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5012. }
  5013. } elseif ($bid) {
  5014. $content = $this->getContentByBid($bid);
  5015. if (!$content) {
  5016. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5017. }
  5018. } elseif ($content) {
  5019. $content = filterContent($content);
  5020. }else {
  5021. $content = filterContent(getProp($anime, 'content'));
  5022. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5023. $need_generate_content = true;
  5024. }
  5025. }
  5026. // 判断是否需要生成原文内容
  5027. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5028. // 如果需要生成原文内容,添加额外的要求
  5029. $content_generation_requirement = $need_generate_content
  5030. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5031. : "";
  5032. // 美术风格
  5033. $input_art_style = getProp($anime, 'art_style');
  5034. if (!$input_art_style) {
  5035. $input_art_style = getProp($data, 'art_style');
  5036. }
  5037. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5038. // 美术风格
  5039. if (!$mappedArtStyle) {
  5040. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5041. }else {
  5042. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5043. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5044. }else {
  5045. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5046. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5047. }
  5048. }
  5049. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5050. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5051. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5052. 中年女:邻居阿姨
  5053. 老年男:幽默大爷
  5054. 老年女:婆婆
  5055. 萌娃:奶气萌娃";
  5056. $system_message = ['role'=>'system', 'content'=>$is_single
  5057. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5058. 强制要求:
  5059. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5060. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5061. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5062. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5063. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5064. 普通要求:
  5065. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5066. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5067. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5068. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5069. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5070. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5071. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5072. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5073. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5074. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5075. 3.$mappedArtStyle_prompt\n\n
  5076. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5077. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5078. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5079. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5080. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5081. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5082. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5083. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5084. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5085. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5086. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5087. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5088. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5089. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5090. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5091. 示例如下:\n
  5092. ###剧本名:西昆仑
  5093. ###故事梗概
  5094. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5095. ###剧本亮点
  5096. 亮点1:绝境奇药,生死一线
  5097. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5098. 亮点2:结拜兄妹,化解尴尬
  5099. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5100. 亮点3:纤发夺命,情愫暗涌
  5101. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5102. ###人物关系
  5103. 阿雪与梁萧之间存在兄妹之情。
  5104. ###核心矛盾
  5105. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5106. ###主体列表
  5107. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5108. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5109. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5110. 姿态:站立。}{{甜心小美}}
  5111. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5112. 全景,正面拍摄,青年女性,亚洲人。
  5113. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5114. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5115. 姿态:站立。}{{阳光青年}}
  5116. ###美术风格
  5117. 基础画风风格词:厚涂古风
  5118. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5119. ###场景列表
  5120. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5121. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5122. 无人物。}
  5123. ###分镜剧本
  5124. ##第1幕:徐家老旧厨房 白天 室内
  5125. 分镜1
  5126. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5127. 场景:徐家老旧厨房
  5128. 构图设计:全景,低角度仰视
  5129. 运镜调度:手持拍摄
  5130. 配音角色:旁白
  5131. 出镜角色:许芸-校服装、徐母
  5132. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5133. 画面类型:普通画面
  5134. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5135. 分镜2
  5136. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5137. 场景:徐家老旧厨房
  5138. 构图设计:近景,徐母面部特写
  5139. 运镜调度:固定镜头
  5140. 配音角色:徐母
  5141. 出镜角色:徐母
  5142. 台词内容:问我夜不归宿死哪儿去了。
  5143. 画面类型:对口型
  5144. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5145. ##第2幕:徐家简陋客厅 黄昏 室内
  5146. 分镜3
  5147. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5148. 场景:徐家简陋客厅
  5149. 构图设计:全景,景深虚化
  5150. 运镜调度:固定镜头
  5151. 配音角色:旁白
  5152. 出镜角色:无
  5153. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5154. 画面类型:普通画面
  5155. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5156. 分镜4
  5157. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5158. 场景:徐家简陋客厅
  5159. 构图设计:特写,火车票
  5160. 运镜调度:固定镜头
  5161. 配音角色:旁白
  5162. 出镜角色:无
  5163. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5164. 画面类型:普通画面
  5165. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5166. "
  5167. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5168. 强制要求:\n
  5169. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5170. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5171. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5172. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5173. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5174. 普通要求:\n
  5175. 1.剧本名(必须生成)必须与文档内容高度相关
  5176. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5177. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5178. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5179. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5180. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5181. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5182. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5183. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5184. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5185. 4.$mappedArtStyle_prompt\n\n
  5186. 示例如下:\n
  5187. ###剧本名:西昆仑
  5188. ###故事梗概
  5189. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5190. ###剧本亮点
  5191. 亮点1:绝境奇药,生死一线
  5192. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5193. 亮点2:结拜兄妹,化解尴尬
  5194. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5195. 亮点3:纤发夺命,情愫暗涌
  5196. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5197. ###人物关系
  5198. 阿雪与梁萧之间存在兄妹之情。
  5199. ###核心矛盾
  5200. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5201. ###主体列表
  5202. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5203. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5204. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5205. 姿态:站立。}{{甜心小美}}
  5206. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5207. 全景,正面拍摄,青年女性,亚洲人。
  5208. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5209. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5210. 姿态:站立。}{{阳光青年}}
  5211. ###美术风格
  5212. 基础画风风格词:厚涂古风
  5213. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5214. ###场景列表
  5215. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5216. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5217. 无人物。}"];
  5218. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  5219. $episode_count = $this->extractEpisodeNumber($prompt);
  5220. if ((int)getProp($anime, 'is_multi') !== 1) {
  5221. yield [
  5222. 'type' => 'done',
  5223. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  5224. 'reasoning' => '',
  5225. 'usage' => []
  5226. ];
  5227. return;
  5228. }
  5229. if ($episode_count) {
  5230. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  5231. $system_message = [
  5232. 'role' => 'system',
  5233. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5234. 强制要求:\n
  5235. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5236. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5237. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5238. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5239. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5240. 普通要求:\n
  5241. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5242. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5243. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5244. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5245. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5246. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5247. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5248. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5249. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5250. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  5251. 示例如下:\n
  5252. ###剧本名:西昆仑
  5253. ###故事梗概
  5254. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5255. ###剧本亮点
  5256. 亮点1:绝境奇药,生死一线
  5257. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5258. 亮点2:结拜兄妹,化解尴尬
  5259. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5260. 亮点3:纤发夺命,情愫暗涌
  5261. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5262. ###人物关系
  5263. 阿雪与梁萧之间存在兄妹之情。
  5264. ###核心矛盾
  5265. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5266. ###主体列表
  5267. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5268. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5269. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5270. 姿态:站立。}{{甜心小美}}
  5271. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5272. 全景,正面拍摄,青年女性,亚洲人。
  5273. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5274. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5275. 姿态:站立。}{{阳光青年}}
  5276. ###美术风格
  5277. 基础画风风格词:厚涂古风
  5278. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5279. ###场景列表
  5280. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5281. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5282. 无人物。}
  5283. ###分集详细内容
  5284. ##第1章 重生
  5285. 我重生了。
  5286. 源于一个男人偏执的暗恋。
  5287. ##第2章 相救
  5288. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  5289. 我眼睛扫向站在锅炉后的卞大伟。"
  5290. ];
  5291. // 构建消息
  5292. $messages = [
  5293. $system_message,
  5294. [
  5295. 'role' => 'user',
  5296. 'content' => "以下是文档内容:
  5297. {$content}
  5298. 用户问题:
  5299. {$question}"
  5300. ]
  5301. ];
  5302. }else {
  5303. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  5304. // 构建消息
  5305. $messages = [
  5306. $system_message,
  5307. [
  5308. 'role' => 'user',
  5309. 'content' => "以下是文档内容:
  5310. {$content}
  5311. 用户问题:
  5312. {$question}"
  5313. ]
  5314. ];
  5315. }else {
  5316. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  5317. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  5318. return (array)$value;
  5319. })->toArray();
  5320. array_unshift($messages, $system_message);
  5321. $messages[] = [
  5322. 'role' => 'user',
  5323. 'content' => $prompt
  5324. ];
  5325. }
  5326. }
  5327. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5328. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5329. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5330. if ($model === 'deepseek-chat') {
  5331. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5332. $model = 'deepseek-v4-flash';
  5333. $thinkingMode = 'disabled';
  5334. } elseif ($model === 'deepseek-reasoner') {
  5335. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5336. $model = 'deepseek-v4-flash';
  5337. $thinkingMode = 'enabled';
  5338. }
  5339. $post_data = [
  5340. 'model' => $model,
  5341. 'messages' => $messages,
  5342. // 'max_tokens' => 8192,
  5343. 'temperature' => 0.7,
  5344. 'frequency_penalty' => 0,
  5345. 'presence_penalty' => 0,
  5346. 'response_format' => ['type' => 'text'],
  5347. 'thinking' => ['type' => $thinkingMode],
  5348. 'stream' => true // 启用流式输出
  5349. ];
  5350. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5351. // 根据模型类型选择调用方法
  5352. $fullContent = '';
  5353. $fullReasoningContent = '';
  5354. $usage = [];
  5355. // dd($post_data);
  5356. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  5357. try {
  5358. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5359. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5360. } else if (in_array($model, $this->gpt_text_models)) {
  5361. // GPT-5.4 模型使用 TokenRouter API
  5362. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5363. } else if (in_array($model, $this->gemini_text_models)) {
  5364. // Gemini 模型使用 Gemini API
  5365. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  5366. } else {
  5367. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5368. }
  5369. // 验证返回值类型
  5370. if (!is_iterable($streamGenerator)) {
  5371. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5372. dLog('deepseek')->error('方法名流式生成器无效', [
  5373. 'generator_type' => $errorType,
  5374. 'model' => $model,
  5375. // 添加其他上下文信息
  5376. ]);
  5377. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  5378. 'type' => $errorType,
  5379. 'model' => $model
  5380. ]);
  5381. yield [
  5382. 'type' => 'error',
  5383. // 根据方法返回相应的空数据结构
  5384. 'answer' => '',
  5385. 'reasoning' => '',
  5386. 'usage' => [],
  5387. 'error' => '接口返回数据异常,请重新请求'
  5388. ];
  5389. return;
  5390. }
  5391. // 处理流式输出
  5392. foreach ($streamGenerator as $chunk) {
  5393. if (isset($chunk['type'])) {
  5394. if ($chunk['type'] === 'done') {
  5395. $fullContent = $chunk['full_content'];
  5396. $fullReasoningContent = $chunk['full_reasoning'];
  5397. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5398. } else {
  5399. yield $chunk;
  5400. }
  5401. }
  5402. }
  5403. } catch (\Exception $e) {
  5404. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  5405. 'model' => $model,
  5406. 'trace' => $e->getTraceAsString()
  5407. ]);
  5408. logDB('deepseek', 'error', '方法名流式处理失败', [
  5409. 'error' => $e->getMessage(),
  5410. 'model' => $model
  5411. ]);
  5412. yield [
  5413. 'type' => 'error',
  5414. // 根据方法返回相应的空数据结构
  5415. 'answer' => '',
  5416. 'reasoning' => '',
  5417. 'usage' => [],
  5418. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5419. ];
  5420. return;
  5421. }
  5422. dLog('deepseek')->info('完整内容: '.$fullContent);
  5423. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5424. // 处理完整内容并返回最终结果
  5425. $script_arr = [];
  5426. if ($fullContent) {
  5427. $script_arr = handleScriptContent($fullContent);
  5428. dLog('deepseek')->info('解析内容', $script_arr);
  5429. logDB('deepseek', 'info', '解析内容', $script_arr);
  5430. }
  5431. if (empty($script_arr['roles'])) {
  5432. // 未生成剧本相关内容,保存对话记录并返回提示
  5433. dLog('deepseek')->info('未生成剧本相关的内容');
  5434. try {
  5435. $now = date('Y-m-d H:i:s');
  5436. // 保存对话记录
  5437. $records = [
  5438. [
  5439. 'uid' => $uid,
  5440. 'anime_id' => $anime_id,
  5441. 'sequence' => 0,
  5442. 'role' => 'user',
  5443. 'content' => $prompt,
  5444. 'created_at' => $now,
  5445. 'updated_at' => $now
  5446. ],
  5447. [
  5448. 'uid' => $uid,
  5449. 'anime_id' => $anime_id,
  5450. 'sequence' => 0,
  5451. 'role' => 'assistant',
  5452. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  5453. 'created_at' => $now,
  5454. 'updated_at' => $now
  5455. ]
  5456. ];
  5457. DB::table('mp_anime_records')->insert($records);
  5458. } catch (\Exception $e) {
  5459. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5460. }
  5461. yield [
  5462. 'type' => 'done',
  5463. 'script' => [],
  5464. 'episode' => [],
  5465. 'answer' => $fullContent,
  5466. 'reasoning' => $fullReasoningContent,
  5467. 'usage' => $usage,
  5468. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5469. ];
  5470. return;
  5471. }
  5472. // 替换美术风格
  5473. if ($mappedArtStyle !== '') {
  5474. $script_arr['art_style'] = $mappedArtStyle;
  5475. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5476. }
  5477. if ($user_anime_name != '新剧本策划') {
  5478. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5479. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5480. // 确认对话名称唯一性
  5481. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5482. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  5483. }
  5484. }else {
  5485. $anime_name = $user_anime_name;
  5486. }
  5487. $table_data = [
  5488. 'user_id' => $uid,
  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. 'generate_status' => '待执行',
  5500. 'updated_at' => date('Y-m-d H:i:s')
  5501. ];
  5502. if ($anime_name) $table_data['anime_name'] = $anime_name;
  5503. // 如果是修改集数,则将content内容更新(会改变原文)
  5504. if (isset($episode_count) && $episode_count > 0) {
  5505. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  5506. $table_data['start_episode_sequence'] = 1;
  5507. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  5508. }else {
  5509. // 如果需要生成原文内容,从script_arr中提取
  5510. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5511. $table_data['content'] = $script_arr['content'];
  5512. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  5513. if (!$table_data['content']) {
  5514. yield [
  5515. 'type' => 'done',
  5516. 'script' => [],
  5517. 'episode' => [],
  5518. 'answer' => $fullContent,
  5519. 'reasoning' => $fullReasoningContent,
  5520. 'usage' => $usage,
  5521. 'error' => '未生成剧本内容,请调整提示词再试'
  5522. ];
  5523. return;
  5524. }
  5525. }
  5526. if (isset($table_data['content']) && $table_data['content']) {
  5527. $chapters = splitContent($table_data['content']);
  5528. $chapter_count = count($chapters);
  5529. if ($chapter_count > 0) {
  5530. $table_data['start_episode_sequence'] = 1;
  5531. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5532. }
  5533. }
  5534. }
  5535. $single_episode = [];
  5536. try {
  5537. DB::beginTransaction();
  5538. $now = date('Y-m-d H:i:s');
  5539. // 更新动漫大纲
  5540. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5541. if (!$boolen) {
  5542. dLog('deepseek')->info('对话修改失败', $table_data);
  5543. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  5544. Utils::throwError('20003:对话修改失败');
  5545. }
  5546. // 保存对话记录
  5547. $records = [
  5548. [
  5549. 'uid' => $uid,
  5550. 'anime_id' => $anime_id,
  5551. 'sequence' => 0,
  5552. 'role' => 'user',
  5553. 'content' => $prompt,
  5554. 'created_at' => $now,
  5555. 'updated_at' => $now
  5556. ],
  5557. [
  5558. 'uid' => $uid,
  5559. 'anime_id' => $anime_id,
  5560. 'sequence' => 0,
  5561. 'role' => 'assistant',
  5562. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5563. 'content' => $fullContent,
  5564. 'created_at' => $now,
  5565. 'updated_at' => $now
  5566. ]
  5567. ];
  5568. // 保存对话记录
  5569. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5570. if (!$boolen3) {
  5571. Utils::throwError('20003:对话记录保存失败');
  5572. }
  5573. // 单剧集模式:生成并保存剧集信息
  5574. if ($is_single) {
  5575. $anime_name = getProp($anime, 'anime_name', '未命名');
  5576. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5577. if (empty($episode_arr['acts'])) {
  5578. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5579. }
  5580. $saveResult = $this->saveEpisodeVersionData(
  5581. $anime_id,
  5582. 1,
  5583. $episode_arr,
  5584. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5585. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5586. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5587. null,
  5588. null,
  5589. false,
  5590. $content,
  5591. $now
  5592. );
  5593. $single_episode = $saveResult['episode'];
  5594. $episode_id = $saveResult['episode_id'];
  5595. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5596. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5597. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5598. 'props' => json_encode($saveResult['merged_props'], 256),
  5599. 'updated_at' => $now
  5600. ]);
  5601. if ($boolen5 === false) {
  5602. Utils::throwError('20003:单剧集主表资源同步失败');
  5603. }
  5604. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5605. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5606. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5607. $episode_record_content = '确认分镜大纲';
  5608. if ($content !== '') {
  5609. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5610. }
  5611. $episode_records = [
  5612. [
  5613. 'uid' => $uid,
  5614. 'anime_id' => $anime_id,
  5615. 'role' => 'user',
  5616. 'content' => $episode_record_content,
  5617. 'sequence' => 1,
  5618. 'episode_id' => $episode_id,
  5619. 'created_at' => $now,
  5620. 'updated_at' => $now
  5621. ],
  5622. [
  5623. 'uid' => $uid,
  5624. 'anime_id' => $anime_id,
  5625. 'role' => 'assistant',
  5626. 'content' => $fullContent,
  5627. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5628. 'sequence' => 1,
  5629. 'episode_id' => $episode_id,
  5630. 'created_at' => $now,
  5631. 'updated_at' => $now
  5632. ]
  5633. ];
  5634. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5635. if (!$boolen4) {
  5636. Utils::throwError('20003:单剧集分镜记录保存失败');
  5637. }
  5638. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  5639. if ($is_single && !empty($single_episode)) {
  5640. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5641. 'anime_id' => $anime_id,
  5642. 'episode_id' => $episode_id ?? 0,
  5643. ]);
  5644. }
  5645. }
  5646. }catch (\Exception $e) {
  5647. DB::rollBack();
  5648. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  5649. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  5650. yield [
  5651. 'type' => 'done',
  5652. 'answer' => $fullContent,
  5653. 'reasoning' => $fullReasoningContent,
  5654. 'usage' => $usage,
  5655. 'error' => $e->getMessage(),
  5656. ];
  5657. return;
  5658. }
  5659. DB::commit();
  5660. dLog('deepseek')->info('保存完毕');
  5661. if ($is_single && !empty($single_episode)) {
  5662. // $this->batchSetGlobalRoleImg([
  5663. // 'anime_id' => $anime_id,
  5664. // ]);
  5665. // $this->batchSetGlobalSceneImg([
  5666. // 'anime_id' => $anime_id,
  5667. // ]);
  5668. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5669. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5670. }
  5671. $table_data['anime_id'] = $anime_id;
  5672. $table_data['roles'] = json_decode($table_data['roles'], true);
  5673. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5674. unset($table_data['updated_at']);
  5675. unset($table_data['status']);
  5676. yield [
  5677. 'type' => 'done',
  5678. 'script' => $table_data,
  5679. 'episode' => $single_episode,
  5680. 'answer' => $fullContent,
  5681. 'reasoning' => $fullReasoningContent,
  5682. 'usage' => $usage
  5683. ];
  5684. }
  5685. public function chat($data) {
  5686. $uid = Site::getUid();
  5687. // 积分余额预检(不足直接报错)
  5688. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  5689. $anime_id = getProp($data, 'anime_id');
  5690. $file = getProp($data, 'file');
  5691. $content = getProp($data, 'content', '');
  5692. $bid = getProp($data, 'bid', 0);
  5693. $script_id = getProp($data, 'script_id', 0);
  5694. $episode_number = getProp($data, 'episode_number', 1);
  5695. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5696. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5697. if (!$anime) Utils::throwError('20003:该对话不存在!');
  5698. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  5699. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  5700. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  5701. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  5702. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  5703. $roles = is_array($roles) ? $roles : [];
  5704. $scenes = is_array($scenes) ? $scenes : [];
  5705. // 获取最后一集序号
  5706. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  5707. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  5708. // 转换主体列表和场景列表的格式
  5709. // 获取参考主体或场景
  5710. if ((int)$episode_number === 1) {
  5711. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  5712. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  5713. }else {
  5714. $prev_episode_number = $episode_number - 1;
  5715. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  5716. }
  5717. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  5718. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  5719. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  5720. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  5721. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5722. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5723. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5724. 中年女:邻居阿姨
  5725. 老年男:幽默大爷
  5726. 老年女:婆婆
  5727. 萌娃:奶气萌娃";
  5728. if ($roles_content) {
  5729. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  5730. 主体范围:\n {$roles_content}\n
  5731. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  5732. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5733. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  5734. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5735. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  5736. }else {
  5737. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5738. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5739. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  5740. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5741. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  5742. }
  5743. if ($scenes_content) {
  5744. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  5745. 场景范围:\n {$scenes_content}\n
  5746. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  5747. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5748. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5749. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  5750. }else {
  5751. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5752. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5753. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5754. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  5755. }
  5756. // 提取文件内容
  5757. if ($file) {
  5758. $uploaded_content = $this->extractFileContent($file);
  5759. if (!$uploaded_content) {
  5760. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5761. }
  5762. } elseif ($script_id) {
  5763. $uploaded_content = $this->getContentByScriptId($script_id);
  5764. if (!$uploaded_content) {
  5765. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5766. }
  5767. } elseif ($bid) {
  5768. $uploaded_content = $this->getContentByBid($bid);
  5769. if (!$uploaded_content) {
  5770. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5771. }
  5772. } elseif ($content) {
  5773. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  5774. }
  5775. // elseif ($prompt) {
  5776. // $uploaded_content = filterContent($prompt);
  5777. // }
  5778. else {
  5779. $uploaded_content = '';
  5780. }
  5781. $input_art_style = getProp($anime, 'art_style');
  5782. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5783. // 美术风格
  5784. if (!$mappedArtStyle) {
  5785. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5786. }else {
  5787. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5788. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5789. }else {
  5790. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5791. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5792. }
  5793. }
  5794. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5795. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5796. // 强制要求:
  5797. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5798. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5799. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5800. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  5801. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  5802. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  5803. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  5804. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  5805. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  5806. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  5807. // - 分镜要和场景列表、人物主体保持一致\n
  5808. // 普通要求:
  5809. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  5810. // {$role_demo}
  5811. // {$scene_demo}
  5812. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5813. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5814. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5815. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5816. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  5817. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5818. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5819. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5820. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5821. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5822. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5823. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5824. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5825. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5826. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  5827. // 5.$mappedArtStyle_prompt\n\n
  5828. // 示例格式:\n
  5829. // 第1集:隐形的守护者
  5830. // ###故事梗概
  5831. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5832. // ###美术风格
  5833. // 基础画风风格词:韩漫二次元
  5834. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  5835. // ###主体列表
  5836. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  5837. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  5838. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  5839. // ###场景列表
  5840. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  5841. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5842. // 无人物。}
  5843. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  5844. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  5845. // 无人物。}
  5846. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  5847. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  5848. // 无人物。}
  5849. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  5850. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  5851. // 无人物。}
  5852. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  5853. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  5854. // 无人物。}
  5855. // ###分镜剧本
  5856. // ##第1幕:徐家老旧厨房 白天 室内
  5857. // 分镜1
  5858. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5859. // 场景:徐家老旧厨房
  5860. // 构图设计:全景,低角度仰视
  5861. // 运镜调度:手持拍摄
  5862. // 配音角色:旁白
  5863. // 出镜角色:许芸-校服装、徐母
  5864. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5865. // 画面类型:普通画面
  5866. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5867. // 分镜2
  5868. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5869. // 场景:徐家老旧厨房
  5870. // 构图设计:近景,徐母面部特写
  5871. // 运镜调度:固定镜头
  5872. // 配音角色:徐母
  5873. // 出镜角色:徐母
  5874. // 台词内容:问我夜不归宿死哪儿去了。
  5875. // 画面类型:对口型
  5876. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5877. // ##第2幕:徐家简陋客厅 黄昏 室内
  5878. // 分镜3
  5879. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5880. // 场景:徐家简陋客厅
  5881. // 构图设计:全景,景深虚化
  5882. // 运镜调度:固定镜头
  5883. // 配音角色:旁白
  5884. // 出镜角色:无
  5885. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5886. // 画面类型:普通画面
  5887. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5888. // 分镜4
  5889. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5890. // 场景:徐家简陋客厅
  5891. // 构图设计:特写,火车票
  5892. // 运镜调度:固定镜头
  5893. // 配音角色:旁白
  5894. // 出镜角色:无
  5895. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5896. // 画面类型:普通画面
  5897. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  5898. // \n\n";
  5899. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  5900. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  5901. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  5902. 普通要求:
  5903. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  5904. {$role_demo}
  5905. {$scene_demo}
  5906. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5907. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5908. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5909. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  5910. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  5911. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5912. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5913. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5914. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5915. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5916. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5917. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5918. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5919. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5920. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  5921. 5.$mappedArtStyle_prompt
  5922. 6.《情绪-视听语言映射表》:
  5923. 6.1 场景空间与时间心理学 (Scene & Temporality)
  5924. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  5925. -----|---------|------------|----------------
  5926. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  5927. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  5928. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  5929. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  5930. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  5931. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  5932. -----|---------|------------|----------------
  5933. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  5934. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  5935. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  5936. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  5937. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  5938. --------|---------|--------------|-------------
  5939. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  5940. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  5941. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  5942. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  5943. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  5944. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  5945. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  5946. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  5947. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  5948. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  5949. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  5950. -----|---------|------------|------------
  5951. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  5952. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  5953. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  5954. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  5955. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  5956. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  5957. --------|---------|--------------|----------
  5958. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  5959. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  5960. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  5961. 6.6 声音设计与潜意识影响 (Soundscape)
  5962. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  5963. -----|---------|------------|------------------
  5964. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  5965. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  5966. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  5967. 理论基石:
  5968. - The Five C's of Cinematography by Joseph V. Mascelli
  5969. - Film Art: An Introduction by David Bordwell
  5970. - Sight, Sound, Motion by Herbert Zettl
  5971. - Notes on the Cinematograph by Robert Bresson
  5972. \n\n
  5973. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  5974. 示例格式:\n
  5975. 第1集:隐形的守护者
  5976. ###故事梗概
  5977. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5978. ###美术风格
  5979. 基础画风风格词:韩漫二次元
  5980. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  5981. ###主体列表
  5982. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  5983. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  5984. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  5985. ###场景列表
  5986. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  5987. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5988. 无人物。}
  5989. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  5990. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  5991. 无人物。}
  5992. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  5993. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  5994. 无人物。}
  5995. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  5996. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  5997. 无人物。}
  5998. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  5999. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6000. 无人物。}
  6001. ###分镜剧本
  6002. ##第1幕:徐家老旧厨房 白天 室内
  6003. 分镜1
  6004. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6005. 场景:徐家老旧厨房
  6006. 构图设计:全景,低角度仰视
  6007. 运镜调度:手持拍摄
  6008. 配音角色:旁白
  6009. 出镜角色:许芸-校服装、徐母
  6010. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6011. 画面类型:普通画面
  6012. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6013. 分镜2
  6014. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6015. 场景:徐家老旧厨房
  6016. 构图设计:近景,徐母面部特写
  6017. 运镜调度:固定镜头
  6018. 配音角色:徐母
  6019. 出镜角色:徐母
  6020. 台词内容:问我夜不归宿死哪儿去了。
  6021. 画面类型:对口型
  6022. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6023. ##第2幕:徐家简陋客厅 黄昏 室内
  6024. 分镜3
  6025. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6026. 场景:徐家简陋客厅
  6027. 构图设计:全景,景深虚化
  6028. 运镜调度:固定镜头
  6029. 配音角色:旁白
  6030. 出镜角色:无
  6031. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6032. 画面类型:普通画面
  6033. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6034. 分镜4
  6035. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6036. 场景:徐家简陋客厅
  6037. 构图设计:特写,火车票
  6038. 运镜调度:固定镜头
  6039. 配音角色:旁白
  6040. 出镜角色:无
  6041. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6042. 画面类型:普通画面
  6043. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6044. \n\n";
  6045. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6046. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  6047. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  6048. $prompt = $origin_prompt;
  6049. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  6050. // 获取章节内容
  6051. $full_content = getProp($anime, 'content');
  6052. if ($uploaded_content) {
  6053. $full_content = $uploaded_content;
  6054. }
  6055. // 根据章节内容拆分章节
  6056. $chapters = splitContent($full_content);
  6057. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  6058. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  6059. $messages = [];
  6060. if ($prompt == '确认分镜大纲') {
  6061. // 暂时保留
  6062. $content = $chapter_content;
  6063. if ($is_single) $content = $full_content; // 单剧集使用全文
  6064. if (!$content) {
  6065. Utils::throwError('20003:章节内容无法获取,请确认');
  6066. }
  6067. $question = $is_single
  6068. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  6069. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  6070. // 构建消息
  6071. $messages[] =
  6072. [
  6073. 'role' => 'user',
  6074. 'content' => $question
  6075. ];
  6076. }else if ($prompt == '继续策划下一集') {
  6077. if ($is_single) {
  6078. Utils::throwError('20003:单剧集不支持继续策划下一集');
  6079. }
  6080. $content = $chapter_content;
  6081. if (!$content) {
  6082. Utils::throwError('20003:章节内容无法获取,请确认');
  6083. }
  6084. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  6085. // 获取上一集最后记录
  6086. $prev_sequence = $episode_number - 1;
  6087. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  6088. // 构建消息
  6089. $messages[] =
  6090. [
  6091. 'role' => 'user',
  6092. 'content' => $question
  6093. ];
  6094. }else {
  6095. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  6096. if (!$content) {
  6097. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  6098. }
  6099. if (!$content) {
  6100. Utils::throwError('20003:章节内容无法获取,请确认');
  6101. }
  6102. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  6103. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  6104. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  6105. if ($origin_prompt) {
  6106. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  6107. }
  6108. $messages[] =
  6109. [
  6110. 'role' => 'user',
  6111. 'content' => $question
  6112. ];
  6113. }
  6114. // 处理文本模型
  6115. $model = getProp($data, 'model');
  6116. if (!$model) {
  6117. // 用户没有输入,从anime表获取
  6118. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6119. $model = getProp($anime, 'model');
  6120. if (!$model) {
  6121. // anime表也没有,使用默认值
  6122. $model = 'doubao-seed-2-0-mini-260215';
  6123. }
  6124. }
  6125. // 验证模型是否在可用模型表中
  6126. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6127. $model = 'doubao-seed-2-0-mini-260215';
  6128. }
  6129. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6130. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6131. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6132. if ($model === 'deepseek-chat') {
  6133. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6134. $model = 'deepseek-v4-flash';
  6135. $thinkingMode = 'disabled';
  6136. } elseif ($model === 'deepseek-reasoner') {
  6137. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6138. $model = 'deepseek-v4-flash';
  6139. $thinkingMode = 'enabled';
  6140. }
  6141. $post_data = [
  6142. 'model' => $model,
  6143. 'messages' => $messages,
  6144. // 'max_tokens' => 8192,
  6145. 'temperature' => 0.2,
  6146. 'frequency_penalty' => 0,
  6147. 'presence_penalty' => 0,
  6148. 'response_format' => ['type' => 'text'],
  6149. 'thinking' => ['type' => $thinkingMode],
  6150. 'stream' => true // 启用流式输出
  6151. ];
  6152. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6153. // 根据模型类型选择调用方法
  6154. $fullContent = '';
  6155. $fullReasoningContent = '';
  6156. $usage = [];
  6157. try {
  6158. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6159. // DeepSeek 官方模型使用 DeepSeek API
  6160. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6161. } else if (in_array($model, $this->gpt_text_models)) {
  6162. // GPT-5.4 模型使用 TokenRouter API
  6163. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6164. } else if (in_array($model, $this->gemini_text_models)) {
  6165. // Gemini 模型使用 Gemini API
  6166. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6167. } else {
  6168. // 其他模型使用火山引擎API
  6169. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6170. }
  6171. // 验证返回值类型
  6172. if (!is_iterable($streamGenerator)) {
  6173. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6174. dLog('deepseek')->error('chat流式生成器无效', [
  6175. 'generator_type' => $errorType,
  6176. 'model' => $model,
  6177. 'anime_id' => $anime_id,
  6178. 'episode_number' => $episode_number
  6179. ]);
  6180. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  6181. 'type' => $errorType,
  6182. 'model' => $model
  6183. ]);
  6184. yield [
  6185. 'type' => 'error',
  6186. 'episode' => [],
  6187. 'answer' => '',
  6188. 'reasoning' => '',
  6189. 'usage' => [],
  6190. 'error' => '接口返回数据异常,请重新请求'
  6191. ];
  6192. return;
  6193. }
  6194. // 处理流式输出
  6195. foreach ($streamGenerator as $chunk) {
  6196. if (isset($chunk['type'])) {
  6197. if ($chunk['type'] === 'done') {
  6198. // 最终结果
  6199. $fullContent = $chunk['full_content'];
  6200. $fullReasoningContent = $chunk['full_reasoning'];
  6201. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6202. } else {
  6203. // 逐块yield数据
  6204. yield $chunk;
  6205. }
  6206. }
  6207. }
  6208. } catch (\Exception $e) {
  6209. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  6210. 'model' => $model,
  6211. 'anime_id' => $anime_id,
  6212. 'episode_number' => $episode_number,
  6213. 'trace' => $e->getTraceAsString()
  6214. ]);
  6215. logDB('deepseek', 'error', 'chat流式处理失败', [
  6216. 'error' => $e->getMessage(),
  6217. 'model' => $model
  6218. ]);
  6219. yield [
  6220. 'type' => 'error',
  6221. 'episode' => [],
  6222. 'answer' => '',
  6223. 'reasoning' => '',
  6224. 'usage' => [],
  6225. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6226. ];
  6227. return;
  6228. }
  6229. dLog('deepseek')->info('完整内容: '.$fullContent);
  6230. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6231. // 处理完整内容并返回最终结果
  6232. $episode_arr = handleEpisodeContent($fullContent);
  6233. logDB('deepseek', 'info', '解析内容', $episode_arr);
  6234. if (empty($episode_arr['acts'])) {
  6235. // 未生成剧本相关内容,保存对话记录并返回提示
  6236. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  6237. try {
  6238. $now = date('Y-m-d H:i:s');
  6239. // 保存对话记录
  6240. $records = [
  6241. [
  6242. 'uid' => $uid,
  6243. 'anime_id' => $anime_id,
  6244. 'sequence' => $episode_number,
  6245. 'role' => 'user',
  6246. 'content' => $prompt,
  6247. 'created_at' => $now,
  6248. 'updated_at' => $now
  6249. ],
  6250. [
  6251. 'uid' => $uid,
  6252. 'anime_id' => $anime_id,
  6253. 'sequence' => $episode_number,
  6254. 'role' => 'assistant',
  6255. 'content' => $fullContent,
  6256. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6257. 'created_at' => $now,
  6258. 'updated_at' => $now
  6259. ]
  6260. ];
  6261. DB::table('mp_anime_records')->insert($records);
  6262. } catch (\Exception $e) {
  6263. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6264. }
  6265. yield [
  6266. 'type' => 'done',
  6267. 'episode' => [],
  6268. 'answer' => $fullContent,
  6269. 'reasoning' => $fullReasoningContent,
  6270. 'usage' => $usage,
  6271. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  6272. ];
  6273. return;
  6274. }
  6275. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  6276. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  6277. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  6278. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  6279. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  6280. $existing_props = is_array($existing_props) ? $existing_props : [];
  6281. $now = date('Y-m-d H:i:s');
  6282. try {
  6283. DB::beginTransaction();
  6284. $saveResult = $this->saveEpisodeVersionData(
  6285. $anime_id,
  6286. $episode_number,
  6287. $episode_arr,
  6288. $existing_roles,
  6289. $existing_scenes,
  6290. $existing_props,
  6291. $current_episode,
  6292. $base_episode,
  6293. $is_regenerate_version,
  6294. $content,
  6295. $now
  6296. );
  6297. $episode = $saveResult['episode'];
  6298. $episode_id = $saveResult['episode_id'];
  6299. $merged_roles = $saveResult['merged_roles'];
  6300. $merged_scenes = $saveResult['merged_scenes'];
  6301. $merged_props = $saveResult['merged_props'];
  6302. $record_content = $origin_prompt;
  6303. if ($uploaded_content !== '') {
  6304. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  6305. }
  6306. $records = [
  6307. [
  6308. 'uid' => $uid,
  6309. 'anime_id' => $anime_id,
  6310. 'role' => 'user',
  6311. 'content' => $record_content,
  6312. 'sequence' => $episode_number,
  6313. 'episode_id' => $episode_id,
  6314. 'created_at' => $now,
  6315. 'updated_at' => $now
  6316. ],
  6317. [
  6318. 'uid' => $uid,
  6319. 'anime_id' => $anime_id,
  6320. 'role' => 'assistant',
  6321. 'content' => $fullContent,
  6322. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6323. 'sequence' => $episode_number,
  6324. 'episode_id' => $episode_id,
  6325. 'created_at' => $now,
  6326. 'updated_at' => $now
  6327. ]
  6328. ];
  6329. $boolen4 = DB::table('mp_anime_records')->insert($records);
  6330. if (!$boolen4) {
  6331. Utils::throwError('20003:对话记录保存失败');
  6332. }
  6333. // 保存模型和内容到anime表
  6334. $update_anime_data = [
  6335. 'model' => $model,
  6336. 'updated_at' => $now
  6337. ];
  6338. if ($uploaded_content) {
  6339. $update_anime_data['content'] = $uploaded_content;
  6340. }
  6341. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  6342. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6343. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6344. 'anime_id' => $anime_id,
  6345. 'episode_number' => $episode_number,
  6346. 'model' => $model,
  6347. ]);
  6348. }catch (\Exception $e) {
  6349. DB::rollBack();
  6350. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6351. yield [
  6352. 'type' => 'done',
  6353. 'answer' => $fullContent,
  6354. 'reasoning' => $fullReasoningContent,
  6355. 'usage' => $usage,
  6356. 'error' => $e->getMessage(),
  6357. ];
  6358. return;
  6359. }
  6360. DB::commit();
  6361. if ($is_global_generate_pics) {
  6362. // // 批量生成全局角色图片
  6363. // $this->batchSetGlobalRoleImg([
  6364. // 'anime_id' => $anime_id,
  6365. // ], true);
  6366. // // 批量生成全局场景图片
  6367. // $this->batchSetGlobalSceneImg([
  6368. // 'anime_id' => $anime_id,
  6369. // ], true);
  6370. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6371. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6372. }
  6373. $episode['episode_id'] = $episode_id;
  6374. $episode['roles'] = $merged_roles;
  6375. $episode['scenes'] = $merged_scenes;
  6376. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  6377. yield [
  6378. 'type' => 'done',
  6379. 'episode' => $episode,
  6380. 'answer' => $fullContent,
  6381. 'reasoning' => $fullReasoningContent,
  6382. 'usage' => $usage
  6383. ];
  6384. }
  6385. public function addChatForAce($data) {
  6386. $uid = Site::getUid();
  6387. $anime_id = getProp($data, 'anime_id');
  6388. if (!$anime_id) Utils::throwError('20003:请选择对话');
  6389. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  6390. if (!$anime) Utils::throwError('20003:对话不存在');
  6391. $file = getProp($data, 'file');
  6392. $content = getProp($data, 'content', '');
  6393. $bid = getProp($data, 'bid', 0);
  6394. $script_id = getProp($data, 'script_id', 0);
  6395. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  6396. $prompt = getProp($data, 'prompt');
  6397. $is_multi = getProp($anime, 'is_multi');
  6398. $is_single = (int)$is_multi !== 1;
  6399. // 积分余额预检(仅单剧集模式收费)
  6400. if ($is_single) {
  6401. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  6402. }
  6403. $extra_products = getProp($data, 'products', []);
  6404. if (!$extra_products) {
  6405. $extra_products = getProp($anime, 'extra_products');
  6406. if ($extra_products) {
  6407. $extra_products = json_decode($extra_products, true);
  6408. }else {
  6409. $extra_products = [];
  6410. }
  6411. }else {
  6412. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6413. }
  6414. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6415. $anime_script_id = getProp($anime, 'script_id');
  6416. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  6417. $cpid = Site::getCpid();
  6418. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6419. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6420. ->where('mapping.script_id', $anime_script_id)
  6421. ->where('product.cpid', $cpid)
  6422. ->where('product.is_deleted', 0);
  6423. $mappings = $script_products_mappings->select(
  6424. 'mapping.product_id',
  6425. 'mapping.episode_number',
  6426. 'product.product_name',
  6427. 'product.type',
  6428. 'product.product',
  6429. 'product.pic_prompt',
  6430. 'product.url',
  6431. 'product.pic_task_id',
  6432. 'product.pic_task_status',
  6433. 'product.three_view_image_url'
  6434. )
  6435. ->get();
  6436. // 按 product_id 分组,合并 episode_number
  6437. $productMap = [];
  6438. foreach ($mappings as $item) {
  6439. $product_id = $item->product_id;
  6440. $product_name = $item->product_name;
  6441. // 处理product_name两边的符号
  6442. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6443. if (!isset($productMap[$product_id])) {
  6444. $productMap[$product_id] = [
  6445. 'product_id' => $product_id,
  6446. 'product_name' => $product_name,
  6447. 'type' => (int)$item->type,
  6448. 'product' => (int)$item->product,
  6449. 'pic_prompt' => $item->pic_prompt,
  6450. 'url' => $item->url,
  6451. 'pic_task_id' => $item->pic_task_id,
  6452. 'pic_task_status' => $item->pic_task_status,
  6453. 'episode_numbers' => [],
  6454. ];
  6455. }
  6456. // 添加 episode_number(去重)
  6457. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6458. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6459. }
  6460. }
  6461. // 将查询到的剧本资产合并到extra_products中
  6462. // 先构建extra_products的索引(以product_id为key,用于去重)
  6463. $extraProductsMap = [];
  6464. foreach ($extra_products as $item) {
  6465. $key = getProp($item, 'product_id');
  6466. if ($key) {
  6467. $extraProductsMap[$key] = $item;
  6468. }
  6469. }
  6470. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6471. foreach ($productMap as $product) {
  6472. $product_id = $product['product_id'];
  6473. // 如果不存在则添加(不带episode_number信息)
  6474. if (!isset($extraProductsMap[$product_id])) {
  6475. $extraProductsMap[$product_id] = [
  6476. 'product_id' => $product['product_id'],
  6477. 'product_name' => $product['product_name'],
  6478. 'type' => $product['type'],
  6479. 'product' => $product['product'],
  6480. 'pic_prompt' => $product['pic_prompt'],
  6481. 'url' => $product['url'],
  6482. 'pic_task_id' => $product['pic_task_id'],
  6483. 'pic_task_status' => $product['pic_task_status'],
  6484. ];
  6485. }
  6486. }
  6487. // 重新赋值给extra_products
  6488. $extra_products = array_values($extraProductsMap);
  6489. }
  6490. $user_anime_name = getProp($anime, 'anime_name');
  6491. // 处理提示词
  6492. if ($prompt && $extra_products) {
  6493. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6494. foreach($extra_products as $item) {
  6495. $product_name = getProp($item, 'product_name');
  6496. if ($product_name) {
  6497. // 替换 {product_name} 为 product_name
  6498. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6499. }
  6500. }
  6501. }
  6502. // 处理文本模型
  6503. $model = getProp($data, 'model');
  6504. if (!$model) {
  6505. // 用户没有输入,从anime表获取
  6506. $model = getProp($anime, 'model');
  6507. if (!$model) {
  6508. // anime表也没有,使用默认值
  6509. $model = 'deepseek-v4-pro';
  6510. }
  6511. }
  6512. // 验证模型是否在可用模型表中
  6513. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6514. $model = 'deepseek-v4-pro';
  6515. }
  6516. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6517. if ($prompt) {
  6518. $question .= "本次修改要求如下:\n{$prompt}";
  6519. }
  6520. // if (!$file && !$content && !$bid) {
  6521. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  6522. // }
  6523. // 提取文件内容
  6524. if ($file) {
  6525. $content = $this->extractFileContent($file);
  6526. if (!$content) {
  6527. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6528. }
  6529. } elseif ($script_id) {
  6530. $content = $this->getContentByScriptId($script_id);
  6531. if (!$content) {
  6532. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6533. }
  6534. } elseif ($bid) {
  6535. $content = $this->getContentByBid($bid);
  6536. if (!$content) {
  6537. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6538. }
  6539. } elseif ($content) {
  6540. $content = filterContent($content);
  6541. } else {
  6542. $content = getProp($anime, 'content');
  6543. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6544. $need_generate_content = true;
  6545. }
  6546. }
  6547. // 美术风格
  6548. $input_art_style = getProp($data, 'art_style');
  6549. if (!$input_art_style) {
  6550. $mappedArtStyle = getProp($anime, 'art_style');
  6551. }else {
  6552. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6553. }
  6554. // 判断是否需要生成原文内容
  6555. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6556. // 如果需要生成原文内容,添加额外的要求
  6557. $content_generation_requirement = $need_generate_content
  6558. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6559. : "";
  6560. // 美术风格
  6561. if (!$mappedArtStyle) {
  6562. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6563. }else {
  6564. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6565. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6566. }else {
  6567. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6568. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6569. }
  6570. }
  6571. // 构建主体、场景和道具提示词
  6572. $extra_role_prompt = "\n";
  6573. $extra_scene_prompt = "\n";
  6574. $extra_prop_prompt = "\n";
  6575. $ref_products = []; // 参考资产
  6576. if ($extra_products) {
  6577. foreach($extra_products as $item) {
  6578. $product = getProp($item, 'product');
  6579. $product_name = getProp($item, 'product_name');
  6580. if ($product_name == '旁白') continue;
  6581. $ref_products[$product_name] = $item;
  6582. $pic_prompt = getProp($item, 'pic_prompt');
  6583. if ((int)$product === 1) {
  6584. // 拼接角色信息
  6585. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6586. } elseif ((int)$product === 2) {
  6587. // 拼接场景信息
  6588. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6589. } elseif ((int)$product === 3) {
  6590. // 拼接道具信息
  6591. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6592. }
  6593. }
  6594. // 优化提示词,融入剧本
  6595. if (!empty(trim($extra_role_prompt))) {
  6596. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6597. }
  6598. if (!empty(trim($extra_scene_prompt))) {
  6599. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6600. }
  6601. if (!empty(trim($extra_prop_prompt))) {
  6602. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6603. }
  6604. }
  6605. if ($anime_script_id && $is_single) {
  6606. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6607. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6608. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6609. }else {
  6610. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6611. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6612. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6613. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6614. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6615. {$extra_role_prompt}";
  6616. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6617. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6618. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6619. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6620. {$extra_scene_prompt}";
  6621. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6622. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6623. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6624. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6625. {$extra_prop_prompt}";
  6626. }
  6627. $systemPrompt = $is_single
  6628. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6629. 强制要求:
  6630. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6631. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6632. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6633. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6634. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6635. 普通要求:
  6636. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6637. $role_demo
  6638. $scene_demo
  6639. $prop_demo
  6640. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6641. 5.1片段分割逻辑(优先级从高到低):
  6642. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6643. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6644. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6645. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6646. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6647. - 片段数量格式为: 片段数量:8
  6648. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6649. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6650. 5.3分镜结构:每个分镜包含以下字段:
  6651. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6652. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6653. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6654. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6655. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6656. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6657. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6658. - 运镜:场景+画面描述+运镜
  6659. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  6660. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  6661. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6662. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6663. 6.{$mappedArtStyle_prompt}\n\n
  6664. 示例如下:\n
  6665. ###剧本名:西昆仑
  6666. ###故事梗概
  6667. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6668. ###剧本亮点
  6669. 亮点1:绝境奇药,生死一线
  6670. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6671. 亮点2:结拜兄妹,化解尴尬
  6672. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6673. 亮点3:纤发夺命,情愫暗涌
  6674. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6675. ###人物关系
  6676. 阿雪与梁萧之间存在兄妹之情。
  6677. ###核心矛盾
  6678. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6679. ###主体列表
  6680. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6681. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6682. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6683. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6684. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6685. 全景,正面拍摄,青年女性,亚洲人。
  6686. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6687. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6688. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6689. ###美术风格
  6690. 基础画风风格词:厚涂古风
  6691. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6692. ###场景列表
  6693. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6694. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6695. 无人物。}
  6696. ###分段剧本
  6697. 片段数量:8
  6698. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6699. ##片段1
  6700. 时长:12s
  6701. 分镜1
  6702. 出场角色:刀疤脸
  6703. 场景:边境小镇街道
  6704. 出场道具:酒杯-高脚杯
  6705. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6706. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6707. 配音台词:
  6708. 背景音效:
  6709. 分镜2
  6710. 出场角色:刀疤脸
  6711. 场景:悦来酒馆
  6712. 出场道具:酒杯-高脚杯
  6713. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6714. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6715. 配音台词:
  6716. 背景音效:
  6717. 分镜3
  6718. 出场角色:刀疤脸
  6719. 场景:悦来酒馆
  6720. 出场道具:酒杯-高脚杯
  6721. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6722. 运镜:从中景推向令牌特写。
  6723. 配音台词:
  6724. 背景音效:
  6725. 分镜4
  6726. 出场角色:刀疤脸
  6727. 场景:悦来酒馆
  6728. 出场道具:酒杯-高脚杯
  6729. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6730. 运镜:极速推向酒水溅起的瞬间。
  6731. 配音台词:
  6732. 背景音效:
  6733. 分镜5
  6734. 出场角色:刀疤脸
  6735. 场景:悦来酒馆
  6736. 出场道具:酒杯-高脚杯
  6737. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6738. 运镜:固定机位,利用倾斜构图制造压迫感。
  6739. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6740. 背景音效:
  6741. \n\n"
  6742. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6743. 强制要求:\n
  6744. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6745. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6746. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6747. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6748. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6749. 普通要求:\n
  6750. 1.剧本名(必须生成)必须与文档内容高度相关
  6751. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6752. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6753. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6754. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6755. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6756. {$extra_role_prompt}
  6757. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6758. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6759. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6760. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6761. {$extra_scene_prompt}
  6762. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6763. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6764. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6765. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6766. {$extra_prop_prompt}
  6767. 5.{$mappedArtStyle_prompt}\n\n
  6768. 示例如下:\n
  6769. ###剧本名:西昆仑
  6770. ###故事梗概
  6771. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6772. ###剧本亮点
  6773. 亮点1:绝境奇药,生死一线
  6774. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6775. 亮点2:结拜兄妹,化解尴尬
  6776. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6777. 亮点3:纤发夺命,情愫暗涌
  6778. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6779. ###人物关系
  6780. 阿雪与梁萧之间存在兄妹之情。
  6781. ###核心矛盾
  6782. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6783. ###主体列表
  6784. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6785. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6786. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6787. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6788. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6789. 全景,正面拍摄,青年女性,亚洲人。
  6790. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6791. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6792. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6793. ###美术风格
  6794. 基础画风风格词:厚涂古风
  6795. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6796. ###场景列表
  6797. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6798. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6799. 无人物。}
  6800. ###道具列表
  6801. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  6802. // 构建消息
  6803. $messages = [
  6804. [
  6805. 'role' => 'system',
  6806. 'content' => $systemPrompt
  6807. ],
  6808. [
  6809. 'role' => 'user',
  6810. 'content' => "以下是文档内容:
  6811. {$content}
  6812. 用户问题:
  6813. {$question}"
  6814. ]
  6815. ];
  6816. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6817. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6818. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6819. if ($model === 'deepseek-chat') {
  6820. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6821. $model = 'deepseek-v4-flash';
  6822. $thinkingMode = 'disabled';
  6823. } elseif ($model === 'deepseek-reasoner') {
  6824. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6825. $model = 'deepseek-v4-flash';
  6826. $thinkingMode = 'enabled';
  6827. }
  6828. $post_data = [
  6829. 'model' => $model,
  6830. 'messages' => $messages,
  6831. // 'max_tokens' => 8192,
  6832. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  6833. 'frequency_penalty' => 0,
  6834. 'presence_penalty' => 0,
  6835. 'response_format' => ['type' => 'text'],
  6836. 'thinking' => ['type'=>$thinkingMode],
  6837. 'stream' => true // 启用流式输出
  6838. ];
  6839. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6840. // 根据模型类型选择调用方法
  6841. $fullContent = '';
  6842. $fullReasoningContent = '';
  6843. $usage = [];
  6844. try {
  6845. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6846. // DeepSeek 官方模型使用 DeepSeek API
  6847. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6848. } else if (in_array($model, $this->gpt_text_models)) {
  6849. // GPT-5.4 模型使用 TokenRouter API
  6850. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6851. } else if (in_array($model, $this->gemini_text_models)) {
  6852. // Gemini 模型使用 Gemini API
  6853. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6854. } else {
  6855. // 其他模型使用火山引擎API
  6856. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6857. }
  6858. // 验证返回值类型
  6859. if (!is_iterable($streamGenerator)) {
  6860. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6861. dLog('deepseek')->error('addChat流式生成器无效', [
  6862. 'generator_type' => $errorType,
  6863. 'model' => $model,
  6864. 'anime_id' => $anime_id
  6865. ]);
  6866. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  6867. 'type' => $errorType,
  6868. 'model' => $model
  6869. ]);
  6870. yield [
  6871. 'type' => 'error',
  6872. 'script' => [],
  6873. 'episode' => [],
  6874. 'answer' => '',
  6875. 'reasoning' => '',
  6876. 'usage' => [],
  6877. 'error' => '接口返回数据异常,请重新请求'
  6878. ];
  6879. return;
  6880. }
  6881. // 处理流式输出
  6882. foreach ($streamGenerator as $chunk) {
  6883. if (isset($chunk['type'])) {
  6884. if ($chunk['type'] === 'done') {
  6885. // 最终结果
  6886. $fullContent = $chunk['full_content'];
  6887. $fullReasoningContent = $chunk['full_reasoning'];
  6888. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6889. } else {
  6890. // 逐块yield数据
  6891. yield $chunk;
  6892. }
  6893. }
  6894. }
  6895. } catch (\Exception $e) {
  6896. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  6897. 'model' => $model,
  6898. 'anime_id' => $anime_id,
  6899. 'trace' => $e->getTraceAsString()
  6900. ]);
  6901. logDB('deepseek', 'error', 'addChat流式处理失败', [
  6902. 'error' => $e->getMessage(),
  6903. 'model' => $model
  6904. ]);
  6905. yield [
  6906. 'type' => 'error',
  6907. 'script' => [],
  6908. 'episode' => [],
  6909. 'answer' => '',
  6910. 'reasoning' => '',
  6911. 'usage' => [],
  6912. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6913. ];
  6914. return;
  6915. }
  6916. dLog('deepseek')->info('完整内容: '.$fullContent);
  6917. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6918. // 处理完整内容并返回最终结果
  6919. $script_arr = [];
  6920. if ($fullContent) {
  6921. $script_arr = handleScriptContentForAce($fullContent);
  6922. dLog('deepseek')->info('解析内容', $script_arr);
  6923. logDB('deepseek', 'info', '解析内容', $script_arr);
  6924. }
  6925. if (empty($script_arr['roles'])) {
  6926. // 未生成剧本相关内容,保存对话记录并返回提示
  6927. dLog('deepseek')->info('未生成剧本相关的内容');
  6928. try {
  6929. DB::beginTransaction();
  6930. $now = date('Y-m-d H:i:s');
  6931. // 保存对话记录
  6932. $records = [
  6933. [
  6934. 'uid' => $uid,
  6935. 'anime_id' => $anime_id,
  6936. 'sequence' => 0,
  6937. 'role' => 'user',
  6938. 'content' => $prompt,
  6939. 'created_at' => $now,
  6940. 'updated_at' => $now
  6941. ],
  6942. [
  6943. 'uid' => $uid,
  6944. 'anime_id' => $anime_id,
  6945. 'sequence' => 0,
  6946. 'role' => 'assistant',
  6947. // 'content' => $fullContent,
  6948. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  6949. 'created_at' => $now,
  6950. 'updated_at' => $now
  6951. ]
  6952. ];
  6953. DB::table('mp_anime_records')->insert($records);
  6954. DB::commit();
  6955. } catch (\Exception $e) {
  6956. DB::rollBack();
  6957. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6958. }
  6959. yield [
  6960. 'type' => 'done',
  6961. 'script' => [],
  6962. 'episode' => [],
  6963. 'answer' => $fullContent,
  6964. 'reasoning' => $fullReasoningContent,
  6965. 'usage' => $usage,
  6966. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6967. ];
  6968. return;
  6969. }
  6970. // 如果需要生成原文内容,从script_arr中提取
  6971. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6972. $content = $script_arr['content'];
  6973. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  6974. if (!$content) {
  6975. yield [
  6976. 'type' => 'done',
  6977. 'script' => [],
  6978. 'episode' => [],
  6979. 'answer' => $fullContent,
  6980. 'reasoning' => $fullReasoningContent,
  6981. 'usage' => $usage,
  6982. 'error' => '未生成剧本内容,请调整提示词再试'
  6983. ];
  6984. return;
  6985. }
  6986. }
  6987. // 替换美术风格
  6988. if ($mappedArtStyle !== '') {
  6989. $script_arr['art_style'] = $mappedArtStyle;
  6990. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6991. }
  6992. // 新建动漫
  6993. if ($user_anime_name == '新剧本策划') {
  6994. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6995. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6996. // if (!$anime_name) {
  6997. // // 未识别到剧本名,保存对话记录并返回提示
  6998. // dLog('deepseek')->info('未能识别到剧本名称');
  6999. // try {
  7000. // DB::beginTransaction();
  7001. // $now = date('Y-m-d H:i:s');
  7002. // // 保存对话记录
  7003. // $records = [
  7004. // [
  7005. // 'uid' => $uid,
  7006. // 'anime_id' => $anime_id,
  7007. // 'sequence' => 0,
  7008. // 'role' => 'user',
  7009. // 'content' => $prompt,
  7010. // 'created_at' => $now,
  7011. // 'updated_at' => $now
  7012. // ],
  7013. // [
  7014. // 'uid' => $uid,
  7015. // 'anime_id' => $anime_id,
  7016. // 'sequence' => 0,
  7017. // 'role' => 'assistant',
  7018. // 'content' => '未能生成剧本名称,请重试',
  7019. // 'created_at' => $now,
  7020. // 'updated_at' => $now
  7021. // ]
  7022. // ];
  7023. // DB::table('mp_anime_records')->insert($records);
  7024. // DB::commit();
  7025. // } catch (\Exception $e) {
  7026. // DB::rollBack();
  7027. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7028. // }
  7029. // yield [
  7030. // 'type' => 'done',
  7031. // 'script' => [],
  7032. // 'episode' => [],
  7033. // 'answer' => $fullContent,
  7034. // 'reasoning' => $fullReasoningContent,
  7035. // 'usage' => $usage,
  7036. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  7037. // ];
  7038. // return;
  7039. // }
  7040. // 确认对话名称唯一性
  7041. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  7042. $anime_name = $anime_name . '_' . date('YmdHis');
  7043. }
  7044. }else {
  7045. $anime_name = $user_anime_name;
  7046. }
  7047. $table_data = [
  7048. 'user_id' => $uid,
  7049. 'anime_name' => $anime_name,
  7050. 'model' => $model,
  7051. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  7052. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  7053. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  7054. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  7055. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  7056. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  7057. 'art_style_type' => $input_art_style,
  7058. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  7059. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  7060. 'status' => '解析完成',
  7061. 'content' => $content,
  7062. 'is_multi' => $is_multi,
  7063. 'ace_mode' => $ace_mode,
  7064. 'generate_status' => '待执行',
  7065. 'updated_at' => date('Y-m-d H:i:s')
  7066. ];
  7067. if ($table_data['content']) {
  7068. $chapters = splitContent($table_data['content']);
  7069. $chapter_count = count($chapters);
  7070. if ($chapter_count > 0) {
  7071. $table_data['start_episode_sequence'] = 1;
  7072. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  7073. }
  7074. }
  7075. if ($extra_products) {
  7076. $table_data['extra_products'] = json_encode($extra_products, 256);
  7077. }
  7078. // 如果有剧本ID则进行绑定
  7079. if ($script_id) {
  7080. $table_data['script_id'] = $script_id;
  7081. }
  7082. $single_episode = [];
  7083. try {
  7084. DB::beginTransaction();
  7085. $now = date('Y-m-d H:i:s');
  7086. // 更新动漫大纲
  7087. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7088. if (!$boolen) {
  7089. dLog('deepseek')->info('动漫保存失败', $table_data);
  7090. Utils::throwError('20003:动漫保存失败');
  7091. }
  7092. // 保存对话记录
  7093. $records = [
  7094. [
  7095. 'uid' => $uid,
  7096. 'anime_id' => $anime_id,
  7097. 'sequence' => 0,
  7098. 'role' => 'user',
  7099. 'content' => $prompt,
  7100. 'created_at' => date('Y-m-d H:i:s'),
  7101. 'updated_at' => date('Y-m-d H:i:s')
  7102. ],
  7103. [
  7104. 'uid' => $uid,
  7105. 'anime_id' => $anime_id,
  7106. 'sequence' => 0,
  7107. 'role' => 'assistant',
  7108. 'content' => $fullContent,
  7109. 'created_at' => date('Y-m-d H:i:s'),
  7110. 'updated_at' => date('Y-m-d H:i:s')
  7111. ]
  7112. ];
  7113. // 保存对话记录
  7114. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7115. if (!$boolen3) {
  7116. Utils::throwError('20003:对话记录保存失败');
  7117. }
  7118. if ($is_single) {
  7119. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7120. if (empty($episode_arr['acts'])) {
  7121. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7122. }
  7123. $saveResult = $this->saveEpisodeVersionData(
  7124. $anime_id,
  7125. 1,
  7126. $episode_arr,
  7127. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7128. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7129. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7130. null,
  7131. null,
  7132. false,
  7133. $content,
  7134. $now,
  7135. $ref_products
  7136. );
  7137. $single_episode = $saveResult['episode'];
  7138. $episode_id = $saveResult['episode_id'];
  7139. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7140. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7141. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7142. 'props' => json_encode($saveResult['merged_props'], 256),
  7143. 'updated_at' => $now
  7144. ]);
  7145. if ($boolen5 === false) {
  7146. Utils::throwError('20003:单剧集主表资源同步失败');
  7147. }
  7148. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7149. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7150. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7151. $episode_record_content = '确认分镜大纲';
  7152. if ($content !== '') {
  7153. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7154. }
  7155. $episode_records = [
  7156. [
  7157. 'uid' => $uid,
  7158. 'anime_id' => $anime_id,
  7159. 'role' => 'user',
  7160. 'content' => $episode_record_content,
  7161. 'sequence' => 1,
  7162. 'episode_id' => $episode_id,
  7163. 'created_at' => $now,
  7164. 'updated_at' => $now
  7165. ],
  7166. [
  7167. 'uid' => $uid,
  7168. 'anime_id' => $anime_id,
  7169. 'role' => 'assistant',
  7170. 'content' => $fullContent,
  7171. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7172. 'sequence' => 1,
  7173. 'episode_id' => $episode_id,
  7174. 'created_at' => $now,
  7175. 'updated_at' => $now
  7176. ]
  7177. ];
  7178. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7179. if (!$boolen4) {
  7180. Utils::throwError('20003:单剧集分镜记录保存失败');
  7181. }
  7182. }
  7183. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7184. if ($is_single && !empty($single_episode)) {
  7185. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7186. 'anime_id' => $anime_id,
  7187. 'episode_id' => $episode_id ?? 0,
  7188. ]);
  7189. }
  7190. }catch (\Exception $e) {
  7191. DB::rollBack();
  7192. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7193. yield [
  7194. 'type' => 'done',
  7195. 'answer' => $fullContent,
  7196. 'reasoning' => $fullReasoningContent,
  7197. 'usage' => $usage,
  7198. 'error' => $e->getMessage(),
  7199. ];
  7200. return;
  7201. }
  7202. DB::commit();
  7203. dLog('deepseek')->info('保存完毕');
  7204. if ($is_single && !empty($single_episode)) {
  7205. // $this->batchSetGlobalRoleImg([
  7206. // 'anime_id' => $anime_id,
  7207. // ]);
  7208. // $this->batchSetGlobalSceneImg([
  7209. // 'anime_id' => $anime_id,
  7210. // ]);
  7211. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7212. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7213. }
  7214. $table_data['anime_id'] = $anime_id;
  7215. $table_data['roles'] = json_decode($table_data['roles'], true);
  7216. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7217. // $table_data['episodes'] = $script_arr['episodes'];
  7218. unset($table_data['created_at']);
  7219. unset($table_data['updated_at']);
  7220. unset($table_data['status']);
  7221. dLog('deepseek')->info('开始返回');
  7222. yield [
  7223. 'type' => 'done',
  7224. 'script' => $table_data,
  7225. 'episode' => $single_episode,
  7226. 'answer' => $fullContent,
  7227. 'reasoning' => $fullReasoningContent,
  7228. 'usage' => $usage
  7229. ];
  7230. }
  7231. public function reGenerateAnimeForAce($data) {
  7232. $uid = Site::getUid();
  7233. $file = getProp($data, 'file');
  7234. $content = getProp($data, 'content', '');
  7235. $bid = getProp($data, 'bid', 0);
  7236. $script_id = getProp($data, 'script_id', 0);
  7237. $anime_id = getProp($data, 'anime_id');
  7238. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7239. if (!$anime) {
  7240. Utils::throwError('20003:该对话不存在');
  7241. }
  7242. $is_multi = getProp($anime, 'is_multi', 1);
  7243. $is_single = (int)$is_multi !== 1;
  7244. // 积分余额预检(仅单剧集模式收费)
  7245. if ($is_single) {
  7246. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  7247. }
  7248. $extra_products = getProp($data, 'products', []);
  7249. if (!$extra_products) {
  7250. $extra_products = getProp($anime, 'extra_products');
  7251. if ($extra_products) {
  7252. $extra_products = json_decode($extra_products, true);
  7253. }else {
  7254. $extra_products = [];
  7255. }
  7256. }else {
  7257. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7258. }
  7259. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7260. $anime_script_id = getProp($anime, 'script_id');
  7261. if ($anime_script_id && $is_single) {
  7262. $cpid = Site::getCpid();
  7263. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7264. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7265. ->where('mapping.script_id', $anime_script_id)
  7266. ->where('product.cpid', $cpid)
  7267. ->where('product.is_deleted', 0);
  7268. $mappings = $script_products_mappings->select(
  7269. 'mapping.product_id',
  7270. 'mapping.episode_number',
  7271. 'product.product_name',
  7272. 'product.type',
  7273. 'product.product',
  7274. 'product.pic_prompt',
  7275. 'product.url',
  7276. 'product.pic_task_id',
  7277. 'product.pic_task_status',
  7278. 'product.three_view_image_url'
  7279. )
  7280. ->get();
  7281. // 按 product_id 分组,合并 episode_number
  7282. $productMap = [];
  7283. foreach ($mappings as $item) {
  7284. $product_id = $item->product_id;
  7285. $product_name = $item->product_name;
  7286. // 处理product_name两边的符号
  7287. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7288. if (!isset($productMap[$product_id])) {
  7289. $productMap[$product_id] = [
  7290. 'product_id' => $product_id,
  7291. 'product_name' => $product_name,
  7292. 'type' => (int)$item->type,
  7293. 'product' => (int)$item->product,
  7294. 'pic_prompt' => $item->pic_prompt,
  7295. 'url' => $item->url,
  7296. 'pic_task_id' => $item->pic_task_id,
  7297. 'pic_task_status' => $item->pic_task_status,
  7298. 'episode_numbers' => [],
  7299. ];
  7300. }
  7301. // 添加 episode_number(去重)
  7302. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7303. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7304. }
  7305. }
  7306. // 将查询到的剧本资产合并到extra_products中
  7307. // 先构建extra_products的索引(以product_id为key,用于去重)
  7308. $extraProductsMap = [];
  7309. foreach ($extra_products as $item) {
  7310. $key = getProp($item, 'product_id');
  7311. if ($key) {
  7312. $extraProductsMap[$key] = $item;
  7313. }
  7314. }
  7315. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7316. foreach ($productMap as $product) {
  7317. $product_id = $product['product_id'];
  7318. // 如果不存在则添加(不带episode_number信息)
  7319. if (!isset($extraProductsMap[$product_id])) {
  7320. $extraProductsMap[$product_id] = [
  7321. 'product_id' => $product['product_id'],
  7322. 'product_name' => $product['product_name'],
  7323. 'type' => $product['type'],
  7324. 'product' => $product['product'],
  7325. 'pic_prompt' => $product['pic_prompt'],
  7326. 'url' => $product['url'],
  7327. 'pic_task_id' => $product['pic_task_id'],
  7328. 'pic_task_status' => $product['pic_task_status'],
  7329. ];
  7330. }
  7331. }
  7332. // 重新赋值给extra_products
  7333. $extra_products = array_values($extraProductsMap);
  7334. }
  7335. $user_anime_name = getProp($anime, 'anime_name');
  7336. $prompt = getProp($data, 'prompt');
  7337. // 处理提示词
  7338. if ($prompt && $extra_products) {
  7339. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7340. foreach($extra_products as $item) {
  7341. $product_name = getProp($item, 'product_name');
  7342. if ($product_name) {
  7343. // 替换 {product_name} 为 product_name
  7344. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7345. }
  7346. }
  7347. }
  7348. // 处理文本模型
  7349. $model = getProp($data, 'model');
  7350. if (!$model) {
  7351. // 用户没有输入,从anime表获取
  7352. $model = getProp($anime, 'model');
  7353. if (!$model) {
  7354. // anime表也没有,使用默认值
  7355. $model = 'deepseek-v4-pro';
  7356. }
  7357. }
  7358. // 验证模型是否在可用模型表中
  7359. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7360. $model = 'deepseek-v4-pro';
  7361. }
  7362. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  7363. if ($is_single) {
  7364. $episode_exists = DB::table('mp_anime_episodes')
  7365. ->where('anime_id', $anime_id)
  7366. ->where('sequence', 1)
  7367. ->exists();
  7368. if ($episode_exists) {
  7369. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  7370. }
  7371. }
  7372. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7373. if ($prompt) {
  7374. $question .= "本次修改要求如下:\n{$prompt}";
  7375. }
  7376. // 提取文件内容
  7377. if ($file) {
  7378. $content = $this->extractFileContent($file);
  7379. if (!$content) {
  7380. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7381. }
  7382. } elseif ($script_id) {
  7383. $content = $this->getContentByScriptId($script_id);
  7384. if (!$content) {
  7385. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7386. }
  7387. } elseif ($bid) {
  7388. $content = $this->getContentByBid($bid);
  7389. if (!$content) {
  7390. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7391. }
  7392. } elseif ($content) {
  7393. $content = filterContent($content);
  7394. }else {
  7395. $content = filterContent(getProp($anime, 'content'));
  7396. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7397. $need_generate_content = true;
  7398. }
  7399. }
  7400. // 判断是否需要生成原文内容
  7401. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7402. // 如果需要生成原文内容,添加额外的要求
  7403. $content_generation_requirement = $need_generate_content
  7404. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7405. : "";
  7406. // 美术风格
  7407. $input_art_style = getProp($data, 'art_style');
  7408. if (!$input_art_style) {
  7409. $mappedArtStyle = getProp($anime, 'art_style');
  7410. }else {
  7411. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7412. }
  7413. if (!$mappedArtStyle) {
  7414. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7415. }else {
  7416. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7417. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7418. }else {
  7419. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7420. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7421. }
  7422. }
  7423. // 构建主体、场景和道具提示词
  7424. $extra_role_prompt = "\n";
  7425. $extra_scene_prompt = "\n";
  7426. $extra_prop_prompt = "\n";
  7427. $ref_products = []; // 参考资产
  7428. if ($extra_products) {
  7429. foreach($extra_products as $item) {
  7430. $product = getProp($item, 'product');
  7431. $product_name = getProp($item, 'product_name');
  7432. if ($product_name == '旁白') continue;
  7433. $ref_products[$product_name] = $item;
  7434. $pic_prompt = getProp($item, 'pic_prompt');
  7435. if ((int)$product === 1) {
  7436. // 拼接角色信息
  7437. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7438. } elseif ((int)$product === 2) {
  7439. // 拼接场景信息
  7440. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7441. } elseif ((int)$product === 3) {
  7442. // 拼接道具信息
  7443. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7444. }
  7445. }
  7446. // 优化提示词,融入剧本
  7447. if (!empty(trim($extra_role_prompt))) {
  7448. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7449. }
  7450. if (!empty(trim($extra_scene_prompt))) {
  7451. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7452. }
  7453. if (!empty(trim($extra_prop_prompt))) {
  7454. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7455. }
  7456. }
  7457. if ($anime_script_id && $is_single) {
  7458. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7459. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7460. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7461. }else {
  7462. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7463. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7464. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7465. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7466. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7467. {$extra_role_prompt}";
  7468. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7469. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7470. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7471. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7472. {$extra_scene_prompt}";
  7473. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7474. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7475. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7476. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7477. {$extra_prop_prompt}";
  7478. }
  7479. $system_message = ['role'=>'system', 'content'=>$is_single
  7480. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7481. 强制要求:
  7482. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7483. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7484. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7485. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7486. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7487. 普通要求:
  7488. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7489. $role_demo
  7490. $scene_demo
  7491. $prop_demo
  7492. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7493. 5.1片段分割逻辑(优先级从高到低):
  7494. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7495. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7496. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7497. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7498. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7499. - 片段数量格式为: 片段数量:8
  7500. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7501. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7502. 5.3分镜结构:每个分镜包含以下字段:
  7503. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7504. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7505. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7506. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7507. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7508. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7509. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7510. - 运镜:场景+画面描述+运镜
  7511. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7512. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7513. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7514. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7515. 6.{$mappedArtStyle_prompt}\n\n
  7516. 示例如下:\n
  7517. ###剧本名:西昆仑
  7518. ###故事梗概
  7519. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7520. ###剧本亮点
  7521. 亮点1:绝境奇药,生死一线
  7522. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7523. 亮点2:结拜兄妹,化解尴尬
  7524. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7525. 亮点3:纤发夺命,情愫暗涌
  7526. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7527. ###人物关系
  7528. 阿雪与梁萧之间存在兄妹之情。
  7529. ###核心矛盾
  7530. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7531. ###主体列表
  7532. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7533. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7534. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7535. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7536. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7537. 全景,正面拍摄,青年女性,亚洲人。
  7538. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7539. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7540. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7541. ###美术风格
  7542. 基础画风风格词:厚涂古风
  7543. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7544. ###场景列表
  7545. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7546. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7547. 无人物。}
  7548. ###分段剧本
  7549. 片段数量:8
  7550. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7551. ##片段1
  7552. 时长:12s
  7553. 分镜1
  7554. 出场角色:刀疤脸
  7555. 场景:边境小镇街道
  7556. 出场道具:酒杯-高脚杯
  7557. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7558. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7559. 配音台词:
  7560. 背景音效:
  7561. 分镜2
  7562. 出场角色:刀疤脸
  7563. 场景:悦来酒馆
  7564. 出场道具:酒杯-高脚杯
  7565. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7566. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7567. 配音台词:
  7568. 背景音效:
  7569. 分镜3
  7570. 出场角色:刀疤脸
  7571. 场景:悦来酒馆
  7572. 出场道具:酒杯-高脚杯
  7573. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7574. 运镜:从中景推向令牌特写。
  7575. 配音台词:
  7576. 背景音效:
  7577. 分镜4
  7578. 出场角色:刀疤脸
  7579. 场景:悦来酒馆
  7580. 出场道具:酒杯-高脚杯
  7581. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7582. 运镜:极速推向酒水溅起的瞬间。
  7583. 配音台词:
  7584. 背景音效:
  7585. 分镜5
  7586. 出场角色:刀疤脸
  7587. 场景:悦来酒馆
  7588. 出场道具:酒杯-高脚杯
  7589. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7590. 运镜:固定机位,利用倾斜构图制造压迫感。
  7591. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7592. 背景音效:
  7593. \n\n"
  7594. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7595. 强制要求:\n
  7596. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7597. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7598. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7599. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7600. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7601. 普通要求:\n
  7602. 1.剧本名(必须生成)必须与文档内容高度相关
  7603. $role_demo
  7604. $scene_demo
  7605. $prop_demo
  7606. 5.{$mappedArtStyle_prompt}\n\n
  7607. 示例如下:\n
  7608. ###剧本名:西昆仑
  7609. ###故事梗概
  7610. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7611. ###剧本亮点
  7612. 亮点1:绝境奇药,生死一线
  7613. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7614. 亮点2:结拜兄妹,化解尴尬
  7615. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7616. 亮点3:纤发夺命,情愫暗涌
  7617. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7618. ###人物关系
  7619. 阿雪与梁萧之间存在兄妹之情。
  7620. ###核心矛盾
  7621. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7622. ###主体列表
  7623. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7624. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7625. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7626. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7627. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7628. 全景,正面拍摄,青年女性,亚洲人。
  7629. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7630. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7631. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7632. ###美术风格
  7633. 基础画风风格词:厚涂古风
  7634. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7635. ###场景列表
  7636. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7637. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7638. 无人物。}
  7639. ###道具列表
  7640. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  7641. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  7642. $episode_count = $this->extractEpisodeNumber($prompt);
  7643. if ((int)getProp($anime, 'is_multi') !== 1) {
  7644. yield [
  7645. 'type' => 'done',
  7646. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  7647. 'reasoning' => '',
  7648. 'usage' => []
  7649. ];
  7650. return;
  7651. }
  7652. if ($episode_count) {
  7653. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  7654. $system_message = [
  7655. 'role' => 'system',
  7656. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7657. 强制要求:\n
  7658. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7659. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7660. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7661. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7662. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7663. 普通要求:\n
  7664. 1.<故事梗概>控制在200-300字左右
  7665. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7666. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7667. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7668. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7669. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7670. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7671. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7672. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7673. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7674. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  7675. 示例如下:\n
  7676. ###剧本名:西昆仑
  7677. ###故事梗概
  7678. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7679. ###剧本亮点
  7680. 亮点1:绝境奇药,生死一线
  7681. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7682. 亮点2:结拜兄妹,化解尴尬
  7683. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7684. 亮点3:纤发夺命,情愫暗涌
  7685. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7686. ###人物关系
  7687. 阿雪与梁萧之间存在兄妹之情。
  7688. ###核心矛盾
  7689. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7690. ###主体列表
  7691. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7692. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7693. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7694. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7695. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7696. 全景,正面拍摄,青年女性,亚洲人。
  7697. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7698. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7699. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7700. ###美术风格
  7701. 基础画风风格词:厚涂古风
  7702. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7703. ###场景列表
  7704. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7705. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7706. 无人物。}
  7707. ###分集详细内容
  7708. ##第1章 重生
  7709. 我重生了。
  7710. 源于一个男人偏执的暗恋。
  7711. ##第2章 相救
  7712. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  7713. 我眼睛扫向站在锅炉后的卞大伟。"
  7714. ];
  7715. // 构建消息
  7716. $messages = [
  7717. $system_message,
  7718. [
  7719. 'role' => 'user',
  7720. 'content' => "以下是文档内容:
  7721. {$content}
  7722. 用户问题:
  7723. {$question}"
  7724. ]
  7725. ];
  7726. }else {
  7727. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  7728. // 构建消息
  7729. $messages = [
  7730. $system_message,
  7731. [
  7732. 'role' => 'user',
  7733. 'content' => "以下是文档内容:
  7734. {$content}
  7735. 用户问题:
  7736. {$question}"
  7737. ]
  7738. ];
  7739. }else {
  7740. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  7741. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  7742. return (array)$value;
  7743. })->toArray();
  7744. array_unshift($messages, $system_message);
  7745. $messages[] = [
  7746. 'role' => 'user',
  7747. 'content' => $prompt
  7748. ];
  7749. }
  7750. }
  7751. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7752. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7753. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7754. if ($model === 'deepseek-chat') {
  7755. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7756. $model = 'deepseek-v4-flash';
  7757. $thinkingMode = 'disabled';
  7758. } elseif ($model === 'deepseek-reasoner') {
  7759. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7760. $model = 'deepseek-v4-flash';
  7761. $thinkingMode = 'enabled';
  7762. }
  7763. $post_data = [
  7764. 'model' => $model,
  7765. 'messages' => $messages,
  7766. // 'max_tokens' => 8192,
  7767. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7768. 'frequency_penalty' => 0,
  7769. 'presence_penalty' => 0,
  7770. 'response_format' => ['type' => 'text'],
  7771. 'thinking' => ['type' => $thinkingMode],
  7772. 'stream' => true // 启用流式输出
  7773. ];
  7774. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7775. // 根据模型类型选择调用方法
  7776. $fullContent = '';
  7777. $fullReasoningContent = '';
  7778. $usage = [];
  7779. // dd($post_data);
  7780. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  7781. try {
  7782. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7783. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7784. } else if (in_array($model, $this->gpt_text_models)) {
  7785. // GPT-5.4 模型使用 TokenRouter API
  7786. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7787. } else if (in_array($model, $this->gemini_text_models)) {
  7788. // Gemini 模型使用 Gemini API
  7789. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  7790. } else {
  7791. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7792. }
  7793. // 验证返回值类型
  7794. if (!is_iterable($streamGenerator)) {
  7795. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7796. dLog('deepseek')->error('方法名流式生成器无效', [
  7797. 'generator_type' => $errorType,
  7798. 'model' => $model,
  7799. // 添加其他上下文信息
  7800. ]);
  7801. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  7802. 'type' => $errorType,
  7803. 'model' => $model
  7804. ]);
  7805. yield [
  7806. 'type' => 'error',
  7807. // 根据方法返回相应的空数据结构
  7808. 'answer' => '',
  7809. 'reasoning' => '',
  7810. 'usage' => [],
  7811. 'error' => '接口返回数据异常,请重新请求'
  7812. ];
  7813. return;
  7814. }
  7815. // 处理流式输出
  7816. foreach ($streamGenerator as $chunk) {
  7817. if (isset($chunk['type'])) {
  7818. if ($chunk['type'] === 'done') {
  7819. $fullContent = $chunk['full_content'];
  7820. $fullReasoningContent = $chunk['full_reasoning'];
  7821. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7822. } else {
  7823. yield $chunk;
  7824. }
  7825. }
  7826. }
  7827. } catch (\Exception $e) {
  7828. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  7829. 'model' => $model,
  7830. 'trace' => $e->getTraceAsString()
  7831. ]);
  7832. logDB('deepseek', 'error', '方法名流式处理失败', [
  7833. 'error' => $e->getMessage(),
  7834. 'model' => $model
  7835. ]);
  7836. yield [
  7837. 'type' => 'error',
  7838. // 根据方法返回相应的空数据结构
  7839. 'answer' => '',
  7840. 'reasoning' => '',
  7841. 'usage' => [],
  7842. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7843. ];
  7844. return;
  7845. }
  7846. dLog('deepseek')->info('完整内容: '.$fullContent);
  7847. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7848. // 处理完整内容并返回最终结果
  7849. $script_arr = [];
  7850. if ($fullContent) {
  7851. $script_arr = handleScriptContentForAce($fullContent);
  7852. dLog('deepseek')->info('解析内容', $script_arr);
  7853. logDB('deepseek', 'info', '解析内容', $script_arr);
  7854. }
  7855. if (empty($script_arr['roles'])) {
  7856. // 未生成剧本相关内容,保存对话记录并返回提示
  7857. dLog('deepseek')->info('未生成剧本相关的内容');
  7858. try {
  7859. $now = date('Y-m-d H:i:s');
  7860. // 保存对话记录
  7861. $records = [
  7862. [
  7863. 'uid' => $uid,
  7864. 'anime_id' => $anime_id,
  7865. 'sequence' => 0,
  7866. 'role' => 'user',
  7867. 'content' => $prompt,
  7868. 'created_at' => $now,
  7869. 'updated_at' => $now
  7870. ],
  7871. [
  7872. 'uid' => $uid,
  7873. 'anime_id' => $anime_id,
  7874. 'sequence' => 0,
  7875. 'role' => 'assistant',
  7876. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  7877. 'created_at' => $now,
  7878. 'updated_at' => $now
  7879. ]
  7880. ];
  7881. DB::table('mp_anime_records')->insert($records);
  7882. } catch (\Exception $e) {
  7883. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7884. }
  7885. yield [
  7886. 'type' => 'done',
  7887. 'script' => [],
  7888. 'episode' => [],
  7889. 'answer' => $fullContent,
  7890. 'reasoning' => $fullReasoningContent,
  7891. 'usage' => $usage,
  7892. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  7893. ];
  7894. return;
  7895. }
  7896. // 替换美术风格
  7897. if ($mappedArtStyle !== '') {
  7898. $script_arr['art_style'] = $mappedArtStyle;
  7899. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  7900. }
  7901. if ($user_anime_name != '新剧本策划') {
  7902. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  7903. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  7904. // 确认对话名称唯一性
  7905. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  7906. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  7907. }
  7908. }else {
  7909. $anime_name = $user_anime_name;
  7910. }
  7911. $table_data = [
  7912. 'user_id' => $uid,
  7913. 'model' => $model,
  7914. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  7915. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  7916. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  7917. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  7918. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  7919. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  7920. 'art_style_type' => $input_art_style,
  7921. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  7922. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  7923. 'status' => '解析完成',
  7924. 'generate_status' => '待执行',
  7925. 'updated_at' => date('Y-m-d H:i:s')
  7926. ];
  7927. if ($anime_name) $table_data['anime_name'] = $anime_name;
  7928. // 如果是修改集数,则将content内容更新(会改变原文)
  7929. if (isset($episode_count) && $episode_count > 0) {
  7930. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  7931. $table_data['start_episode_sequence'] = 1;
  7932. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  7933. }else {
  7934. // 如果需要生成原文内容,从script_arr中提取
  7935. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  7936. $table_data['content'] = $script_arr['content'];
  7937. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  7938. if (!$table_data['content']) {
  7939. yield [
  7940. 'type' => 'done',
  7941. 'script' => [],
  7942. 'episode' => [],
  7943. 'answer' => $fullContent,
  7944. 'reasoning' => $fullReasoningContent,
  7945. 'usage' => $usage,
  7946. 'error' => '未生成剧本内容,请调整提示词再试'
  7947. ];
  7948. return;
  7949. }
  7950. }
  7951. if (isset($table_data['content']) && $table_data['content']) {
  7952. $chapters = splitContent($table_data['content']);
  7953. $chapter_count = count($chapters);
  7954. if ($chapter_count > 0) {
  7955. $table_data['start_episode_sequence'] = 1;
  7956. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  7957. }
  7958. }
  7959. }
  7960. if ($extra_products) {
  7961. $table_data['extra_products'] = json_encode($extra_products, 256);
  7962. }
  7963. $single_episode = [];
  7964. try {
  7965. DB::beginTransaction();
  7966. $now = date('Y-m-d H:i:s');
  7967. // 更新动漫大纲
  7968. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7969. if (!$boolen) {
  7970. dLog('deepseek')->info('对话修改失败', $table_data);
  7971. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  7972. Utils::throwError('20003:对话修改失败');
  7973. }
  7974. // 保存对话记录
  7975. $records = [
  7976. [
  7977. 'uid' => $uid,
  7978. 'anime_id' => $anime_id,
  7979. 'sequence' => 0,
  7980. 'role' => 'user',
  7981. 'content' => $prompt,
  7982. 'created_at' => $now,
  7983. 'updated_at' => $now
  7984. ],
  7985. [
  7986. 'uid' => $uid,
  7987. 'anime_id' => $anime_id,
  7988. 'sequence' => 0,
  7989. 'role' => 'assistant',
  7990. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7991. 'content' => $fullContent,
  7992. 'created_at' => $now,
  7993. 'updated_at' => $now
  7994. ]
  7995. ];
  7996. // 保存对话记录
  7997. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7998. if (!$boolen3) {
  7999. Utils::throwError('20003:对话记录保存失败');
  8000. }
  8001. // 单剧集模式:生成并保存剧集信息
  8002. if ($is_single) {
  8003. $anime_name = getProp($anime, 'anime_name', '未命名');
  8004. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8005. if (empty($episode_arr['acts'])) {
  8006. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  8007. }
  8008. $saveResult = $this->saveEpisodeVersionData(
  8009. $anime_id,
  8010. 1,
  8011. $episode_arr,
  8012. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8013. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8014. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  8015. null,
  8016. null,
  8017. false,
  8018. $content,
  8019. $now,
  8020. $ref_products
  8021. );
  8022. $single_episode = $saveResult['episode'];
  8023. $episode_id = $saveResult['episode_id'];
  8024. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  8025. 'roles' => json_encode($saveResult['merged_roles'], 256),
  8026. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  8027. 'props' => json_encode($saveResult['merged_props'], 256),
  8028. 'updated_at' => $now
  8029. ]);
  8030. if ($boolen5 === false) {
  8031. Utils::throwError('20003:单剧集主表资源同步失败');
  8032. }
  8033. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  8034. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  8035. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  8036. $episode_record_content = '确认分镜大纲';
  8037. if ($content !== '') {
  8038. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  8039. }
  8040. $episode_records = [
  8041. [
  8042. 'uid' => $uid,
  8043. 'anime_id' => $anime_id,
  8044. 'role' => 'user',
  8045. 'content' => $episode_record_content,
  8046. 'sequence' => 1,
  8047. 'episode_id' => $episode_id,
  8048. 'created_at' => $now,
  8049. 'updated_at' => $now
  8050. ],
  8051. [
  8052. 'uid' => $uid,
  8053. 'anime_id' => $anime_id,
  8054. 'role' => 'assistant',
  8055. 'content' => $fullContent,
  8056. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8057. 'sequence' => 1,
  8058. 'episode_id' => $episode_id,
  8059. 'created_at' => $now,
  8060. 'updated_at' => $now
  8061. ]
  8062. ];
  8063. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  8064. if (!$boolen4) {
  8065. Utils::throwError('20003:单剧集分镜记录保存失败');
  8066. }
  8067. }
  8068. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8069. if ($is_single && !empty($single_episode)) {
  8070. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8071. 'anime_id' => $anime_id,
  8072. 'episode_id' => $episode_id ?? 0,
  8073. ]);
  8074. }
  8075. }catch (\Exception $e) {
  8076. DB::rollBack();
  8077. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  8078. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  8079. yield [
  8080. 'type' => 'done',
  8081. 'answer' => $fullContent,
  8082. 'reasoning' => $fullReasoningContent,
  8083. 'usage' => $usage,
  8084. 'error' => $e->getMessage(),
  8085. ];
  8086. return;
  8087. }
  8088. DB::commit();
  8089. dLog('deepseek')->info('保存完毕');
  8090. if ($is_single && !empty($single_episode)) {
  8091. // $this->batchSetGlobalRoleImg([
  8092. // 'anime_id' => $anime_id,
  8093. // ]);
  8094. // $this->batchSetGlobalSceneImg([
  8095. // 'anime_id' => $anime_id,
  8096. // ]);
  8097. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8098. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8099. }
  8100. $table_data['anime_id'] = $anime_id;
  8101. $table_data['roles'] = json_decode($table_data['roles'], true);
  8102. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8103. $table_data['props'] = json_decode($table_data['props'], true);
  8104. unset($table_data['updated_at']);
  8105. unset($table_data['status']);
  8106. yield [
  8107. 'type' => 'done',
  8108. 'script' => $table_data,
  8109. 'episode' => $single_episode,
  8110. 'answer' => $fullContent,
  8111. 'reasoning' => $fullReasoningContent,
  8112. 'usage' => $usage
  8113. ];
  8114. }
  8115. public function chatForAce($data) {
  8116. $uid = Site::getUid();
  8117. // 积分余额预检(不足直接报错)
  8118. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  8119. $anime_id = getProp($data, 'anime_id');
  8120. $file = getProp($data, 'file');
  8121. $content = getProp($data, 'content', '');
  8122. $bid = getProp($data, 'bid', 0);
  8123. $script_id = getProp($data, 'script_id', 0);
  8124. $episode_number = getProp($data, 'episode_number', 1);
  8125. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8126. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8127. if (!$anime) Utils::throwError('20003:该对话不存在!');
  8128. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  8129. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  8130. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  8131. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  8132. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  8133. $roles = is_array($roles) ? $roles : [];
  8134. $scenes = is_array($scenes) ? $scenes : [];
  8135. $extra_products = getProp($data, 'products', []);
  8136. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  8137. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  8138. $anime_script_id = getProp($anime, 'script_id');
  8139. if ($anime_script_id) {
  8140. $cpid = Site::getCpid();
  8141. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  8142. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8143. ->where('mapping.script_id', $anime_script_id)
  8144. ->where('product.cpid', $cpid)
  8145. ->where('product.is_deleted', 0);
  8146. // 如果提供了 episode_number,则过滤指定集数
  8147. if ($episode_number !== null && $episode_number !== '') {
  8148. $script_products_mappings->where('mapping.episode_number', $episode_number);
  8149. }
  8150. $mappings = $script_products_mappings->select(
  8151. 'mapping.product_id',
  8152. 'mapping.episode_number',
  8153. 'product.product_name',
  8154. 'product.type',
  8155. 'product.product',
  8156. 'product.pic_prompt',
  8157. 'product.url',
  8158. 'product.pic_task_id',
  8159. 'product.pic_task_status',
  8160. 'product.three_view_image_url'
  8161. )
  8162. ->get();
  8163. // 按 product_id 分组,合并 episode_number
  8164. $productMap = [];
  8165. foreach ($mappings as $item) {
  8166. $product_id = $item->product_id;
  8167. $product_name = $item->product_name;
  8168. // 处理product_name两边的符号
  8169. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8170. if (!isset($productMap[$product_id])) {
  8171. $productMap[$product_id] = [
  8172. 'product_id' => $product_id,
  8173. 'product_name' => $product_name,
  8174. 'type' => (int)$item->type,
  8175. 'product' => (int)$item->product,
  8176. 'pic_prompt' => $item->pic_prompt,
  8177. 'url' => $item->url,
  8178. 'pic_task_id' => $item->pic_task_id,
  8179. 'pic_task_status' => $item->pic_task_status,
  8180. 'episode_numbers' => [],
  8181. ];
  8182. }
  8183. // 添加 episode_number(去重)
  8184. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8185. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8186. }
  8187. }
  8188. // 将查询到的剧本资产合并到extra_products中
  8189. // 先构建extra_products的索引(以product_id+episode_number为key)
  8190. $extraProductsMap = [];
  8191. foreach ($extra_products as $item) {
  8192. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  8193. $extraProductsMap[$key] = $item;
  8194. }
  8195. // 合并剧本资产(去重:product_id+episode_number)
  8196. foreach ($productMap as $product) {
  8197. foreach ($product['episode_numbers'] as $ep_num) {
  8198. $key = $product['product_id'] . '_' . $ep_num;
  8199. // 如果不存在则添加
  8200. if (!isset($extraProductsMap[$key])) {
  8201. $extraProductsMap[$key] = [
  8202. 'product_id' => $product['product_id'],
  8203. 'product_name' => $product['product_name'],
  8204. 'type' => $product['type'],
  8205. 'product' => $product['product'],
  8206. 'pic_prompt' => $product['pic_prompt'],
  8207. 'url' => $product['url'],
  8208. 'pic_task_id' => $product['pic_task_id'],
  8209. 'pic_task_status' => $product['pic_task_status'],
  8210. 'episode_number' => $ep_num,
  8211. ];
  8212. }
  8213. }
  8214. }
  8215. // 重新赋值给extra_products
  8216. $extra_products = array_values($extraProductsMap);
  8217. }
  8218. // 处理提示词
  8219. if ($prompt && $extra_products) {
  8220. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8221. foreach($extra_products as $item) {
  8222. $product_name = getProp($item, 'product_name');
  8223. if ($product_name) {
  8224. // 替换 {product_name} 为 product_name
  8225. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8226. }
  8227. }
  8228. }
  8229. // 获取最后一集序号
  8230. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  8231. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  8232. // 转换主体列表和场景列表的格式
  8233. // 获取参考主体或场景
  8234. if ((int)$episode_number === 1) {
  8235. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  8236. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  8237. }else {
  8238. $prev_episode_number = $episode_number - 1;
  8239. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  8240. }
  8241. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  8242. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  8243. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  8244. // 合并anime_products和extra_products(extra_products优先,去重)
  8245. $anime_products = getProp($anime, 'extra_products');
  8246. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  8247. $ref_products = [];
  8248. foreach($anime_products as $item) {
  8249. $product_name = getProp($item, 'product_name');
  8250. $ref_products[$product_name] = $item;
  8251. }
  8252. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  8253. $extra_roles = []; // 从extra_products中提取的角色
  8254. $extra_scenes = []; // 从extra_products中提取的场景
  8255. $extra_props = []; // 从extra_products中提取的道具
  8256. if ($extra_products && is_array($extra_products)) {
  8257. foreach($extra_products as $item) {
  8258. $product = (int)getProp($item, 'product');
  8259. $product_name = getProp($item, 'product_name');
  8260. if ($product_name == '旁白') continue;
  8261. $pic_prompt = getProp($item, 'pic_prompt');
  8262. $ref_products[$product_name] = $item;
  8263. if ($product === 1) {
  8264. // 角色
  8265. $extra_roles[$product_name] = [
  8266. 'role' => $product_name,
  8267. 'pic_prompt' => $pic_prompt,
  8268. 'url' => getProp($item, 'url', ''),
  8269. ];
  8270. } elseif ($product === 2) {
  8271. // 场景
  8272. $extra_scenes[$product_name] = [
  8273. 'scene' => $product_name,
  8274. 'pic_prompt' => $pic_prompt,
  8275. 'url' => getProp($item, 'url', ''),
  8276. ];
  8277. } elseif ($product === 3) {
  8278. // 道具
  8279. $extra_props[$product_name] = [
  8280. 'prop' => $product_name,
  8281. 'pic_prompt' => $pic_prompt,
  8282. 'url' => getProp($item, 'url', ''),
  8283. ];
  8284. }
  8285. }
  8286. }
  8287. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  8288. $merged_roles = [];
  8289. foreach($ref_roles as $role) {
  8290. $role_name = getProp($role, 'role');
  8291. if (!isset($extra_roles[$role_name])) {
  8292. $merged_roles[$role_name] = $role;
  8293. }
  8294. }
  8295. // 添加extra_roles
  8296. foreach($extra_roles as $role_name => $role) {
  8297. $merged_roles[$role_name] = $role;
  8298. }
  8299. $ref_roles = array_values($merged_roles);
  8300. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  8301. $merged_scenes = [];
  8302. foreach($ref_scenes as $scene) {
  8303. $scene_name = getProp($scene, 'scene');
  8304. if (!isset($extra_scenes[$scene_name])) {
  8305. $merged_scenes[$scene_name] = $scene;
  8306. }
  8307. }
  8308. // 添加extra_scenes
  8309. foreach($extra_scenes as $scene_name => $scene) {
  8310. $merged_scenes[$scene_name] = $scene;
  8311. }
  8312. $ref_scenes = array_values($merged_scenes);
  8313. // 合并ref_props和extra_props(extra_props优先,去重)
  8314. $merged_props = [];
  8315. foreach($ref_props as $prop) {
  8316. $prop_name = getProp($prop, 'prop');
  8317. if (!isset($extra_props[$prop_name])) {
  8318. $merged_props[$prop_name] = $prop;
  8319. }
  8320. }
  8321. // 添加extra_props
  8322. foreach($extra_props as $prop_name => $prop) {
  8323. $merged_props[$prop_name] = $prop;
  8324. }
  8325. $ref_props = array_values($merged_props);
  8326. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  8327. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  8328. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  8329. // 构建强制主体、场景和道具提示词
  8330. $forced_roles_prompt = "";
  8331. $forced_scenes_prompt = "";
  8332. $forced_props_prompt = "";
  8333. if (!empty($extra_roles)) {
  8334. $forced_roles_list = "";
  8335. foreach($extra_roles as $role_name => $role) {
  8336. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  8337. }
  8338. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  8339. }
  8340. if (!empty($extra_scenes)) {
  8341. $forced_scenes_list = "";
  8342. foreach($extra_scenes as $scene_name => $scene) {
  8343. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  8344. }
  8345. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  8346. }
  8347. if (!empty($extra_props)) {
  8348. $forced_props_list = "";
  8349. foreach($extra_props as $prop_name => $prop) {
  8350. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  8351. }
  8352. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  8353. }
  8354. if ($anime_script_id) {
  8355. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  8356. }else if ($roles_content) {
  8357. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  8358. 主体范围:\n {$roles_content}\n
  8359. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  8360. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8361. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8362. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8363. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8364. }else {
  8365. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8366. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8367. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8368. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8369. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8370. }
  8371. if ($anime_script_id) {
  8372. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  8373. }else if ($scenes_content) {
  8374. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8375. 场景范围:\n {$scenes_content}\n
  8376. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  8377. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  8378. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8379. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8380. }else {
  8381. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8382. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8383. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8384. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8385. }
  8386. if ($anime_script_id) {
  8387. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  8388. }else if ($props_content) {
  8389. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8390. 道具范围:\n {$props_content}\n
  8391. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  8392. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  8393. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8394. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8395. }else {
  8396. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8397. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  8398. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8399. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8400. }
  8401. // 提取文件内容
  8402. if ($file) {
  8403. $uploaded_content = $this->extractFileContent($file);
  8404. if (!$uploaded_content) {
  8405. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8406. }
  8407. } elseif ($script_id) {
  8408. $uploaded_content = $this->getContentByScriptId($script_id);
  8409. if (!$uploaded_content) {
  8410. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  8411. }
  8412. } elseif ($bid) {
  8413. $uploaded_content = $this->getContentByBid($bid);
  8414. if (!$uploaded_content) {
  8415. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  8416. }
  8417. } elseif ($content) {
  8418. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  8419. }
  8420. // elseif ($prompt) {
  8421. // $uploaded_content = filterContent($prompt);
  8422. // }
  8423. else {
  8424. $uploaded_content = '';
  8425. }
  8426. // 美术风格
  8427. $input_art_style = getProp($data, 'art_style');
  8428. if (!$input_art_style) {
  8429. $mappedArtStyle = getProp($anime, 'art_style');
  8430. }else {
  8431. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  8432. }
  8433. if (!$mappedArtStyle) {
  8434. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  8435. }else {
  8436. if (strstr($mappedArtStyle, '基础画风风格词')) {
  8437. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  8438. }else {
  8439. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  8440. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  8441. }
  8442. }
  8443. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8444. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8445. // 强制要求:
  8446. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8447. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8448. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8449. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  8450. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  8451. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  8452. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  8453. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  8454. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  8455. // 10.分镜要和场景列表、人物主体保持一致\n
  8456. // 普通要求:
  8457. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8458. // {$role_demo}
  8459. // {$scene_demo}
  8460. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8461. // 4.1片段分割逻辑(优先级从高到低):
  8462. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8463. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8464. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8465. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8466. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8467. // - 片段数量格式为: 片段数量:8
  8468. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8469. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8470. // 4.3分镜结构:每个分镜包含以下字段:
  8471. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  8472. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  8473. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8474. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  8475. // - 运镜:场景+画面描述+运镜
  8476. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  8477. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8478. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8479. // 5.$mappedArtStyle_prompt\n\n
  8480. // 示例格式:\n
  8481. // 第1集:隐形的守护者
  8482. // ###故事梗概
  8483. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8484. // ###美术风格
  8485. // 基础画风风格词:胡金铨武侠
  8486. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8487. // ###主体列表
  8488. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8489. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8490. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8491. // ###场景列表
  8492. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8493. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8494. // ###分段剧本
  8495. // 片段数量:8
  8496. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8497. // ##片段1
  8498. // 时长:12s
  8499. // 分镜1
  8500. // 场景:边境小镇街道
  8501. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8502. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8503. // 配音台词:
  8504. // 背景音效:
  8505. // 分镜2
  8506. // 场景:悦来酒馆
  8507. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8508. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8509. // 配音台词:
  8510. // 背景音效:
  8511. // 分镜3
  8512. // 场景:悦来酒馆
  8513. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8514. // 运镜:从中景推向令牌特写。
  8515. // 配音台词:
  8516. // 背景音效:
  8517. // 分镜4
  8518. // 场景:悦来酒馆
  8519. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8520. // 运镜:极速推向酒水溅起的瞬间。
  8521. // 配音台词:
  8522. // 背景音效:
  8523. // 分镜5
  8524. // 镜头描述
  8525. // 场景:悦来酒馆
  8526. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8527. // 运镜:固定机位,利用倾斜构图制造压迫感。
  8528. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8529. // 背景音效:
  8530. // \n\n";
  8531. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  8532. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  8533. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  8534. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  8535. 普通要求:
  8536. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8537. {$role_demo}
  8538. {$scene_demo}
  8539. {$prop_demo}
  8540. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8541. 5.1片段分割逻辑(优先级从高到低):
  8542. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8543. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8544. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8545. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8546. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8547. - 片段数量格式为: 片段数量:8
  8548. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8549. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8550. 5.3分镜结构:每个分镜包含以下字段:
  8551. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8552. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8553. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8554. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8555. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8556. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8557. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8558. - 运镜:场景+画面描述+运镜
  8559. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8560. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8561. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8562. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8563. 6.《情绪-视听语言映射表》:
  8564. 6.1 场景空间与时间心理学 (Scene & Temporality)
  8565. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8566. -----|---------|------------|----------------
  8567. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  8568. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  8569. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  8570. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  8571. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  8572. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8573. -----|---------|------------|----------------
  8574. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  8575. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  8576. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  8577. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  8578. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  8579. --------|---------|--------------|-------------
  8580. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  8581. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  8582. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  8583. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  8584. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  8585. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  8586. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  8587. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  8588. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  8589. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  8590. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  8591. -----|---------|------------|------------
  8592. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  8593. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  8594. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  8595. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  8596. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  8597. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  8598. --------|---------|--------------|----------
  8599. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  8600. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  8601. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  8602. 6.6 声音设计与潜意识影响 (Soundscape)
  8603. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  8604. -----|---------|------------|------------------
  8605. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  8606. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  8607. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  8608. 理论基石:
  8609. - The Five C's of Cinematography by Joseph V. Mascelli
  8610. - Film Art: An Introduction by David Bordwell
  8611. - Sight, Sound, Motion by Herbert Zettl
  8612. - Notes on the Cinematograph by Robert Bresson
  8613. \n\n
  8614. 7.{$mappedArtStyle_prompt}
  8615. 示例格式:\n
  8616. 第1集:隐形的守护者
  8617. ###故事梗概
  8618. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8619. ###美术风格
  8620. 基础画风风格词:胡金铨武侠
  8621. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8622. ###主体列表
  8623. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8624. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8625. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8626. ###场景列表
  8627. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8628. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8629. ###道具列表
  8630. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  8631. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  8632. ###分段剧本
  8633. 片段数量:8
  8634. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8635. ##片段1
  8636. 时长:12s
  8637. 分镜1
  8638. 出场角色:刀疤脸
  8639. 场景:边境小镇街道
  8640. 出场道具:酒杯-高脚杯
  8641. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8642. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8643. 配音台词:
  8644. 背景音效:
  8645. 分镜2
  8646. 出场角色:刀疤脸
  8647. 场景:悦来酒馆
  8648. 出场道具:酒杯-高脚杯
  8649. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8650. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8651. 配音台词:
  8652. 背景音效:
  8653. 分镜3
  8654. 出场角色:刀疤脸
  8655. 场景:悦来酒馆
  8656. 出场道具:酒杯-高脚杯
  8657. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8658. 运镜:从中景推向令牌特写。
  8659. 配音台词:
  8660. 背景音效:
  8661. 分镜4
  8662. 出场角色:刀疤脸
  8663. 场景:悦来酒馆
  8664. 出场道具:酒杯-高脚杯
  8665. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8666. 运镜:极速推向酒水溅起的瞬间。
  8667. 配音台词:
  8668. 背景音效:
  8669. 分镜5
  8670. 出场角色:刀疤脸
  8671. 场景:悦来酒馆
  8672. 出场道具:酒杯-高脚杯
  8673. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8674. 运镜:固定机位,利用倾斜构图制造压迫感。
  8675. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8676. 背景音效:
  8677. \n\n";
  8678. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8679. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  8680. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  8681. $prompt = $origin_prompt;
  8682. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  8683. // 获取章节内容
  8684. $full_content = getProp($anime, 'content');
  8685. if ($uploaded_content) {
  8686. $full_content = $uploaded_content;
  8687. }
  8688. // 根据章节内容拆分章节
  8689. $chapters = splitContent($full_content);
  8690. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  8691. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  8692. $messages = [];
  8693. if ($prompt == '确认分镜大纲') {
  8694. // 暂时保留
  8695. $content = $chapter_content;
  8696. if ($is_single) $content = $full_content; // 单剧集使用全文
  8697. if (!$content) {
  8698. Utils::throwError('20003:章节内容无法获取,请确认');
  8699. }
  8700. $question = $is_single
  8701. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  8702. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  8703. // 构建消息
  8704. $messages[] =
  8705. [
  8706. 'role' => 'user',
  8707. 'content' => $question
  8708. ];
  8709. }else if ($prompt == '继续策划下一集') {
  8710. if ($is_single) {
  8711. Utils::throwError('20003:单剧集不支持继续策划下一集');
  8712. }
  8713. $content = $chapter_content;
  8714. if (!$content) {
  8715. Utils::throwError('20003:章节内容无法获取,请确认');
  8716. }
  8717. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  8718. // 获取上一集最后记录
  8719. $prev_sequence = $episode_number - 1;
  8720. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  8721. // 构建消息
  8722. $messages[] =
  8723. [
  8724. 'role' => 'user',
  8725. 'content' => $question
  8726. ];
  8727. // dd($messages);
  8728. }else {
  8729. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  8730. if (!$content) {
  8731. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  8732. }
  8733. if (!$content) {
  8734. Utils::throwError('20003:章节内容无法获取,请确认');
  8735. }
  8736. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  8737. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  8738. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  8739. if ($origin_prompt) {
  8740. $question .= "本次修改要求如下:\n{$origin_prompt}";
  8741. }
  8742. $messages[] =
  8743. [
  8744. 'role' => 'user',
  8745. 'content' => $question
  8746. ];
  8747. }
  8748. // 处理文本模型
  8749. $model = getProp($data, 'model');
  8750. if (!$model) {
  8751. // 用户没有输入,从anime表获取
  8752. $model = getProp($anime, 'model');
  8753. if (!$model) {
  8754. // anime表也没有,使用默认值
  8755. $model = 'deepseek-v4-pro';
  8756. }
  8757. }
  8758. // 验证模型是否在可用模型表中
  8759. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8760. $model = 'deepseek-v4-pro';
  8761. }
  8762. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8763. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  8764. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8765. if ($model === 'deepseek-chat') {
  8766. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8767. $model = 'deepseek-v4-flash';
  8768. $thinkingMode = 'disabled';
  8769. } elseif ($model === 'deepseek-reasoner') {
  8770. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8771. $model = 'deepseek-v4-flash';
  8772. $thinkingMode = 'enabled';
  8773. }
  8774. $post_data = [
  8775. 'model' => $model,
  8776. 'messages' => $messages,
  8777. // 'max_tokens' => 8192,
  8778. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8779. 'frequency_penalty' => 0,
  8780. 'presence_penalty' => 0,
  8781. 'response_format' => ['type' => 'text'],
  8782. 'thinking' => ['type' => $thinkingMode],
  8783. 'stream' => true // 启用流式输出
  8784. ];
  8785. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8786. // 根据模型类型选择调用方法
  8787. $fullContent = '';
  8788. $fullReasoningContent = '';
  8789. $usage = [];
  8790. try {
  8791. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8792. // DeepSeek 官方模型使用 DeepSeek API
  8793. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8794. } else if (in_array($model, $this->gpt_text_models)) {
  8795. // GPT-5.4 模型使用 TokenRouter API
  8796. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8797. } else if (in_array($model, $this->gemini_text_models)) {
  8798. // Gemini 模型使用 Gemini API
  8799. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8800. } else {
  8801. // 其他模型使用火山引擎API
  8802. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8803. }
  8804. // 验证返回值类型
  8805. if (!is_iterable($streamGenerator)) {
  8806. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8807. dLog('deepseek')->error('chat流式生成器无效', [
  8808. 'generator_type' => $errorType,
  8809. 'model' => $model,
  8810. 'anime_id' => $anime_id,
  8811. 'episode_number' => $episode_number
  8812. ]);
  8813. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  8814. 'type' => $errorType,
  8815. 'model' => $model
  8816. ]);
  8817. yield [
  8818. 'type' => 'error',
  8819. 'episode' => [],
  8820. 'answer' => '',
  8821. 'reasoning' => '',
  8822. 'usage' => [],
  8823. 'error' => '接口返回数据异常,请重新请求'
  8824. ];
  8825. return;
  8826. }
  8827. // 处理流式输出
  8828. foreach ($streamGenerator as $chunk) {
  8829. if (isset($chunk['type'])) {
  8830. if ($chunk['type'] === 'done') {
  8831. // 最终结果
  8832. $fullContent = $chunk['full_content'];
  8833. $fullReasoningContent = $chunk['full_reasoning'];
  8834. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8835. } else {
  8836. // 逐块yield数据
  8837. yield $chunk;
  8838. }
  8839. }
  8840. }
  8841. } catch (\Exception $e) {
  8842. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  8843. 'model' => $model,
  8844. 'anime_id' => $anime_id,
  8845. 'episode_number' => $episode_number,
  8846. 'trace' => $e->getTraceAsString()
  8847. ]);
  8848. logDB('deepseek', 'error', 'chat流式处理失败', [
  8849. 'error' => $e->getMessage(),
  8850. 'model' => $model
  8851. ]);
  8852. yield [
  8853. 'type' => 'error',
  8854. 'episode' => [],
  8855. 'answer' => '',
  8856. 'reasoning' => '',
  8857. 'usage' => [],
  8858. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8859. ];
  8860. return;
  8861. }
  8862. dLog('deepseek')->info('完整内容: '.$fullContent);
  8863. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8864. // 处理完整内容并返回最终结果
  8865. $episode_arr = handleEpisodeContentForAce($fullContent);
  8866. logDB('deepseek', 'info', '解析内容', $episode_arr);
  8867. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  8868. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  8869. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  8870. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  8871. // }
  8872. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  8873. $max_retries = 3;
  8874. $retry_count = 0;
  8875. $validation_failed = false;
  8876. $validation_error_msg = '';
  8877. // 验证生成的内容
  8878. if ($anime_script_id) {
  8879. // 检查是否有acts数据
  8880. if (empty($episode_arr['acts'])) {
  8881. $validation_failed = true;
  8882. $validation_error_msg = '未生成分镜剧本相关的内容';
  8883. } else {
  8884. // 仅当存在强制主体设定时校验主体列表
  8885. if (!empty($extra_roles)) {
  8886. $generated_roles = array_column($episode_arr['roles'], 'role');
  8887. // 过滤掉"旁白"角色
  8888. $generated_roles = array_filter($generated_roles, function($role) {
  8889. return $role !== '旁白';
  8890. });
  8891. $expected_roles = array_keys($extra_roles);
  8892. // 找出生成的主体中不在预期列表中的主体
  8893. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8894. if (!empty($invalid_roles)) {
  8895. $validation_failed = true;
  8896. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8897. }
  8898. }
  8899. // 仅当存在强制场景设定时校验场景列表
  8900. if (!$validation_failed && !empty($extra_scenes)) {
  8901. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  8902. $expected_scenes = array_keys($extra_scenes);
  8903. // 找出生成的场景中不在预期列表中的场景
  8904. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8905. if (!empty($invalid_scenes)) {
  8906. $validation_failed = true;
  8907. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8908. }
  8909. }
  8910. // 仅当存在强制道具设定时校验道具列表
  8911. if (!$validation_failed && !empty($extra_props)) {
  8912. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8913. $expected_props = array_keys($extra_props);
  8914. // 找出生成的道具中不在预期列表中的道具
  8915. $invalid_props = array_diff($generated_props, $expected_props);
  8916. if (!empty($invalid_props)) {
  8917. $validation_failed = true;
  8918. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8919. }
  8920. }
  8921. }
  8922. } else {
  8923. // 如果没有anime_script_id,只检查是否有acts数据
  8924. if (empty($episode_arr['acts'])) {
  8925. $validation_failed = true;
  8926. $validation_error_msg = '未生成分镜剧本相关的内容';
  8927. }
  8928. }
  8929. // 重试逻辑
  8930. while ($validation_failed && $retry_count < $max_retries) {
  8931. $retry_count++;
  8932. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  8933. 'reason' => $validation_error_msg,
  8934. 'anime_id' => $anime_id,
  8935. 'episode_number' => $episode_number
  8936. ]);
  8937. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  8938. 'reason' => $validation_error_msg,
  8939. 'anime_id' => $anime_id
  8940. ]);
  8941. // 发送流式重试提示
  8942. yield [
  8943. 'type' => 'retry',
  8944. 'retry_count' => $retry_count,
  8945. 'reason' => $validation_error_msg
  8946. ];
  8947. // 构建重试提示词
  8948. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  8949. if ($anime_script_id) {
  8950. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  8951. $retry_prompt .= "2. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  8952. $retry_prompt .= "3. 必须包含完整的分镜剧本内容\n";
  8953. } else {
  8954. $retry_prompt .= "1. 必须包含完整的分镜剧本内容\n";
  8955. }
  8956. // 添加重试消息到messages
  8957. $messages[] = [
  8958. 'role' => 'assistant',
  8959. 'content' => $fullContent
  8960. ];
  8961. $messages[] = [
  8962. 'role' => 'user',
  8963. 'content' => $retry_prompt
  8964. ];
  8965. // 更新post_data的messages
  8966. $post_data['messages'] = $messages;
  8967. // 重新调用API
  8968. try {
  8969. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8970. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8971. } else if (in_array($model, $this->gpt_text_models)) {
  8972. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8973. } else if (in_array($model, $this->gemini_text_models)) {
  8974. // Gemini 模型使用 Gemini API
  8975. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8976. } else {
  8977. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8978. }
  8979. // 处理流式输出
  8980. $fullContent = '';
  8981. $fullReasoningContent = '';
  8982. foreach ($streamGenerator as $chunk) {
  8983. if (isset($chunk['type'])) {
  8984. if ($chunk['type'] === 'done') {
  8985. $fullContent = $chunk['full_content'];
  8986. $fullReasoningContent = $chunk['full_reasoning'];
  8987. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8988. } else {
  8989. yield $chunk;
  8990. }
  8991. }
  8992. }
  8993. // 重新解析内容
  8994. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  8995. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  8996. $episode_arr = handleEpisodeContentForAce($fullContent);
  8997. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  8998. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  8999. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  9000. // }
  9001. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  9002. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  9003. // 重新验证
  9004. $validation_failed = false;
  9005. $validation_error_msg = '';
  9006. if ($anime_script_id) {
  9007. if (empty($episode_arr['acts'])) {
  9008. $validation_failed = true;
  9009. $validation_error_msg = '未生成分镜剧本相关的内容';
  9010. } else {
  9011. // 仅当存在强制主体设定时校验主体列表
  9012. if (!empty($extra_roles)) {
  9013. $generated_roles = array_column($episode_arr['roles'], 'role');
  9014. // 过滤掉"旁白"角色
  9015. $generated_roles = array_filter($generated_roles, function($role) {
  9016. return $role !== '旁白';
  9017. });
  9018. $expected_roles = array_keys($extra_roles);
  9019. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9020. if (!empty($invalid_roles)) {
  9021. $validation_failed = true;
  9022. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9023. }
  9024. }
  9025. // 仅当存在强制场景设定时校验场景列表
  9026. if (!$validation_failed && !empty($extra_scenes)) {
  9027. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  9028. $expected_scenes = array_keys($extra_scenes);
  9029. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9030. if (!empty($invalid_scenes)) {
  9031. $validation_failed = true;
  9032. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9033. }
  9034. }
  9035. // 仅当存在强制道具设定时校验道具列表
  9036. if (!$validation_failed && !empty($extra_props)) {
  9037. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9038. $expected_props = array_keys($extra_props);
  9039. $invalid_props = array_diff($generated_props, $expected_props);
  9040. if (!empty($invalid_props)) {
  9041. $validation_failed = true;
  9042. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9043. }
  9044. }
  9045. }
  9046. } else {
  9047. if (empty($episode_arr['acts'])) {
  9048. $validation_failed = true;
  9049. $validation_error_msg = '未生成分镜剧本相关的内容';
  9050. }
  9051. }
  9052. } catch (\Exception $e) {
  9053. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  9054. 'trace' => $e->getTraceAsString()
  9055. ]);
  9056. break;
  9057. }
  9058. }
  9059. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  9060. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  9061. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  9062. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  9063. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  9064. if ($validation_failed && $retry_count >= $max_retries) {
  9065. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  9066. 'retry_count' => $retry_count,
  9067. 'last_error' => $validation_error_msg
  9068. ]);
  9069. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  9070. 'error' => $validation_error_msg,
  9071. 'anime_id' => $anime_id
  9072. ]);
  9073. $validation_failed = false;
  9074. $validation_error_msg = '';
  9075. }
  9076. // 如果重试后仍然失败
  9077. if ($validation_failed) {
  9078. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  9079. 'retry_count' => $retry_count,
  9080. 'last_error' => $validation_error_msg
  9081. ]);
  9082. try {
  9083. $now = date('Y-m-d H:i:s');
  9084. $records = [
  9085. [
  9086. 'uid' => $uid,
  9087. 'anime_id' => $anime_id,
  9088. 'sequence' => $episode_number,
  9089. 'role' => 'user',
  9090. 'content' => $prompt,
  9091. 'created_at' => $now,
  9092. 'updated_at' => $now
  9093. ],
  9094. [
  9095. 'uid' => $uid,
  9096. 'anime_id' => $anime_id,
  9097. 'sequence' => $episode_number,
  9098. 'role' => 'assistant',
  9099. 'content' => $fullContent,
  9100. 'created_at' => $now,
  9101. 'updated_at' => $now
  9102. ]
  9103. ];
  9104. DB::table('mp_anime_records')->insert($records);
  9105. } catch (\Exception $e) {
  9106. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9107. }
  9108. yield [
  9109. 'type' => 'done',
  9110. 'episode' => [],
  9111. 'answer' => $fullContent,
  9112. 'reasoning' => $fullReasoningContent,
  9113. 'usage' => $usage,
  9114. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  9115. ];
  9116. return;
  9117. }
  9118. // 验证成功,记录日志
  9119. if ($retry_count > 0) {
  9120. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  9121. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  9122. }
  9123. // 老逻辑
  9124. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  9125. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  9126. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  9127. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  9128. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  9129. $existing_props = is_array($existing_props) ? $existing_props : [];
  9130. $now = date('Y-m-d H:i:s');
  9131. try {
  9132. DB::beginTransaction();
  9133. $saveResult = $this->saveEpisodeVersionData(
  9134. $anime_id,
  9135. $episode_number,
  9136. $episode_arr,
  9137. $existing_roles,
  9138. $existing_scenes,
  9139. $existing_props,
  9140. $current_episode,
  9141. $base_episode,
  9142. $is_regenerate_version,
  9143. $content,
  9144. $now,
  9145. $ref_products
  9146. );
  9147. $episode = $saveResult['episode'];
  9148. $episode_id = $saveResult['episode_id'];
  9149. $merged_roles = $saveResult['merged_roles'];
  9150. $merged_scenes = $saveResult['merged_scenes'];
  9151. $merged_props = $saveResult['merged_props'];
  9152. $record_content = $origin_prompt;
  9153. if ($uploaded_content !== '') {
  9154. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  9155. }
  9156. $records = [
  9157. [
  9158. 'uid' => $uid,
  9159. 'anime_id' => $anime_id,
  9160. 'role' => 'user',
  9161. 'content' => $record_content,
  9162. 'sequence' => $episode_number,
  9163. 'episode_id' => $episode_id,
  9164. 'created_at' => $now,
  9165. 'updated_at' => $now
  9166. ],
  9167. [
  9168. 'uid' => $uid,
  9169. 'anime_id' => $anime_id,
  9170. 'role' => 'assistant',
  9171. 'content' => $fullContent,
  9172. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  9173. 'sequence' => $episode_number,
  9174. 'episode_id' => $episode_id,
  9175. 'created_at' => $now,
  9176. 'updated_at' => $now
  9177. ]
  9178. ];
  9179. $boolen4 = DB::table('mp_anime_records')->insert($records);
  9180. if (!$boolen4) {
  9181. Utils::throwError('20003:对话记录保存失败');
  9182. }
  9183. // 保存模型到anime表
  9184. $update_anime_data = [
  9185. 'model' => $model,
  9186. 'updated_at' => $now
  9187. ];
  9188. if ($uploaded_content) {
  9189. $update_anime_data['content'] = $uploaded_content;
  9190. }
  9191. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  9192. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  9193. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  9194. 'anime_id' => $anime_id,
  9195. 'episode_number' => $episode_number,
  9196. 'model' => $model,
  9197. ]);
  9198. }catch (\Exception $e) {
  9199. DB::rollBack();
  9200. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  9201. yield [
  9202. 'type' => 'done',
  9203. 'answer' => $fullContent,
  9204. 'reasoning' => $fullReasoningContent,
  9205. 'usage' => $usage,
  9206. 'error' => $e->getMessage(),
  9207. ];
  9208. return;
  9209. }
  9210. DB::commit();
  9211. if ($is_global_generate_pics) {
  9212. // // 批量生成全局角色图片
  9213. // $this->batchSetGlobalRoleImg([
  9214. // 'anime_id' => $anime_id,
  9215. // ], true);
  9216. // // 批量生成全局场景图片
  9217. // $this->batchSetGlobalSceneImg([
  9218. // 'anime_id' => $anime_id,
  9219. // ], true);
  9220. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  9221. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  9222. }
  9223. $episode['episode_id'] = $episode_id;
  9224. $episode['roles'] = $merged_roles;
  9225. $episode['scenes'] = $merged_scenes;
  9226. $episode['props'] = $merged_props;
  9227. $episode['end_episode_sequence'] = $end_episode_sequence;
  9228. // 获取mp_animes表中的视频参数
  9229. $episode['video_params'] = [
  9230. 'video_model' => getProp($anime, 'video_model'),
  9231. 'video_resolution' => getProp($anime, 'video_resolution'),
  9232. 'ratio' => getProp($anime, 'video_ratio'),
  9233. ];
  9234. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9235. yield [
  9236. 'type' => 'done',
  9237. 'episode' => $episode,
  9238. 'answer' => $fullContent,
  9239. 'reasoning' => $fullReasoningContent,
  9240. 'usage' => $usage
  9241. ];
  9242. }
  9243. /**
  9244. * chatForAce的非流式版本 - 用于定时任务
  9245. * 只获取最终 type=done 的数据,并验证必要字段
  9246. *
  9247. * @param array $data 请求数据
  9248. * @return array 生成结果
  9249. */
  9250. public function chatForAceNonStream($data) {
  9251. $finalResult = null;
  9252. // 调用流式方法,只保存 type=done 的数据
  9253. foreach ($this->chatForAce($data) as $chunk) {
  9254. // 只关注最终结果
  9255. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  9256. $finalResult = $chunk;
  9257. break; // 找到 done 就退出循环
  9258. }
  9259. }
  9260. // 验证最终结果
  9261. if (!$finalResult) {
  9262. return ['error' => '生成失败:未获取到最终结果'];
  9263. }
  9264. // 检查是否有错误
  9265. if (isset($finalResult['error']) && $finalResult['error']) {
  9266. return $finalResult;
  9267. }
  9268. // 验证必要字段
  9269. $episode = $finalResult['episode'] ?? [];
  9270. // 验证 roles
  9271. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  9272. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  9273. }
  9274. // 验证 scenes
  9275. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  9276. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  9277. }
  9278. // 验证 props(道具可以为空,但必须存在且为数组)
  9279. if (!isset($episode['props']) || !is_array($episode['props'])) {
  9280. $episode['props'] = [];
  9281. }
  9282. // 验证 acts(分镜剧本)
  9283. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  9284. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  9285. }
  9286. // 更新验证后的 episode 数据
  9287. $finalResult['episode'] = $episode;
  9288. // 记录验证成功日志
  9289. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  9290. 'roles_count' => count($episode['roles']),
  9291. 'scenes_count' => count($episode['scenes']),
  9292. 'props_count' => count($episode['props']),
  9293. 'acts_count' => count($episode['acts'])
  9294. ]);
  9295. return $finalResult;
  9296. }
  9297. /**
  9298. * 批量生成多个分集
  9299. *
  9300. * @param array $data 请求数据
  9301. * @return array 任务信息
  9302. */
  9303. public function batchGenerateEpisodes($data) {
  9304. $uid = Site::getUid();
  9305. $cpid = Site::getCpid();
  9306. $anime_id = getProp($data, 'anime_id');
  9307. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  9308. if (!$anime_id) {
  9309. Utils::throwError('20003:anime_id参数缺失');
  9310. }
  9311. if ($generate_episode_number < 1) {
  9312. Utils::throwError('20003:生成集数必须大于0');
  9313. }
  9314. // 获取动漫信息
  9315. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9316. if (!$anime) {
  9317. Utils::throwError('20003:该剧集不存在');
  9318. }
  9319. // 检查是否是全能模式
  9320. if ((int)getProp($anime, 'ace_mode') !== 1) {
  9321. Utils::throwError('20003:只有全能模式才支持批量生成');
  9322. }
  9323. // 检查是否是多剧集模式
  9324. if ((int)getProp($anime, 'is_multi') !== 1) {
  9325. Utils::throwError('20003:单剧集不支持批量生成');
  9326. }
  9327. // 获取当前已生成的最大集数
  9328. $currentMaxEpisode = DB::table('mp_anime_episodes')
  9329. ->where('anime_id', $anime_id)
  9330. ->where('is_default', 1)
  9331. ->max('episode_number');
  9332. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  9333. // 确定起始集数
  9334. $startEpisodeNumber = $currentMaxEpisode + 1;
  9335. // 计算结束集数
  9336. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  9337. // 检查是否超过总集数限制
  9338. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  9339. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  9340. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  9341. }
  9342. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  9343. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  9344. ->where('anime_id', $anime_id)
  9345. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  9346. ->whereIn('status', ['pending', 'processing', 'completed'])
  9347. ->count();
  9348. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  9349. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  9350. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  9351. if ($needEpisodeCount > 0) {
  9352. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS * $needEpisodeCount, $uid);
  9353. }
  9354. $now = date('Y-m-d H:i:s');
  9355. $createdTasks = [];
  9356. $skippedTasks = [];
  9357. // 为每一集创建详情记录
  9358. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  9359. // 检查是否已有该集的任务记录
  9360. $existingTask = DB::table('mp_batch_episode_generation_details')
  9361. ->where('anime_id', $anime_id)
  9362. ->where('episode_number', $episodeNumber)
  9363. ->first();
  9364. if ($existingTask) {
  9365. // 如果已存在且未完成,跳过
  9366. if (in_array($existingTask->status, ['pending', 'processing'])) {
  9367. $skippedTasks[] = $episodeNumber;
  9368. continue;
  9369. }
  9370. // 如果是失败状态,可以重新创建(删除旧记录)
  9371. if ($existingTask->status === 'failed') {
  9372. DB::table('mp_batch_episode_generation_details')
  9373. ->where('id', $existingTask->id)
  9374. ->delete();
  9375. }
  9376. // 如果是已完成状态,也跳过
  9377. if ($existingTask->status === 'completed') {
  9378. $skippedTasks[] = $episodeNumber;
  9379. continue;
  9380. }
  9381. }
  9382. // 准备任务数据
  9383. $taskData = [
  9384. 'anime_id' => $anime_id,
  9385. 'uid' => $uid,
  9386. 'cpid' => $cpid,
  9387. 'episode_number' => $episodeNumber,
  9388. 'status' => 'pending',
  9389. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  9390. 'retry_count' => 0,
  9391. 'created_at' => $now,
  9392. 'updated_at' => $now
  9393. ];
  9394. // 创建任务记录
  9395. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  9396. if ($taskId) {
  9397. $createdTasks[] = $episodeNumber;
  9398. }
  9399. }
  9400. if (empty($createdTasks)) {
  9401. if (!empty($skippedTasks)) {
  9402. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  9403. } else {
  9404. Utils::throwError('20003:创建批量生成任务失败');
  9405. }
  9406. }
  9407. return [
  9408. 'anime_id' => $anime_id,
  9409. 'start_episode' => $startEpisodeNumber,
  9410. 'end_episode' => $endEpisodeNumber,
  9411. 'total_episodes' => $generate_episode_number,
  9412. 'created_episodes' => $createdTasks,
  9413. 'skipped_episodes' => $skippedTasks,
  9414. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集。" .
  9415. "已创建: " . implode(',', $createdTasks) .
  9416. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : "")
  9417. ];
  9418. }
  9419. /**
  9420. * 获取批量生成任务状态
  9421. *
  9422. * @param array $data 请求数据
  9423. * @return array 任务状态信息
  9424. */
  9425. public function getBatchGenerationTaskStatus($data) {
  9426. $anime_id = getProp($data, 'anime_id');
  9427. if (!$anime_id) {
  9428. Utils::throwError('20003:anime_id参数缺失');
  9429. }
  9430. // 获取该anime的所有任务
  9431. $tasks = DB::table('mp_batch_episode_generation_details')
  9432. ->where('anime_id', $anime_id)
  9433. ->orderBy('episode_number')
  9434. ->get()
  9435. ->map(function($item) {
  9436. return [
  9437. 'id' => $item->id,
  9438. 'episode_number' => $item->episode_number,
  9439. 'status' => $item->status,
  9440. 'error_message' => $item->error_message,
  9441. 'retry_count' => $item->retry_count,
  9442. 'created_at' => $item->created_at,
  9443. 'updated_at' => $item->updated_at,
  9444. 'completed_at' => $item->completed_at
  9445. ];
  9446. })
  9447. ->toArray();
  9448. if (empty($tasks)) {
  9449. Utils::throwError('20003:该剧集没有批量生成任务');
  9450. }
  9451. // 统计各状态数量
  9452. $totalCount = count($tasks);
  9453. $pendingCount = 0;
  9454. $processingCount = 0;
  9455. $completedCount = 0;
  9456. $failedCount = 0;
  9457. foreach ($tasks as $task) {
  9458. switch ($task['status']) {
  9459. case 'pending':
  9460. $pendingCount++;
  9461. break;
  9462. case 'processing':
  9463. $processingCount++;
  9464. break;
  9465. case 'completed':
  9466. $completedCount++;
  9467. break;
  9468. case 'failed':
  9469. $failedCount++;
  9470. break;
  9471. }
  9472. }
  9473. // 计算进度百分比
  9474. $progress = 0;
  9475. if ($totalCount > 0) {
  9476. $progress = round(($completedCount / $totalCount) * 100, 2);
  9477. }
  9478. // 判断整体状态
  9479. $overallStatus = 'processing';
  9480. if ($completedCount === $totalCount) {
  9481. $overallStatus = 'completed';
  9482. } elseif ($pendingCount === $totalCount) {
  9483. $overallStatus = 'pending';
  9484. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  9485. $overallStatus = 'failed';
  9486. }
  9487. return [
  9488. 'anime_id' => $anime_id,
  9489. 'total_episodes' => $totalCount,
  9490. 'pending_count' => $pendingCount,
  9491. 'processing_count' => $processingCount,
  9492. 'completed_count' => $completedCount,
  9493. 'failed_count' => $failedCount,
  9494. 'progress' => $progress,
  9495. 'overall_status' => $overallStatus,
  9496. 'tasks' => $tasks
  9497. ];
  9498. }
  9499. /**
  9500. * 将生成内容中不在强制列表中的资源合并进强制列表
  9501. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  9502. *
  9503. * @param array $generated 生成内容中的资源列表
  9504. * @param array $forced 强制资源列表(key为资源名称)
  9505. * @param string $type 资源类型:role、scene、prop
  9506. * @return array
  9507. */
  9508. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  9509. {
  9510. foreach ($generated as $item) {
  9511. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  9512. if ($name === null || $name === '') {
  9513. continue;
  9514. }
  9515. if ($name === '旁白') {
  9516. continue;
  9517. }
  9518. if (!isset($forced[$name])) {
  9519. $forced[$name] = $item;
  9520. }
  9521. }
  9522. return $forced;
  9523. }
  9524. /**
  9525. * 智能匹配并替换主体和场景名称
  9526. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  9527. *
  9528. * @param array $episode_arr 解析后的剧集数据
  9529. * @param array $extra_roles 强制主体设定(key为主体名称)
  9530. * @param array $extra_scenes 强制场景设定(key为场景名称)
  9531. * @return array 替换后的剧集数据
  9532. */
  9533. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  9534. $replaced_count = 0;
  9535. // 1. 处理主体列表
  9536. if (!empty($episode_arr['roles'])) {
  9537. foreach ($episode_arr['roles'] as &$role) {
  9538. $generated_role_name = $role['role'] ?? '';
  9539. // 跳过旁白
  9540. if ($generated_role_name === '旁白') {
  9541. continue;
  9542. }
  9543. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  9544. if (!isset($extra_roles[$generated_role_name])) {
  9545. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  9546. if ($matched_role) {
  9547. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  9548. $role['role'] = $matched_role;
  9549. $replaced_count++;
  9550. }
  9551. }
  9552. }
  9553. }
  9554. // 2. 处理场景列表
  9555. if (!empty($episode_arr['scenes'])) {
  9556. foreach ($episode_arr['scenes'] as &$scene) {
  9557. $generated_scene_name = $scene['scene'] ?? '';
  9558. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  9559. if (!isset($extra_scenes[$generated_scene_name])) {
  9560. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  9561. if ($matched_scene) {
  9562. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  9563. $scene['scene'] = $matched_scene;
  9564. $replaced_count++;
  9565. }
  9566. }
  9567. }
  9568. }
  9569. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  9570. if (!empty($episode_arr['acts'])) {
  9571. foreach ($episode_arr['acts'] as &$act) {
  9572. if (!empty($act['segments'])) {
  9573. foreach ($act['segments'] as &$segment) {
  9574. if (!empty($segment['segment_content'])) {
  9575. $original_content = $segment['segment_content'];
  9576. $replaced_content = $original_content;
  9577. // 替换场景名 - 在文本中查找并替换
  9578. foreach (array_keys($extra_scenes) as $full_scene_name) {
  9579. // 尝试找到可能的短名称
  9580. $potential_short_names = [];
  9581. // 提取场景名的主要部分(冒号之前)
  9582. if (mb_strpos($full_scene_name, ':') !== false) {
  9583. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  9584. $potential_short_names[] = $short_name;
  9585. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  9586. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  9587. $potential_short_names[] = $short_name;
  9588. }
  9589. // 替换场景字段中的短名称
  9590. foreach ($potential_short_names as $short_name) {
  9591. if ($short_name !== $full_scene_name) {
  9592. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  9593. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  9594. if ($new_content !== $replaced_content) {
  9595. $replaced_content = $new_content;
  9596. $replaced_count++;
  9597. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  9598. }
  9599. }
  9600. }
  9601. }
  9602. // 替换配音角色名(跳过旁白)
  9603. foreach (array_keys($extra_roles) as $full_role_name) {
  9604. if ($full_role_name === '旁白') {
  9605. continue;
  9606. }
  9607. // 尝试找到可能的短名称
  9608. $potential_short_names = [];
  9609. // 提取角色名的主要部分(短横线之前)
  9610. if (mb_strpos($full_role_name, '-') !== false) {
  9611. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  9612. $potential_short_names[] = $short_name;
  9613. }
  9614. // 替换配音台词中的短名称
  9615. foreach ($potential_short_names as $short_name) {
  9616. if ($short_name !== $full_role_name) {
  9617. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  9618. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  9619. if ($new_content !== $replaced_content) {
  9620. $replaced_content = $new_content;
  9621. $replaced_count++;
  9622. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  9623. }
  9624. }
  9625. }
  9626. }
  9627. // 如果有替换,更新segment_content
  9628. if ($replaced_content !== $original_content) {
  9629. $segment['segment_content'] = $replaced_content;
  9630. }
  9631. }
  9632. }
  9633. }
  9634. }
  9635. }
  9636. if ($replaced_count > 0) {
  9637. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  9638. 'replaced_count' => $replaced_count
  9639. ]);
  9640. }
  9641. return $episode_arr;
  9642. }
  9643. /**
  9644. * 查找匹配的名称
  9645. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  9646. *
  9647. * @param string $generated_name 生成的名称
  9648. * @param array $expected_names 预期的名称列表
  9649. * @return string|null 匹配到的名称,如果没有匹配则返回null
  9650. */
  9651. private function findMatchingName($generated_name, $expected_names) {
  9652. if (empty($generated_name)) {
  9653. return null;
  9654. }
  9655. // 尝试精确匹配
  9656. if (in_array($generated_name, $expected_names)) {
  9657. return $generated_name;
  9658. }
  9659. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  9660. foreach ($expected_names as $expected_name) {
  9661. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  9662. if (mb_strpos($expected_name, $generated_name) === 0) {
  9663. return $expected_name;
  9664. }
  9665. }
  9666. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  9667. // 这样可以处理一些变体,但优先级较低
  9668. foreach ($expected_names as $expected_name) {
  9669. if (mb_strpos($expected_name, $generated_name) !== false) {
  9670. return $expected_name;
  9671. }
  9672. }
  9673. return null;
  9674. }
  9675. /**
  9676. * 重新生成分段剧本
  9677. * @param array $data 包含以下字段:
  9678. * - prompt: string|null 用户修改要求(可选)
  9679. * - template_id: int|null 提示词模板ID(可选)
  9680. * - act_id: int|null 单个片段ID(与episode_id二选一)
  9681. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  9682. * @return array 返回生成结果
  9683. */
  9684. public function regenerateSegmentScript($data) {
  9685. $uid = Site::getUid();
  9686. $prompt = trim((string)getProp($data, 'prompt', ''));
  9687. $template_id = getProp($data, 'template_id', 0);
  9688. $act_id = getProp($data, 'act_id', 0);
  9689. $episode_id = getProp($data, 'episode_id', 0);
  9690. // 验证:prompt和template_id至少提供一个
  9691. if (empty($prompt) && empty($template_id)) {
  9692. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  9693. }
  9694. // 验证:act_id和episode_id二选一
  9695. if (empty($act_id) && empty($episode_id)) {
  9696. Utils::throwError('20003:请提供片段ID或剧集ID');
  9697. }
  9698. if (!empty($act_id) && !empty($episode_id)) {
  9699. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  9700. }
  9701. // 积分余额预检(仅剧集ID模式收费)
  9702. if (!empty($episode_id)) {
  9703. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  9704. }
  9705. // 如果提供了template_id,获取模板提示词
  9706. $template_prompt = '';
  9707. if ($template_id > 0) {
  9708. $template = DB::table('mp_prompt_templates')
  9709. ->where('id', $template_id)
  9710. ->where('is_deleted', 0)
  9711. ->first();
  9712. if (!$template) {
  9713. Utils::throwError('20003:提示词模板不存在或已删除');
  9714. }
  9715. $template_prompt = $template->template_prompt ?? '';
  9716. }
  9717. // 合并用户提示词和模板提示词
  9718. $final_prompt = '';
  9719. if (!empty($template_prompt)) {
  9720. $final_prompt = $template_prompt;
  9721. if (!empty($prompt)) {
  9722. $final_prompt .= "\n\n补充要求:" . $prompt;
  9723. }
  9724. } else {
  9725. $final_prompt = $prompt;
  9726. }
  9727. // 获取需要重新生成的内容参考
  9728. $reference_content = '';
  9729. $target_episode_id = 0;
  9730. $target_anime_id = 0;
  9731. $target_episode_number = 0;
  9732. if ($act_id > 0) {
  9733. // 单个片段模式:获取该片段的内容
  9734. $segment = DB::table('mp_episode_segments')
  9735. ->where('id', $act_id)
  9736. ->first();
  9737. if (!$segment) {
  9738. Utils::throwError('20003:片段不存在');
  9739. }
  9740. $target_episode_id = $segment->episode_id;
  9741. $target_anime_id = $segment->anime_id;
  9742. $target_episode_number = $segment->episode_number;
  9743. $reference_content = $segment->act_content ?? '';
  9744. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  9745. } else {
  9746. // 整个剧集模式:获取所有片段的内容
  9747. $segments = DB::table('mp_episode_segments')
  9748. ->where('episode_id', $episode_id)
  9749. ->orderBy('act_number')
  9750. ->get();
  9751. if ($segments->isEmpty()) {
  9752. Utils::throwError('20003:该剧集没有片段数据');
  9753. }
  9754. $target_episode_id = $episode_id;
  9755. $target_anime_id = $segments[0]->anime_id;
  9756. $target_episode_number = $segments[0]->episode_number;
  9757. // 拼接所有片段内容,保留格式用于AI理解
  9758. $act_contents = [];
  9759. foreach ($segments as $seg) {
  9760. $act_number = $seg->act_number;
  9761. $act_content = $seg->act_content ?? '';
  9762. if (!empty($act_content)) {
  9763. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  9764. }
  9765. }
  9766. $reference_content = implode("\n\n", $act_contents);
  9767. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  9768. if ($episode_content) {
  9769. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  9770. }else {
  9771. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  9772. }
  9773. }
  9774. if (empty($reference_content)) {
  9775. Utils::throwError('20003:没有可参考的片段内容');
  9776. }
  9777. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  9778. $episode = DB::table('mp_anime_episodes')
  9779. ->where('id', $target_episode_id)
  9780. ->first();
  9781. if (!$episode) {
  9782. Utils::throwError('20003:剧集不存在');
  9783. }
  9784. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  9785. $anime_script_id = getProp($anime, 'script_id');
  9786. $intro = $episode->intro ?? '';
  9787. $art_style = $episode->art_style ?? '';
  9788. $roles = json_decode($episode->roles ?? '[]', true);
  9789. $scenes = json_decode($episode->scenes ?? '[]', true);
  9790. $props = json_decode($episode->props ?? '[]', true);
  9791. // 构建提示词中的主体列表和场景列表参考
  9792. $roles_ref = '';
  9793. if (!empty($roles) && is_array($roles)) {
  9794. $roles_list = [];
  9795. foreach ($roles as $role) {
  9796. $role_name = getProp($role, 'role', '');
  9797. $role_desc = getProp($role, 'description', '');
  9798. $pic_prompt = getProp($role, 'pic_prompt', '');
  9799. $voice_prompt = getProp($role, 'voice_prompt', '');
  9800. if (!empty($role_name)) {
  9801. $role_line = $role_name;
  9802. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  9803. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  9804. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  9805. $roles_list[] = $role_line;
  9806. }
  9807. }
  9808. if (!empty($roles_list)) {
  9809. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  9810. }
  9811. }
  9812. $scenes_ref = '';
  9813. if (!empty($scenes) && is_array($scenes)) {
  9814. $scenes_list = [];
  9815. foreach ($scenes as $scene) {
  9816. $scene_name = getProp($scene, 'scene', '');
  9817. $scene_desc = getProp($scene, 'description', '');
  9818. $pic_prompt = getProp($scene, 'pic_prompt', '');
  9819. if (!empty($scene_name)) {
  9820. $scene_line = $scene_name;
  9821. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  9822. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  9823. $scenes_list[] = $scene_line;
  9824. }
  9825. }
  9826. if (!empty($scenes_list)) {
  9827. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  9828. }
  9829. }
  9830. $props_ref = '';
  9831. if (!empty($props) && is_array($props)) {
  9832. $props_list = [];
  9833. foreach ($props as $prop) {
  9834. $prop_name = getProp($prop, 'prop', '');
  9835. $prop_desc = getProp($prop, 'description', '');
  9836. $pic_prompt = getProp($prop, 'pic_prompt', '');
  9837. if (!empty($prop_name)) {
  9838. $prop_line = $prop_name;
  9839. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  9840. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  9841. $props_list[] = $prop_line;
  9842. }
  9843. }
  9844. if (!empty($props_list)) {
  9845. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  9846. }
  9847. }
  9848. // 构建美术风格参考
  9849. $art_style_ref = '';
  9850. if (!empty($art_style)) {
  9851. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  9852. }
  9853. // 构建内容简介参考
  9854. $intro_ref = '';
  9855. if (!empty($intro)) {
  9856. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  9857. }
  9858. // 构建完整的AI提示词
  9859. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  9860. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  9861. $user_prompt .= $intro_ref;
  9862. $user_prompt .= $art_style_ref;
  9863. $user_prompt .= $reference_content;
  9864. // $user_prompt .= $roles_ref;
  9865. // $user_prompt .= $scenes_ref;
  9866. $system_prompt = "\n\n【强制要求】\n";
  9867. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  9868. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  9869. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  9870. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  9871. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  9872. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  9873. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  9874. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  9875. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  9876. ###分段剧本
  9877. 片段数量:8
  9878. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9879. ##片段1
  9880. 时长:12s
  9881. 分镜1
  9882. 出场角色:刀疤脸
  9883. 场景:边境小镇街道
  9884. 出场道具:酒杯-高脚杯
  9885. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9886. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9887. 配音台词:
  9888. 背景音效:
  9889. 分镜2
  9890. 出场角色:刀疤脸
  9891. 场景:悦来酒馆
  9892. 出场道具:酒杯-高脚杯
  9893. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9894. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9895. 配音台词:
  9896. 背景音效:
  9897. 分镜3
  9898. 出场角色:刀疤脸
  9899. 场景:悦来酒馆
  9900. 出场道具:酒杯-高脚杯
  9901. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9902. 运镜:从中景推向令牌特写。
  9903. 配音台词:
  9904. 背景音效:
  9905. 分镜4
  9906. 出场角色:刀疤脸
  9907. 场景:悦来酒馆
  9908. 出场道具:酒杯-高脚杯
  9909. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9910. 运镜:极速推向酒水溅起的瞬间。
  9911. 配音台词:
  9912. 背景音效:
  9913. 分镜5
  9914. 出场角色:刀疤脸
  9915. 场景:悦来酒馆
  9916. 出场道具:酒杯-高脚杯
  9917. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9918. 运镜:固定机位,利用倾斜构图制造压迫感。
  9919. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9920. 背景音效:";
  9921. // 获取模型配置
  9922. $model = getProp($data, 'model');
  9923. if (!$model) {
  9924. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  9925. }
  9926. // 验证模型是否在可用模型表中
  9927. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9928. $model = 'deepseek-v4-pro';
  9929. }
  9930. // 模型兼容性处理
  9931. $thinkingMode = 'disabled';
  9932. $reasoningEffort = 'high';
  9933. if ($model === 'deepseek-chat') {
  9934. $model = 'deepseek-v4-flash';
  9935. $thinkingMode = 'disabled';
  9936. } elseif ($model === 'deepseek-reasoner') {
  9937. $model = 'deepseek-v4-flash';
  9938. $thinkingMode = 'enabled';
  9939. }
  9940. // 构建消息
  9941. $messages = [
  9942. [
  9943. 'role' => 'system',
  9944. 'content' => $system_prompt
  9945. ],
  9946. [
  9947. 'role' => 'user',
  9948. 'content' => $user_prompt
  9949. ]
  9950. ];
  9951. // dd($messages);
  9952. // 构建请求参数
  9953. $post_data = [
  9954. 'model' => $model,
  9955. 'messages' => $messages,
  9956. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9957. 'frequency_penalty' => 0,
  9958. 'presence_penalty' => 0,
  9959. 'response_format' => ['type' => 'text'],
  9960. 'thinking' => ['type' => $thinkingMode],
  9961. 'stream' => false // 非流式输出
  9962. ];
  9963. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9964. // 调用AI生成新的分段剧本
  9965. try {
  9966. $fullContent = '';
  9967. $usage = [];
  9968. // 根据模型类型选择调用方法
  9969. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9970. // DeepSeek 官方模型使用 DeepSeek API
  9971. $chatResult = $this->chatOnly($post_data);
  9972. } else if (in_array($model, $this->gpt_text_models)) {
  9973. // GPT 模型使用 TokenRouter API
  9974. $chatResult = $this->gpt54ChatOnly($post_data);
  9975. } else {
  9976. // 其他模型使用火山引擎API
  9977. $chatResult = $this->volcEngineChatCompletion($post_data);
  9978. }
  9979. if (is_array($chatResult)) {
  9980. $fullContent = $chatResult['fullContent'] ?? '';
  9981. $usage = $chatResult['usage'] ?? [];
  9982. }
  9983. $generated_content = $fullContent;
  9984. if (empty($generated_content)) {
  9985. Utils::throwError('20003:AI生成内容为空,请重试');
  9986. }
  9987. // 解析生成的内容 - 按片段分割
  9988. $parsed_segments = [];
  9989. // 先在开头添加换行符,确保第1片段也能被正确分割
  9990. $normalizedText = "\n" . $generated_content;
  9991. $parts = preg_split('/\n\s*##/', $normalizedText);
  9992. foreach ($parts as $part) {
  9993. $part = trim($part);
  9994. if (empty($part)) continue;
  9995. // 匹配"片段X"格式
  9996. if (!preg_match('/^片段\d+/', $part)) {
  9997. continue;
  9998. }
  9999. // 分离标题和内容
  10000. $lines = explode("\n", $part, 2);
  10001. $actTitle = trim($lines[0]);
  10002. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  10003. // 解析标题,提取序号
  10004. $actNumber = 0;
  10005. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  10006. $actNumber = intval($segmentTitleMatch[1]);
  10007. } else {
  10008. $actNumber = count($parsed_segments) + 1;
  10009. }
  10010. // 提取时长(仅保留数字)
  10011. $actDuration = 0;
  10012. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  10013. $actDurationStr = trim($actDurationMatch[1]);
  10014. // 提取数字部分(支持整数和小数)
  10015. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  10016. $actDuration = (float)$numMatch[1];
  10017. }
  10018. }
  10019. // 清理act_content:去除时长、旁白音色等非分镜内容行
  10020. // 只保留分镜内容,并确保分镜标记使用【】格式
  10021. $cleaned_content = '';
  10022. $content_lines = explode("\n", $actContent);
  10023. $is_capturing = false; // 标记是否开始捕获分镜内容
  10024. $count = 0;
  10025. foreach ($content_lines as $line) {
  10026. $trimmed_line = trim($line);
  10027. // 跳过时长和旁白音色行
  10028. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  10029. continue;
  10030. }
  10031. // 检测是否是分镜开始
  10032. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  10033. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  10034. $count++;
  10035. $is_capturing = true;
  10036. // 如果没有【】,则添加
  10037. if (!preg_match('/^【/u', $trimmed_line)) {
  10038. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  10039. }
  10040. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  10041. }
  10042. // 如果已经开始捕获,则添加该行
  10043. if ($is_capturing && !empty($trimmed_line)) {
  10044. $cleaned_content .= $trimmed_line."\n";
  10045. }
  10046. }
  10047. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  10048. $parsed_segments[] = [
  10049. 'act_number' => $actNumber,
  10050. 'act_title' => $actTitle,
  10051. 'act_duration' => $actDuration,
  10052. 'act_content' => $cleaned_content,
  10053. ];
  10054. }
  10055. if (empty($parsed_segments)) {
  10056. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  10057. }
  10058. // 收集所有资产名称(角色、场景、道具)
  10059. $product_names = [];
  10060. // 收集角色名称
  10061. if (!empty($roles) && is_array($roles)) {
  10062. foreach ($roles as $role) {
  10063. $role_name = getProp($role, 'role', '');
  10064. if (!empty($role_name)) {
  10065. $product_names[] = $role_name;
  10066. }
  10067. }
  10068. }
  10069. // 收集场景名称
  10070. if (!empty($scenes) && is_array($scenes)) {
  10071. foreach ($scenes as $scene) {
  10072. $scene_name = getProp($scene, 'scene', '');
  10073. if (!empty($scene_name)) {
  10074. $product_names[] = $scene_name;
  10075. }
  10076. }
  10077. }
  10078. // 收集道具名称
  10079. if (!empty($props) && is_array($props)) {
  10080. foreach ($props as $prop) {
  10081. $prop_name = getProp($prop, 'prop', '');
  10082. if (!empty($prop_name)) {
  10083. $product_names[] = $prop_name;
  10084. }
  10085. }
  10086. }
  10087. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  10088. $product_names = array_unique($product_names);
  10089. usort($product_names, function($a, $b) {
  10090. return mb_strlen($b) - mb_strlen($a);
  10091. });
  10092. // 处理每个片段的 act_show_content
  10093. foreach ($parsed_segments as &$segment) {
  10094. $act_content = getProp($segment, 'act_content', '');
  10095. if (empty($act_content)) {
  10096. $segment['act_show_content'] = '';
  10097. continue;
  10098. }
  10099. $processed_content = $act_content;
  10100. // 统一替换所有资产名称为 {资产名} 格式
  10101. // 使用占位符避免嵌套替换问题
  10102. $placeholder_map = [];
  10103. $placeholder_index = 0;
  10104. foreach ($product_names as $product_name) {
  10105. // 转义特殊字符
  10106. $escaped_product = preg_quote($product_name, '/');
  10107. // 检查是否匹配且未被 {} 包裹
  10108. $processed_content = preg_replace_callback(
  10109. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  10110. function($matches) use (&$placeholder_map, &$placeholder_index) {
  10111. // 使用唯一占位符
  10112. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  10113. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  10114. $placeholder_index++;
  10115. return $placeholder;
  10116. },
  10117. $processed_content
  10118. );
  10119. }
  10120. // 将所有占位符替换回实际内容
  10121. foreach ($placeholder_map as $placeholder => $replacement) {
  10122. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  10123. }
  10124. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  10125. $shot_counter = 0;
  10126. $processed_content = preg_replace_callback(
  10127. '/【(?:镜头|分镜)(\d+)】/u',
  10128. function($matches) use (&$shot_counter) {
  10129. $shot_counter++;
  10130. return '【镜头' . $shot_counter . '】';
  10131. },
  10132. $processed_content
  10133. );
  10134. $segment['act_show_content'] = $processed_content;
  10135. }
  10136. unset($segment); // 解除引用
  10137. // 保存到数据库
  10138. $now = date('Y-m-d H:i:s');
  10139. $saved_acts = []; // 用于记录保存后的片段信息
  10140. if ($act_id > 0) {
  10141. // 单个片段模式:更新单条记录
  10142. if (count($parsed_segments) > 0) {
  10143. $new_segment = $parsed_segments[0];
  10144. $update_data = [
  10145. 'act_content' => getProp($new_segment, 'act_content', ''),
  10146. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  10147. 'act_title' => getProp($new_segment, 'act_title', ''),
  10148. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  10149. 'updated_at' => $now,
  10150. ];
  10151. DB::table('mp_episode_segments')
  10152. ->where('id', $act_id)
  10153. ->update($update_data);
  10154. // 获取更新后的记录
  10155. $updated_act = DB::table('mp_episode_segments')
  10156. ->where('id', $act_id)
  10157. ->first();
  10158. if ($updated_act) {
  10159. $saved_acts[] = [
  10160. 'act_id' => $updated_act->id,
  10161. 'act_number' => $updated_act->act_number,
  10162. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  10163. 'act_content' => $updated_act->act_content,
  10164. 'act_show_content' => $updated_act->act_show_content,
  10165. 'video_url' => $updated_act->video_url ?? '',
  10166. 'video_duration' => $updated_act->video_duration ?? 0,
  10167. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  10168. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  10169. ];
  10170. }
  10171. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  10172. }
  10173. } else {
  10174. // 整个剧集模式:删除原有记录并批量保存新记录
  10175. DB::beginTransaction();
  10176. try {
  10177. // 删除原有的所有片段记录
  10178. DB::table('mp_episode_segments')
  10179. ->where('episode_id', $target_episode_id)
  10180. ->delete();
  10181. // 批量插入新的片段记录
  10182. $segments_to_insert = [];
  10183. foreach ($parsed_segments as $index => $segment) {
  10184. $act_number = $index + 1;
  10185. $segments_to_insert[] = [
  10186. 'anime_id' => $target_anime_id,
  10187. 'episode_id' => $target_episode_id,
  10188. 'episode_number' => $target_episode_number,
  10189. 'act_number' => $act_number,
  10190. 'act_title' => getProp($segment, 'act_title', ''),
  10191. 'act_duration' => getProp($segment, 'act_duration', 0),
  10192. 'act_content' => getProp($segment, 'act_content', ''),
  10193. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  10194. 'created_at' => $now,
  10195. 'updated_at' => $now,
  10196. ];
  10197. }
  10198. if (!empty($segments_to_insert)) {
  10199. DB::table('mp_episode_segments')->insert($segments_to_insert);
  10200. }
  10201. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  10202. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  10203. 'anime_id' => $target_anime_id,
  10204. 'episode_id' => $target_episode_id,
  10205. ]);
  10206. DB::commit();
  10207. // 查询保存后的所有片段记录
  10208. $saved_segments = DB::table('mp_episode_segments')
  10209. ->where('episode_id', $target_episode_id)
  10210. ->orderBy('act_number')
  10211. ->get();
  10212. foreach ($saved_segments as $saved_segment) {
  10213. $saved_acts[] = [
  10214. 'act_id' => $saved_segment->id,
  10215. 'act_number' => $saved_segment->act_number,
  10216. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  10217. 'act_content' => $saved_segment->act_content,
  10218. 'act_show_content' => $saved_segment->act_show_content,
  10219. 'video_url' => $saved_segment->video_url ?? '',
  10220. 'video_duration' => $saved_segment->video_duration ?? 0,
  10221. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  10222. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  10223. ];
  10224. }
  10225. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  10226. 'episode_id' => $target_episode_id,
  10227. 'segments_count' => count($segments_to_insert)
  10228. ]);
  10229. } catch (\Exception $e) {
  10230. DB::rollBack();
  10231. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  10232. Utils::throwError('20003:保存失败,请重试');
  10233. }
  10234. }
  10235. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  10236. return [
  10237. 'anime_id' => $target_anime_id,
  10238. 'episode_id' => $target_episode_id,
  10239. 'title' => getProp($episode, 'title', ''),
  10240. 'episode_number' => $target_episode_number,
  10241. 'is_generated' => getProp($episode, 'is_generated', 0),
  10242. 'acts' => $saved_acts,
  10243. ];
  10244. } catch (\Exception $e) {
  10245. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  10246. throw $e;
  10247. }
  10248. }
  10249. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  10250. {
  10251. $episode_arr = [
  10252. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  10253. 'intro' => getProp($script_arr, 'intro'),
  10254. 'art_style' => getProp($script_arr, 'art_style'),
  10255. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  10256. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  10257. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  10258. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  10259. ];
  10260. if (empty($episode_arr['acts'])) {
  10261. $fallback_episode_arr = handleEpisodeContent($fullContent);
  10262. if (!empty($fallback_episode_arr['acts'])) {
  10263. $episode_arr = array_merge($fallback_episode_arr, [
  10264. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  10265. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  10266. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  10267. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  10268. ]);
  10269. }
  10270. }
  10271. // if (!getProp($episode_arr, 'episode_title')) {
  10272. // $episode_title = '';
  10273. // $episodes = getProp($script_arr, 'episodes', []);
  10274. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  10275. // $episode_title = '第1集:' . $episodes[0]['title'];
  10276. // }
  10277. // if (!$episode_title) {
  10278. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  10279. // }
  10280. // $episode_arr['episode_title'] = $episode_title;
  10281. // }
  10282. return $episode_arr;
  10283. }
  10284. private function saveEpisodeVersionData(
  10285. int $anime_id,
  10286. int $episode_number,
  10287. array $episode_arr,
  10288. array $existing_roles,
  10289. array $existing_scenes,
  10290. array $existing_props,
  10291. $current_episode,
  10292. $base_episode,
  10293. bool $is_regenerate_version,
  10294. string $content,
  10295. string $now,
  10296. array $ref_products = []
  10297. ): array {
  10298. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  10299. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  10300. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  10301. // 过滤掉关键字段为空的条目
  10302. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  10303. return !empty($item['role'] ?? null);
  10304. }));
  10305. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  10306. return !empty($item['scene'] ?? null);
  10307. }));
  10308. $merged_props = array_values(array_filter($generated_props, function ($item) {
  10309. return !empty($item['prop'] ?? null);
  10310. }));
  10311. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  10312. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  10313. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  10314. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10315. $ace_mode = getProp($anime, 'ace_mode');
  10316. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  10317. $global_roles = json_decode(getProp($anime, 'roles'), true);
  10318. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  10319. $global_roles = is_array($global_roles) ? $global_roles : [];
  10320. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  10321. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  10322. $art_style_type = getProp($anime, 'art_style_type');
  10323. // 检查并创建 roles 的图片生成任务
  10324. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  10325. // 检查并创建 scenes 的图片生成任务
  10326. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  10327. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  10328. if ($arr && is_array($arr)) {
  10329. $merged_roles = $arr['roles'];
  10330. $merged_scenes = $arr['scenes'];
  10331. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  10332. }
  10333. // 确保数据是数组类型
  10334. if (!is_array($merged_roles)) {
  10335. dLog('deepseek')->error('merged_roles不是数组类型', [
  10336. 'type' => gettype($merged_roles),
  10337. 'value' => $merged_roles
  10338. ]);
  10339. $merged_roles = [];
  10340. }
  10341. if (!is_array($merged_scenes)) {
  10342. dLog('deepseek')->error('merged_scenes不是数组类型', [
  10343. 'type' => gettype($merged_scenes),
  10344. 'value' => $merged_scenes
  10345. ]);
  10346. $merged_scenes = [];
  10347. }
  10348. if (!is_array($merged_props)) {
  10349. dLog('deepseek')->error('merged_props不是数组类型', [
  10350. 'type' => gettype($merged_props),
  10351. 'value' => $merged_props
  10352. ]);
  10353. $merged_props = [];
  10354. }
  10355. // 同步新出现的主体和场景到全局
  10356. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  10357. $role_arr = [];
  10358. foreach ($merged_roles as $item) {
  10359. $role_arr[$item['role']] = $item;
  10360. }
  10361. $version_count = DB::table('mp_anime_episodes')
  10362. ->where('anime_id', $anime_id)
  10363. ->where('episode_number', $episode_number)
  10364. ->count('id');
  10365. $episode = [
  10366. 'anime_id' => $anime_id,
  10367. 'episode_number' => $episode_number,
  10368. 'title' => getProp($episode_arr, 'episode_title'),
  10369. 'content' => $content,
  10370. 'intro' => getProp($episode_arr, 'intro'),
  10371. 'art_style' => getProp($episode_arr, 'art_style'),
  10372. 'roles' => json_encode($merged_roles, 256),
  10373. 'scenes' => json_encode($merged_scenes, 256),
  10374. 'props' => json_encode($merged_props, 256),
  10375. 'generate_status' => '待执行',
  10376. 'generate_at' => $now,
  10377. 'is_default' => 1,
  10378. 'updated_at' => $now,
  10379. ];
  10380. $del_flag = false;
  10381. if ($is_regenerate_version) {
  10382. DB::table('mp_anime_episodes')
  10383. ->where('anime_id', $anime_id)
  10384. ->where('episode_number', $episode_number)
  10385. ->update(['is_default' => 0, 'updated_at' => $now]);
  10386. $episode['sequence'] = $version_count + 1;
  10387. $episode['created_at'] = $now;
  10388. $episode['cpid'] = Site::getCpid();
  10389. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  10390. if (!$episode_id) {
  10391. Utils::throwError('20003:创建剧集版本失败');
  10392. }
  10393. } else {
  10394. $target_episode = $current_episode ?: $base_episode;
  10395. if ($target_episode) {
  10396. $episode_id = getProp($target_episode, 'id');
  10397. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  10398. DB::table('mp_anime_episodes')
  10399. ->where('anime_id', $anime_id)
  10400. ->where('episode_number', $episode_number)
  10401. ->where('id', '<>', $episode_id)
  10402. ->update(['is_default' => 0, 'updated_at' => $now]);
  10403. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  10404. if ($boolen === false) {
  10405. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  10406. Utils::throwError('20003:分集内容保存失败');
  10407. }
  10408. $del_flag = true;
  10409. } else {
  10410. DB::table('mp_anime_episodes')
  10411. ->where('anime_id', $anime_id)
  10412. ->where('episode_number', $episode_number)
  10413. ->update(['is_default' => 0, 'updated_at' => $now]);
  10414. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  10415. $episode['created_at'] = $now;
  10416. $episode['cpid'] = Site::getCpid();
  10417. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  10418. if (!$episode_id) {
  10419. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  10420. Utils::throwError('20003:分集内容保存失败');
  10421. }
  10422. }
  10423. }
  10424. $segments = [];
  10425. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  10426. // 如果是第2集及以后,获取上一集的主体音色数据
  10427. $previous_roles_voice = [];
  10428. if ($episode_number >= 2) {
  10429. $previous_episode = DB::table('mp_anime_episodes')
  10430. ->where('anime_id', $anime_id)
  10431. ->where('episode_number', $episode_number - 1)
  10432. ->where('is_default', 1)
  10433. ->first();
  10434. if ($previous_episode) {
  10435. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  10436. if (is_array($previous_roles)) {
  10437. foreach ($previous_roles as $prev_role) {
  10438. $role_name = getProp($prev_role, 'role');
  10439. if ($role_name) {
  10440. $previous_roles_voice[$role_name] = [
  10441. 'voice_name' => getProp($prev_role, 'voice_name'),
  10442. 'voice_type' => getProp($prev_role, 'voice_type'),
  10443. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  10444. ];
  10445. $voice_prompt = getProp($prev_role, 'voice_prompt');
  10446. if ($voice_prompt) {
  10447. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  10448. }
  10449. }
  10450. }
  10451. }
  10452. }
  10453. }
  10454. // 将继承的音色数据同步到当前集的主体列表
  10455. if (!empty($previous_roles_voice)) {
  10456. foreach ($merged_roles as &$role) {
  10457. $role_name = getProp($role, 'role');
  10458. if ($role_name && isset($previous_roles_voice[$role_name])) {
  10459. // 强制继承上一集的音色数据
  10460. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  10461. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  10462. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  10463. // 如果上一集有 voice_prompt 则继承,否则跳过
  10464. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  10465. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  10466. }
  10467. }
  10468. }
  10469. unset($role); // 解除引用
  10470. // 更新 role_arr 以便后续使用
  10471. $role_arr = [];
  10472. foreach ($merged_roles as $item) {
  10473. $role_arr[$item['role']] = $item;
  10474. }
  10475. }
  10476. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  10477. $emotion_list = array_flip($emotion_list);
  10478. foreach ($acts as $act) {
  10479. $act_segments = getProp($act, 'segments', []);
  10480. if (!is_array($act_segments)) {
  10481. continue;
  10482. }
  10483. if ((int)$ace_mode === 1) {
  10484. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  10485. $merged_parts = [];
  10486. foreach ($act_segments as $seg) {
  10487. $seg_num = getProp($seg, 'segment_number');
  10488. $seg_content = getProp($seg, 'segment_content');
  10489. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  10490. }
  10491. $act_content = implode("\n", $merged_parts);
  10492. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  10493. $segments[] = [
  10494. 'anime_id' => $anime_id,
  10495. 'episode_id' => $episode_id,
  10496. 'episode_number' => $episode_number,
  10497. 'act_number' => getProp($act, 'act_number'),
  10498. 'act_title' => getProp($act, 'act_title'),
  10499. 'act_duration' => getProp($act, 'act_duration'),
  10500. 'act_content' => $act_content,
  10501. 'created_at' => $now,
  10502. 'updated_at' => $now
  10503. ];
  10504. } else {
  10505. foreach ($act_segments as $segment) {
  10506. $voice_actor = getProp($segment, 'voice_actor');
  10507. // 优先从上一集继承音色数据
  10508. $timbre_info = [];
  10509. if (isset($previous_roles_voice[$voice_actor])) {
  10510. // 从上一集继承音色数据
  10511. $timbre_info = $previous_roles_voice[$voice_actor];
  10512. } elseif (isset($role_arr[$voice_actor])) {
  10513. // 使用当前集的主体音色数据
  10514. $timbre_info = $role_arr[$voice_actor];
  10515. }
  10516. $voice_type = getProp($timbre_info, 'voice_type');
  10517. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  10518. if ($timbre_emotion) {
  10519. $timbre_emotion = explode(',', $timbre_emotion);
  10520. } else {
  10521. $timbre_emotion = [];
  10522. }
  10523. $emotion = getProp($segment, 'emotion', '中性');
  10524. if (!in_array($emotion, $timbre_emotion)) {
  10525. $emotion = '中性';
  10526. }
  10527. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  10528. $segments[] = [
  10529. 'anime_id' => $anime_id,
  10530. 'episode_id' => $episode_id,
  10531. 'episode_number' => $episode_number,
  10532. 'act_number' => getProp($act, 'act_number'),
  10533. 'act_title' => getProp($act, 'act_title'),
  10534. 'act_duration' => getProp($act, 'act_duration'),
  10535. 'segment_id' => getProp($segment, 'segment_id'),
  10536. 'segment_number' => getProp($segment, 'segment_number'),
  10537. 'segment_content' => getProp($segment, 'segment_content'),
  10538. 'description' => getProp($segment, 'description'),
  10539. 'composition' => getProp($segment, 'composition'),
  10540. 'camera_movement' => getProp($segment, 'camera_movement'),
  10541. 'voice_actor' => $voice_actor,
  10542. 'dialogue' => getProp($segment, 'dialogue'),
  10543. 'frame_type' => getProp($segment, 'frame_type'),
  10544. 'scene' => getProp($segment, 'scene'),
  10545. 'characters' => getProp($segment, 'characters'),
  10546. 'tail_frame' => getProp($segment, 'tail_frame'),
  10547. 'voice_name' => getProp($timbre_info, 'voice_name'),
  10548. 'voice_type' => $voice_type,
  10549. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  10550. 'emotion' => $emotion,
  10551. 'emotion_type' => $emotion_type,
  10552. 'gender' => getProp($segment, 'gender', '0'),
  10553. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  10554. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  10555. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  10556. 'pitch' => getProp($segment, 'pitch', 0),
  10557. 'created_at' => $now,
  10558. 'updated_at' => $now
  10559. ];
  10560. }
  10561. }
  10562. }
  10563. if ($segments) {
  10564. if ($del_flag) {
  10565. DB::table('mp_episode_segments')
  10566. ->where('anime_id', $anime_id)
  10567. ->where('episode_id', $episode_id)
  10568. ->delete();
  10569. }
  10570. $boolen = DB::table('mp_episode_segments')->insert($segments);
  10571. if (!$boolen) {
  10572. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  10573. Utils::throwError('20003:分镜内容保存失败');
  10574. }
  10575. }
  10576. dLog('deepseek')->info('segments', $segments);
  10577. // ace_mode=1: acts 返回值按合并格式调整
  10578. if ((int)$ace_mode === 1) {
  10579. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  10580. $act_map = [];
  10581. foreach ($table_act_data as $item) {
  10582. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  10583. }
  10584. $restructured_acts = [];
  10585. foreach ($acts as $act) {
  10586. $act_segments = getProp($act, 'segments', []);
  10587. if (!is_array($act_segments)) {
  10588. continue;
  10589. }
  10590. $merged_parts = [];
  10591. foreach ($act_segments as $seg) {
  10592. $seg_num = getProp($seg, 'segment_number');
  10593. $seg_content = getProp($seg, 'segment_content');
  10594. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  10595. }
  10596. $act_content = implode("\n", $merged_parts);
  10597. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  10598. $restructured_acts[] = [
  10599. 'anime_id' => $anime_id,
  10600. 'episode_id' => $episode_id,
  10601. 'episode_number' => $episode_number,
  10602. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  10603. 'act_number' => getProp($act, 'act_number'),
  10604. 'act_title' => getProp($act, 'act_title'),
  10605. 'act_duration' => getProp($act, 'act_duration'),
  10606. 'act_content' => $act_content,
  10607. 'created_at' => $now,
  10608. 'updated_at' => $now,
  10609. ];
  10610. }
  10611. $acts = $restructured_acts;
  10612. }
  10613. $episode['episode_id'] = $episode_id;
  10614. $episode['roles'] = $merged_roles;
  10615. $episode['scenes'] = $merged_scenes;
  10616. $episode['props'] = $merged_props;
  10617. $episode['acts'] = $acts;
  10618. return [
  10619. 'episode' => $episode,
  10620. 'episode_id' => $episode_id,
  10621. 'merged_roles' => $merged_roles,
  10622. 'merged_scenes' => $merged_scenes,
  10623. 'merged_props' => $merged_props,
  10624. ];
  10625. }
  10626. private function buildEpisodeItemContent(array $items, string $nameKey): string
  10627. {
  10628. $content = '';
  10629. foreach ($items as $item) {
  10630. $name = trim((string)getProp($item, $nameKey));
  10631. if ($name === '' || $name === '旁白') {
  10632. continue;
  10633. }
  10634. $description = trim((string)getProp($item, 'description'));
  10635. $content .= $name . ': ' . $description;
  10636. if ($nameKey == 'role') {
  10637. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  10638. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10639. $voice_name = trim(getProp($item, 'voice_name'));
  10640. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  10641. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  10642. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  10643. }else {
  10644. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  10645. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10646. }
  10647. $content .= "\n";
  10648. }
  10649. return trim($content);
  10650. }
  10651. private function getEpisodeChatContent($animeId, $sequence, $content) {
  10652. if ((int)$sequence <= 0) {
  10653. return [];
  10654. }
  10655. $origin_content = '';
  10656. if ($content) {
  10657. $origin_content = '本集剧情内容:'.$content;
  10658. }else {
  10659. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  10660. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  10661. }
  10662. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  10663. // 获取分集信息
  10664. $episode = DB::table('mp_anime_episodes')
  10665. ->where('anime_id', $animeId)
  10666. ->where('episode_number', $sequence)
  10667. ->where('is_default', 1)
  10668. ->first();
  10669. if (!$episode) {
  10670. return [];
  10671. }
  10672. $episode_id = getProp($episode, 'id');
  10673. $episode_number = getProp($episode, 'episode_number');
  10674. $title = getProp($episode, 'title');
  10675. $intro = getProp($episode, 'intro');
  10676. $art_style = getProp($episode, 'art_style');
  10677. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10678. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10679. // 组装纯文本内容
  10680. $content = '';
  10681. // 添加分集标题和梗概
  10682. $content .= "###第{$episode_number}集:{$title}\n\n";
  10683. $content .= "###故事梗概\n";
  10684. $content .= trim($intro) . "\n\n";
  10685. // 添加美术风格
  10686. $content .= "###美术风格\n";
  10687. $content .= trim($art_style) . "\n\n";
  10688. // 添加主体列表
  10689. $content .= "###主体列表\n";
  10690. $pangbai_voice_prompt = "";
  10691. foreach ($roles as $role) {
  10692. $name = getProp($role, 'role');
  10693. $description = getProp($role, 'description');
  10694. $pic_prompt = getProp($role, 'pic_prompt');
  10695. $voice_prompt = getProp($role, 'voice_prompt');
  10696. $voice_name = getProp($role, 'voice_name');
  10697. $content .= "{$name}: {$description}";
  10698. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10699. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  10700. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  10701. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  10702. $content .= "\n";
  10703. }
  10704. $content .= "\n";
  10705. // 添加场景列表
  10706. $content .= "###场景列表\n";
  10707. foreach ($scenes as $scene) {
  10708. $name = getProp($scene, 'scene');
  10709. $description = getProp($scene, 'description');
  10710. $pic_prompt = getProp($scene, 'pic_prompt');
  10711. $content .= "{$name}: {$description}";
  10712. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10713. $content .= "\n";
  10714. }
  10715. $content .= "\n";
  10716. // 获取分镜信息
  10717. $segments = DB::table('mp_episode_segments')
  10718. ->where('anime_id', $animeId)
  10719. ->where('episode_id', $episode_id)
  10720. ->orderBy('segment_number')
  10721. ->get();
  10722. if ($segments && count($segments) > 0) {
  10723. if ((int)$ace_mode === 1) {
  10724. $content .= "###分段剧本\n";
  10725. // 获取片段数量
  10726. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  10727. $content .= "片段数量:{$act_count}\n";
  10728. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  10729. $content .= "\n";
  10730. }else {
  10731. $content .= "###分镜剧本\n";
  10732. }
  10733. // 按幕分组
  10734. $currentAct = null;
  10735. foreach ($segments as $segment) {
  10736. $act_number = getProp($segment, 'act_number');
  10737. $act_title = getProp($segment, 'act_title');
  10738. $act_duration = getProp($segment, 'act_duration');
  10739. $segment_number = getProp($segment, 'segment_number');
  10740. $segment_content = getProp($segment, 'segment_content');
  10741. $scene_description = getProp($segment, 'scene_description');
  10742. $scene_name = getProp($segment, 'scene_name');
  10743. $composition = getProp($segment, 'composition');
  10744. $camera_movement = getProp($segment, 'camera_movement');
  10745. $voice_type = getProp($segment, 'voice_type');
  10746. $characters = getProp($segment, 'characters');
  10747. $dialogue = getProp($segment, 'dialogue');
  10748. $frame_type = getProp($segment, 'frame_type');
  10749. $tail_frame_description = getProp($segment, 'tail_frame_description');
  10750. // 判断是否是全能模式
  10751. if ((int)$ace_mode === 1) { // 全能模式
  10752. // 如果是新的分段,添加分段标题
  10753. if ($act_number !== $currentAct) {
  10754. $currentAct = $act_number;
  10755. $content .= "##{$act_title}\n";
  10756. $content .= "时长:{$act_duration}s\n";
  10757. }
  10758. }else {
  10759. // 如果是新的幕,添加幕标题
  10760. if ($act_number !== $currentAct) {
  10761. $currentAct = $act_number;
  10762. $content .= "##第{$act_number}幕:{$scene_name}\n";
  10763. }
  10764. }
  10765. // 添加分镜信息
  10766. $content .= "分镜{$segment_number}\n";
  10767. $content .= "分镜内容:\n{$segment_content}\n";
  10768. // $content .= "画面描述:{$scene_description}\n";
  10769. // $content .= "场景:{$scene_name}\n";
  10770. // $content .= "构图设计:{$composition}\n";
  10771. // $content .= "运镜调度:{$camera_movement}\n";
  10772. // if (!empty($voice_type)) {
  10773. // $content .= "配音角色:{$voice_type}\n";
  10774. // }
  10775. // if (!empty($characters)) {
  10776. // $content .= "出镜角色:{$characters}\n";
  10777. // }
  10778. // if (!empty($dialogue)) {
  10779. // $content .= "台词内容:\"{$dialogue}\"\n";
  10780. // }
  10781. // $content .= "画面类型:{$frame_type}\n";
  10782. // $content .= "尾帧描述:{$tail_frame_description}\n";
  10783. $content .= "\n";
  10784. }
  10785. }
  10786. $content = trim($content);
  10787. if($content) $content = "上集剧本内容:\n{$content}";
  10788. return [
  10789. [
  10790. 'role' => 'user',
  10791. 'content' => $origin_content
  10792. ],
  10793. [
  10794. 'role' => 'assistant',
  10795. 'content' => $content
  10796. ]
  10797. ];
  10798. }
  10799. private function getEpisodeChatMessages($animeId, $sequence): array
  10800. {
  10801. if ((int)$sequence <= 0) {
  10802. return [];
  10803. }
  10804. return DB::table('mp_anime_records')
  10805. ->where('anime_id', $animeId)
  10806. ->where('sequence', $sequence)
  10807. ->where('episode_id', '>', 0)
  10808. ->select('role', 'content')
  10809. ->orderBy('created_at')
  10810. ->orderBy('id')
  10811. ->get()
  10812. ->map(function ($value) {
  10813. return (array)$value;
  10814. })
  10815. ->toArray();
  10816. }
  10817. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  10818. {
  10819. $existingMap = [];
  10820. foreach ($existingItems as $item) {
  10821. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  10822. if ($itemKey === '') {
  10823. continue;
  10824. }
  10825. $existingMap[$itemKey] = $item;
  10826. }
  10827. if (!$generatedItems) {
  10828. return array_values($existingItems);
  10829. }
  10830. $merged = [];
  10831. foreach ($generatedItems as $item) {
  10832. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  10833. if ($itemKey === '') {
  10834. continue;
  10835. }
  10836. if (isset($existingMap[$itemKey])) {
  10837. if (trim((string)getProp($item, 'description')) === '') {
  10838. $merged[] = $existingMap[$itemKey];
  10839. continue;
  10840. }
  10841. // 检查内容是否发生变化
  10842. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  10843. if (!$isChanged) {
  10844. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  10845. $mergedItem = [
  10846. $nameKey => trim((string)getProp($item, $nameKey)),
  10847. 'description' => trim((string)getProp($item, 'description')),
  10848. ];
  10849. // 如果有 pic_prompt,添加到合并项中
  10850. $picPrompt = getProp($item, 'pic_prompt');
  10851. if (!empty($picPrompt)) {
  10852. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  10853. }
  10854. // 继承现有项的 URL
  10855. $existingUrl = getProp($existingMap[$itemKey], 'url');
  10856. if (!empty($existingUrl)) {
  10857. $mergedItem['url'] = $existingUrl;
  10858. }
  10859. // 继承现有项的 task_id
  10860. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  10861. if (!empty($existingTaskId)) {
  10862. $mergedItem['task_id'] = $existingTaskId;
  10863. }
  10864. // 继承现有项的 task_status
  10865. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  10866. if (!empty($existingTaskStatus)) {
  10867. $mergedItem['task_status'] = $existingTaskStatus;
  10868. }
  10869. // 保留生成项的音色字段
  10870. $voiceName = getProp($item, 'voice_name');
  10871. if (!empty($voiceName)) {
  10872. $mergedItem['voice_name'] = $voiceName;
  10873. }
  10874. $voiceType = getProp($item, 'voice_type');
  10875. if (!empty($voiceType)) {
  10876. $mergedItem['voice_type'] = $voiceType;
  10877. }
  10878. $audioUrl = getProp($item, 'voice_audio_url');
  10879. if (!empty($audioUrl)) {
  10880. $mergedItem['voice_audio_url'] = $audioUrl;
  10881. }
  10882. $merged[] = $mergedItem;
  10883. } else {
  10884. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  10885. $mergedItem = [
  10886. $nameKey => trim((string)getProp($item, $nameKey)),
  10887. 'description' => trim((string)getProp($item, 'description')),
  10888. ];
  10889. // 如果有 pic_prompt,添加到合并项中
  10890. $picPrompt = getProp($item, 'pic_prompt');
  10891. if (!empty($picPrompt)) {
  10892. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  10893. }
  10894. // 保留生成项的音色字段
  10895. $voiceName = getProp($item, 'voice_name');
  10896. if (!empty($voiceName)) {
  10897. $mergedItem['voice_name'] = $voiceName;
  10898. }
  10899. $voiceType = getProp($item, 'voice_type');
  10900. if (!empty($voiceType)) {
  10901. $mergedItem['voice_type'] = $voiceType;
  10902. }
  10903. $audioUrl = getProp($item, 'voice_audio_url');
  10904. if (!empty($audioUrl)) {
  10905. $mergedItem['voice_audio_url'] = $audioUrl;
  10906. }
  10907. // 不继承 URL、task_id 和 task_status(重置状态)
  10908. $merged[] = $mergedItem;
  10909. }
  10910. } else {
  10911. // 新增项,保留生成项的所有字段
  10912. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  10913. }
  10914. }
  10915. return $merged ?: array_values($existingItems);
  10916. }
  10917. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  10918. {
  10919. $resetItem = [
  10920. $nameKey => trim((string)getProp($item, $nameKey)),
  10921. 'description' => trim((string)getProp($item, 'description')),
  10922. ];
  10923. // 保留指定的字段
  10924. foreach ($preserveFields as $field) {
  10925. $value = getProp($item, $field);
  10926. if (!empty($value)) {
  10927. $resetItem[$field] = $value;
  10928. }
  10929. }
  10930. return $resetItem;
  10931. }
  10932. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  10933. {
  10934. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  10935. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  10936. if ($existingKey !== $generatedKey) {
  10937. return true;
  10938. }
  10939. // 比较 description 是否变化
  10940. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  10941. return true;
  10942. }
  10943. // 比较 pic_prompt 是否变化
  10944. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  10945. }
  10946. private function normalizeEpisodeResourceKey($value): string
  10947. {
  10948. $value = trim((string)$value);
  10949. if ($value === '') {
  10950. return '';
  10951. }
  10952. return strtolower((string)preg_replace('/\s+/u', '', $value));
  10953. }
  10954. // 生成全局角色图片
  10955. private function batchSetGlobalRoleImg($data, $is_force=false) {
  10956. $anime_id = getProp($data, 'anime_id');
  10957. if (!$anime_id) Utils::throwError('1002:请选择对话');
  10958. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10959. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10960. $art_style = getProp($anime, 'art_style');
  10961. $update_flag = false;
  10962. foreach ($roles as &$role) {
  10963. $role_name = getProp($role, 'role');
  10964. if ($role_name == '旁白') continue;
  10965. // 优先使用 pic_prompt,如果没有则使用 description
  10966. $pic_prompt = getProp($role, 'pic_prompt');
  10967. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  10968. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  10969. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  10970. // 参考图地址
  10971. $ref_img_url = getProp($role, 'url');
  10972. if (!$is_force && $ref_img_url) continue;
  10973. $update_flag = true;
  10974. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  10975. try {
  10976. $params = [
  10977. 'prompt' => $description,
  10978. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  10979. 'ref_img_urls' => []
  10980. ];
  10981. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10982. $task_id = $task->id;
  10983. if (!$task_id) {
  10984. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  10985. }
  10986. $role['task_id'] = $task_id;
  10987. $role['task_status'] = 'processing';
  10988. } catch (\Exception $e) {
  10989. Utils::throwError("20003:" . $e->getMessage());
  10990. }
  10991. }
  10992. if (!$update_flag) return true;
  10993. // 保存角色信息
  10994. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  10995. 'roles' => json_encode($roles, 256),
  10996. 'generate_status' => '执行中',
  10997. 'generate_at' => date('Y-m-d H:i:s'),
  10998. 'updated_at' => date('Y-m-d H:i:s')
  10999. ]);
  11000. if (!$boolen) {
  11001. Utils::throwError('20003:保存角色信息失败');
  11002. }
  11003. return $boolen;
  11004. }
  11005. // 生成全局场景图片
  11006. private function batchSetGlobalSceneImg($data, $is_force=false) {
  11007. $anime_id = getProp($data, 'anime_id');
  11008. if (!$anime_id) Utils::throwError('1002:请选择对话');
  11009. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11010. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11011. $art_style = getProp($anime, 'art_style');
  11012. $update_flag = false;
  11013. foreach ($scenes as &$scene) {
  11014. $scene_name = getProp($scene, 'scene');
  11015. // 优先使用 pic_prompt,如果没有则使用 description
  11016. $pic_prompt = getProp($scene, 'pic_prompt');
  11017. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  11018. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  11019. // 参考图地址
  11020. $ref_img_url = getProp($scene, 'url');
  11021. if (!$is_force && $ref_img_url) continue;
  11022. $update_flag = true;
  11023. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  11024. try {
  11025. $params = [
  11026. 'prompt' => $description,
  11027. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  11028. 'ref_img_urls' => []
  11029. ];
  11030. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11031. $task_id = $task->id;
  11032. if (!$task_id) {
  11033. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  11034. }
  11035. $scene['task_id'] = $task_id;
  11036. $scene['task_status'] = 'processing';
  11037. } catch (\Exception $e) {
  11038. Utils::throwError("20003:" . $e->getMessage());
  11039. }
  11040. }
  11041. if (!$update_flag) return true;
  11042. // 保存角色信息
  11043. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  11044. 'scenes' => json_encode($scenes, 256),
  11045. 'generate_status' => '执行中',
  11046. 'generate_at' => date('Y-m-d H:i:s'),
  11047. 'updated_at' => date('Y-m-d H:i:s')
  11048. ]);
  11049. if (!$boolen) {
  11050. Utils::throwError('20003:保存角色信息失败');
  11051. }
  11052. return $boolen;
  11053. }
  11054. // 生成分镜主体、场景和道具图片
  11055. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  11056. $character_prefix = '';
  11057. $scene_prefix = '';
  11058. $prop_prefix = '';
  11059. if ($art_style_type) {
  11060. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  11061. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  11062. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  11063. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  11064. }
  11065. $update_flag = false;
  11066. // 获取上一集的roles、scenes和props数据
  11067. $prev_roles = [];
  11068. $prev_scenes = [];
  11069. $prev_props = [];
  11070. if ($episode_number > 1) {
  11071. $prev_episode = DB::table('mp_anime_episodes')
  11072. ->where('anime_id', $anime_id)
  11073. ->where('episode_number', $episode_number - 1)
  11074. ->where('is_default', 1)
  11075. ->first();
  11076. if ($prev_episode) {
  11077. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  11078. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  11079. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  11080. dLog('deepseek')->info("获取上一集数据成功", [
  11081. 'anime_id' => $anime_id,
  11082. 'prev_episode_number' => $episode_number - 1,
  11083. 'prev_roles_count' => count($prev_roles),
  11084. 'prev_scenes_count' => count($prev_scenes),
  11085. 'prev_props_count' => count($prev_props)
  11086. ]);
  11087. }
  11088. }
  11089. // 处理角色图片生成
  11090. foreach ($roles as &$role) {
  11091. $role_name = getProp($role, 'role');
  11092. if ($role_name == '旁白') continue;
  11093. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  11094. if (isset($ref_products[$role_name])) {
  11095. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  11096. if ($role['url']) continue;
  11097. }
  11098. $role_description = getProp($role, 'description');
  11099. $role_pic_prompt = getProp($role, 'pic_prompt');
  11100. $role_url = getProp($role, 'url');
  11101. // 检查是否可以从上一集继承
  11102. $inherited = false;
  11103. if (!$is_force && !empty($prev_roles)) {
  11104. foreach ($prev_roles as $prev_role) {
  11105. $prev_role_name = getProp($prev_role, 'role');
  11106. $prev_description = getProp($prev_role, 'description');
  11107. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  11108. $prev_url = getProp($prev_role, 'url');
  11109. $prev_task_id = getProp($prev_role, 'task_id');
  11110. $prev_task_status = getProp($prev_role, 'task_status');
  11111. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  11112. if ($role_name == $prev_role_name
  11113. && $role_description == $prev_description
  11114. && $role_pic_prompt == $prev_pic_prompt
  11115. && !empty($prev_url)) {
  11116. $role['task_id'] = $prev_task_id;
  11117. $role['task_status'] = $prev_task_status;
  11118. $role['url'] = $prev_url;
  11119. $inherited = true;
  11120. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  11121. 'anime_id' => $anime_id,
  11122. 'episode_number' => $episode_number,
  11123. 'task_id' => $prev_task_id,
  11124. 'url' => $prev_url
  11125. ]);
  11126. break;
  11127. }
  11128. }
  11129. }
  11130. // 如果已继承或已有url,跳过生成
  11131. if ($inherited || (!$is_force && $role_url)) {
  11132. continue;
  11133. }
  11134. // 优先使用 pic_prompt,如果没有则使用 description
  11135. $pic_prompt = getProp($role, 'pic_prompt');
  11136. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  11137. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11138. $update_flag = true;
  11139. // 调用AIImageGenerationService的生成图片任务接口
  11140. try {
  11141. $params = [
  11142. 'prompt' => $description,
  11143. 'ref_img_urls' => []
  11144. ];
  11145. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11146. $task_id = $task->id;
  11147. if (!$task_id) {
  11148. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  11149. continue; // 不中断,继续处理其他角色
  11150. }
  11151. $role['task_id'] = $task_id;
  11152. $role['task_status'] = 'processing';
  11153. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  11154. 'anime_id' => $anime_id,
  11155. 'episode_number' => $episode_number,
  11156. 'task_id' => $task_id
  11157. ]);
  11158. } catch (\Exception $e) {
  11159. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  11160. // 不抛出异常,继续处理其他角色
  11161. }
  11162. }
  11163. // 处理场景图片生成
  11164. foreach ($scenes as &$scene) {
  11165. $scene_name = getProp($scene, 'scene');
  11166. $scene_description = getProp($scene, 'description');
  11167. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  11168. $scene_url = getProp($scene, 'url');
  11169. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  11170. if (isset($ref_products[$scene_name])) {
  11171. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  11172. if ($scene['url']) continue;
  11173. }
  11174. // 检查是否可以从上一集继承
  11175. $inherited = false;
  11176. if (!$is_force && !empty($prev_scenes)) {
  11177. foreach ($prev_scenes as $prev_scene) {
  11178. $prev_scene_name = getProp($prev_scene, 'scene');
  11179. $prev_description = getProp($prev_scene, 'description');
  11180. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  11181. $prev_url = getProp($prev_scene, 'url');
  11182. $prev_task_id = getProp($prev_scene, 'task_id');
  11183. $prev_task_status = getProp($prev_scene, 'task_status');
  11184. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  11185. if ($scene_name == $prev_scene_name
  11186. && $scene_description == $prev_description
  11187. && $scene_pic_prompt == $prev_pic_prompt
  11188. && !empty($prev_url)) {
  11189. $scene['task_id'] = $prev_task_id;
  11190. $scene['task_status'] = $prev_task_status;
  11191. $scene['url'] = $prev_url;
  11192. $inherited = true;
  11193. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  11194. 'anime_id' => $anime_id,
  11195. 'episode_number' => $episode_number,
  11196. 'task_id' => $prev_task_id,
  11197. 'url' => $prev_url
  11198. ]);
  11199. break;
  11200. }
  11201. }
  11202. }
  11203. // 如果已继承或已有url,跳过生成
  11204. if ($inherited || (!$is_force && $scene_url)) {
  11205. continue;
  11206. }
  11207. // 优先使用 pic_prompt,如果没有则使用 description
  11208. $pic_prompt = getProp($scene, 'pic_prompt');
  11209. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  11210. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11211. $update_flag = true;
  11212. // 调用AIImageGenerationService的生成图片任务接口
  11213. try {
  11214. $params = [
  11215. 'prompt' => $description,
  11216. 'ref_img_urls' => []
  11217. ];
  11218. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11219. $task_id = $task->id;
  11220. if (!$task_id) {
  11221. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  11222. continue; // 不中断,继续处理其他场景
  11223. }
  11224. $scene['task_id'] = $task_id;
  11225. $scene['task_status'] = 'processing';
  11226. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  11227. 'anime_id' => $anime_id,
  11228. 'episode_number' => $episode_number,
  11229. 'task_id' => $task_id
  11230. ]);
  11231. } catch (\Exception $e) {
  11232. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  11233. // 不抛出异常,继续处理其他场景
  11234. }
  11235. }
  11236. // 处理道具图片生成(逻辑与场景一致)
  11237. foreach ($props as &$prop) {
  11238. $prop_name = getProp($prop, 'prop');
  11239. $prop_description = getProp($prop, 'description');
  11240. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  11241. $prop_url = getProp($prop, 'url');
  11242. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  11243. if (isset($ref_products[$prop_name])) {
  11244. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  11245. if ($prop['url']) continue;
  11246. }
  11247. // 检查是否可以从上一集继承
  11248. $inherited = false;
  11249. if (!$is_force && !empty($prev_props)) {
  11250. foreach ($prev_props as $prev_prop) {
  11251. $prev_prop_name = getProp($prev_prop, 'prop');
  11252. $prev_description = getProp($prev_prop, 'description');
  11253. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  11254. $prev_url = getProp($prev_prop, 'url');
  11255. $prev_task_id = getProp($prev_prop, 'task_id');
  11256. $prev_task_status = getProp($prev_prop, 'task_status');
  11257. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  11258. if ($prop_name == $prev_prop_name
  11259. && $prop_description == $prev_description
  11260. && $prop_pic_prompt == $prev_pic_prompt
  11261. && !empty($prev_url)) {
  11262. $prop['task_id'] = $prev_task_id;
  11263. $prop['task_status'] = $prev_task_status;
  11264. $prop['url'] = $prev_url;
  11265. $inherited = true;
  11266. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  11267. 'anime_id' => $anime_id,
  11268. 'episode_number' => $episode_number,
  11269. 'task_id' => $prev_task_id,
  11270. 'url' => $prev_url
  11271. ]);
  11272. break;
  11273. }
  11274. }
  11275. }
  11276. // 如果已继承或已有url,跳过生成
  11277. if ($inherited || (!$is_force && $prop_url)) {
  11278. continue;
  11279. }
  11280. // 优先使用 pic_prompt,如果没有则使用 description
  11281. $pic_prompt = getProp($prop, 'pic_prompt');
  11282. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  11283. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11284. $update_flag = true;
  11285. // 调用AIImageGenerationService的生成图片任务接口
  11286. try {
  11287. $params = [
  11288. 'prompt' => $description,
  11289. 'ref_img_urls' => []
  11290. ];
  11291. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11292. $task_id = $task->id;
  11293. if (!$task_id) {
  11294. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  11295. continue; // 不中断,继续处理其他道具
  11296. }
  11297. $prop['task_id'] = $task_id;
  11298. $prop['task_status'] = 'processing';
  11299. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  11300. 'anime_id' => $anime_id,
  11301. 'episode_number' => $episode_number,
  11302. 'task_id' => $task_id
  11303. ]);
  11304. } catch (\Exception $e) {
  11305. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  11306. // 不抛出异常,继续处理其他道具
  11307. }
  11308. }
  11309. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  11310. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  11311. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  11312. // // 保存剧集的角色和场景信息
  11313. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  11314. // 'roles' => json_encode($roles, 256),
  11315. // 'scenes' => json_encode($scenes, 256),
  11316. // 'generate_status' => '执行中',
  11317. // 'generate_at' => date('Y-m-d H:i:s'),
  11318. // 'updated_at' => date('Y-m-d H:i:s')
  11319. // ]);
  11320. // if (!$boolen) {
  11321. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  11322. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  11323. // }
  11324. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  11325. // 'episode_id' => $episode_id,
  11326. 'roles_count' => count($roles),
  11327. 'scenes_count' => count($scenes),
  11328. 'props_count' => count($props)
  11329. ]);
  11330. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  11331. }
  11332. /**
  11333. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  11334. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  11335. *
  11336. * @param int $anime_id 动漫对话ID
  11337. * @param array $episode_roles 剧集角色数据
  11338. * @param array $episode_scenes 剧集场景数据
  11339. * @param array $episode_props 剧集道具数据
  11340. * @return bool
  11341. */
  11342. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  11343. // 获取全局数据
  11344. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11345. if (!$anime) {
  11346. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  11347. return false;
  11348. }
  11349. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11350. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11351. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  11352. $roles_added = false;
  11353. $roles_updated = false;
  11354. $scenes_added = false;
  11355. $props_added = false;
  11356. // 处理角色同步
  11357. foreach ($episode_roles as $episode_role) {
  11358. $episode_role_name = getProp($episode_role, 'role');
  11359. $episode_description = getProp($episode_role, 'description');
  11360. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  11361. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  11362. // 跳过旁白
  11363. if ($episode_role_name == '旁白') {
  11364. continue;
  11365. }
  11366. // 检查全局中是否已存在相同的角色
  11367. $exists = false;
  11368. $global_role_index = -1;
  11369. foreach ($global_roles as $index => $global_role) {
  11370. $global_role_name = getProp($global_role, 'role');
  11371. $global_description = getProp($global_role, 'description');
  11372. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  11373. // 如果role、description、pic_prompt三项都一致,则认为已存在
  11374. if ($episode_role_name == $global_role_name
  11375. && $episode_description == $global_description
  11376. && $episode_pic_prompt == $global_pic_prompt) {
  11377. $exists = true;
  11378. $global_role_index = $index;
  11379. break;
  11380. }
  11381. }
  11382. // 如果不存在,则添加到全局
  11383. if (!$exists) {
  11384. $global_roles[] = $episode_role;
  11385. $roles_added = true;
  11386. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  11387. 'anime_id' => $anime_id,
  11388. 'role' => $episode_role_name
  11389. ]);
  11390. } else {
  11391. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  11392. if (!empty($episode_voice_prompt)) {
  11393. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  11394. // 如果全局没有voice_prompt或与剧集不一致,则更新
  11395. if ($global_voice_prompt !== $episode_voice_prompt) {
  11396. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  11397. $roles_updated = true;
  11398. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  11399. 'anime_id' => $anime_id,
  11400. 'role' => $episode_role_name,
  11401. 'voice_prompt' => $episode_voice_prompt
  11402. ]);
  11403. }
  11404. }
  11405. }
  11406. }
  11407. // 处理场景同步
  11408. foreach ($episode_scenes as $episode_scene) {
  11409. $episode_scene_name = getProp($episode_scene, 'scene');
  11410. $episode_description = getProp($episode_scene, 'description');
  11411. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  11412. // 检查全局中是否已存在相同的场景
  11413. $exists = false;
  11414. foreach ($global_scenes as $global_scene) {
  11415. $global_scene_name = getProp($global_scene, 'scene');
  11416. $global_description = getProp($global_scene, 'description');
  11417. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  11418. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  11419. if ($episode_scene_name == $global_scene_name
  11420. && $episode_description == $global_description
  11421. && $episode_pic_prompt == $global_pic_prompt) {
  11422. $exists = true;
  11423. break;
  11424. }
  11425. }
  11426. // 如果不存在,则添加到全局
  11427. if (!$exists) {
  11428. $global_scenes[] = $episode_scene;
  11429. $scenes_added = true;
  11430. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  11431. 'anime_id' => $anime_id,
  11432. 'scene' => $episode_scene_name
  11433. ]);
  11434. }
  11435. }
  11436. // 处理道具同步(逻辑与场景一致)
  11437. foreach ($episode_props as $episode_prop) {
  11438. $episode_prop_name = getProp($episode_prop, 'prop');
  11439. $episode_description = getProp($episode_prop, 'description');
  11440. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  11441. // 检查全局中是否已存在相同的道具
  11442. $exists = false;
  11443. foreach ($global_props as $global_prop) {
  11444. $global_prop_name = getProp($global_prop, 'prop');
  11445. $global_description = getProp($global_prop, 'description');
  11446. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  11447. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  11448. if ($episode_prop_name == $global_prop_name
  11449. && $episode_description == $global_description
  11450. && $episode_pic_prompt == $global_pic_prompt) {
  11451. $exists = true;
  11452. break;
  11453. }
  11454. }
  11455. // 如果不存在,则添加到全局
  11456. if (!$exists) {
  11457. $global_props[] = $episode_prop;
  11458. $props_added = true;
  11459. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  11460. 'anime_id' => $anime_id,
  11461. 'prop' => $episode_prop_name
  11462. ]);
  11463. }
  11464. }
  11465. // 如果有新增或更新,则更新全局数据
  11466. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  11467. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  11468. if ($roles_added || $roles_updated) {
  11469. $update_data['roles'] = json_encode($global_roles, 256);
  11470. }
  11471. if ($scenes_added) {
  11472. $update_data['scenes'] = json_encode($global_scenes, 256);
  11473. }
  11474. if ($props_added) {
  11475. $update_data['props'] = json_encode($global_props, 256);
  11476. }
  11477. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  11478. dLog('deepseek')->info('剧集数据同步到全局完成', [
  11479. 'anime_id' => $anime_id,
  11480. 'roles_added' => $roles_added,
  11481. 'roles_updated' => $roles_updated,
  11482. 'scenes_added' => $scenes_added,
  11483. 'props_added' => $props_added,
  11484. 'global_roles_count' => count($global_roles),
  11485. 'global_scenes_count' => count($global_scenes),
  11486. 'global_props_count' => count($global_props)
  11487. ]);
  11488. }
  11489. return true;
  11490. }
  11491. /**
  11492. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  11493. *
  11494. * @param int $anime_id 动漫对话ID
  11495. * @param int $episode_id 分集ID
  11496. * @return bool
  11497. */
  11498. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  11499. // 获取全局角色和场景数据
  11500. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11501. if (!$anime) {
  11502. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  11503. return false;
  11504. }
  11505. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11506. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11507. // 获取指定的分集
  11508. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  11509. if (!$episode) {
  11510. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  11511. return false;
  11512. }
  11513. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  11514. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  11515. $roles_updated = false;
  11516. $scenes_updated = false;
  11517. // 继承角色的task_id、task_status和url
  11518. foreach ($episode_roles as &$episode_role) {
  11519. $episode_role_name = getProp($episode_role, 'role');
  11520. $episode_description = getProp($episode_role, 'description');
  11521. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  11522. $episode_url = getProp($episode_role, 'url');
  11523. // 跳过旁白角色
  11524. if ($episode_role_name == '旁白') {
  11525. continue;
  11526. }
  11527. // 如果剧集中已有URL,跳过
  11528. if (!empty($episode_url)) {
  11529. continue;
  11530. }
  11531. // 遍历全局角色数据,查找匹配的角色
  11532. foreach ($global_roles as $global_role) {
  11533. $global_role_name = getProp($global_role, 'role');
  11534. $global_description = getProp($global_role, 'description');
  11535. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  11536. $global_url = getProp($global_role, 'url');
  11537. $global_task_id = getProp($global_role, 'task_id');
  11538. $global_task_status = getProp($global_role, 'task_status');
  11539. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  11540. if ($episode_role_name == $global_role_name
  11541. && $episode_description == $global_description
  11542. && $episode_pic_prompt == $global_pic_prompt) {
  11543. // 继承 task_id、task_status 和 url
  11544. if (!empty($global_task_id)) {
  11545. $episode_role['task_id'] = $global_task_id;
  11546. $episode_role['task_status'] = $global_task_status;
  11547. $roles_updated = true;
  11548. dLog('deepseek')->info('剧集角色继承全局task_id', [
  11549. 'episode_id' => $episode_id,
  11550. 'role' => $episode_role_name,
  11551. 'task_id' => $global_task_id,
  11552. 'task_status' => $global_task_status
  11553. ]);
  11554. }
  11555. if (!empty($global_url)) {
  11556. $episode_role['url'] = $global_url;
  11557. $roles_updated = true;
  11558. dLog('deepseek')->info('剧集角色继承全局url', [
  11559. 'episode_id' => $episode_id,
  11560. 'role' => $episode_role_name,
  11561. 'url' => $global_url
  11562. ]);
  11563. }
  11564. break;
  11565. }
  11566. }
  11567. }
  11568. // 继承场景的task_id、task_status和url
  11569. foreach ($episode_scenes as &$episode_scene) {
  11570. $episode_scene_name = getProp($episode_scene, 'scene');
  11571. $episode_description = getProp($episode_scene, 'description');
  11572. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  11573. $episode_url = getProp($episode_scene, 'url');
  11574. // 如果剧集中已有URL,跳过
  11575. if (!empty($episode_url)) {
  11576. continue;
  11577. }
  11578. // 遍历全局场景数据,查找匹配的场景
  11579. foreach ($global_scenes as $global_scene) {
  11580. $global_scene_name = getProp($global_scene, 'scene');
  11581. $global_description = getProp($global_scene, 'description');
  11582. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  11583. $global_url = getProp($global_scene, 'url');
  11584. $global_task_id = getProp($global_scene, 'task_id');
  11585. $global_task_status = getProp($global_scene, 'task_status');
  11586. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  11587. if ($episode_scene_name == $global_scene_name
  11588. && $episode_description == $global_description
  11589. && $episode_pic_prompt == $global_pic_prompt) {
  11590. // 继承 task_id、task_status 和 url
  11591. if (!empty($global_task_id)) {
  11592. $episode_scene['task_id'] = $global_task_id;
  11593. $episode_scene['task_status'] = $global_task_status;
  11594. $scenes_updated = true;
  11595. dLog('deepseek')->info('剧集场景继承全局task_id', [
  11596. 'episode_id' => $episode_id,
  11597. 'scene' => $episode_scene_name,
  11598. 'task_id' => $global_task_id,
  11599. 'task_status' => $global_task_status
  11600. ]);
  11601. }
  11602. if (!empty($global_url)) {
  11603. $episode_scene['url'] = $global_url;
  11604. $scenes_updated = true;
  11605. dLog('deepseek')->info('剧集场景继承全局url', [
  11606. 'episode_id' => $episode_id,
  11607. 'scene' => $episode_scene_name,
  11608. 'url' => $global_url
  11609. ]);
  11610. }
  11611. break;
  11612. }
  11613. }
  11614. }
  11615. // 如果有更新,则保存到数据库
  11616. if ($roles_updated || $scenes_updated) {
  11617. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  11618. if ($roles_updated) {
  11619. $update_data['roles'] = json_encode($episode_roles, 256);
  11620. }
  11621. if ($scenes_updated) {
  11622. $update_data['scenes'] = json_encode($episode_scenes, 256);
  11623. }
  11624. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  11625. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  11626. 'episode_id' => $episode_id,
  11627. 'roles_updated' => $roles_updated,
  11628. 'scenes_updated' => $scenes_updated
  11629. ]);
  11630. }
  11631. return true;
  11632. }
  11633. public function chatChangeImg($data) {
  11634. $segment = getProp($data, 'segment');
  11635. $segment_content = getProp($segment, 'segment_content');
  11636. $prompt = getProp($data, 'prompt');
  11637. $ref_img = getProp($data, 'ref_img');
  11638. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  11639. // 处理文本模型
  11640. $model = getProp($data, 'model');
  11641. if (!$model) {
  11642. // 用户没有输入,从anime表获取
  11643. $segment_id = getProp($segment, 'segment_id');
  11644. if ($segment_id) {
  11645. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  11646. if ($episode_id) {
  11647. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  11648. if ($anime_id) {
  11649. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  11650. }
  11651. }
  11652. }
  11653. if (!$model) {
  11654. // anime表也没有,使用默认值
  11655. $model = 'doubao-seed-2-0-mini-260215';
  11656. }
  11657. }
  11658. // 验证模型是否在可用模型表中
  11659. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  11660. $model = 'doubao-seed-2-0-mini-260215';
  11661. }
  11662. $messages[] =
  11663. [
  11664. 'role' => 'user',
  11665. 'content' => $question
  11666. ];
  11667. $post_data = [
  11668. 'model' => $model,
  11669. 'messages' => $messages,
  11670. // 'max_tokens' => 8192,
  11671. 'temperature' => 0.7,
  11672. 'frequency_penalty' => 0,
  11673. 'presence_penalty' => 0,
  11674. 'response_format' => ['type' => 'text'],
  11675. 'stream' => false // 是否启用流式输出
  11676. ];
  11677. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11678. // DeepSeek 官方模型使用 DeepSeek API
  11679. $chatResult = $this->chatOnly($post_data);
  11680. } else if (in_array($model, $this->gpt_text_models)) {
  11681. // GPT-5.4 模型使用 TokenRouter API
  11682. $chatResult = $this->gpt54ChatOnly($post_data);
  11683. } else {
  11684. // 其他模型使用火山引擎API
  11685. $chatResult = $this->volcEngineChatCompletion($post_data);
  11686. }
  11687. if (is_array($chatResult)) {
  11688. extract($chatResult);
  11689. }else {
  11690. Utils::throwError('20003: 接口调用失败!');
  11691. }
  11692. return [
  11693. 'type' => 'done',
  11694. // 'episode' => $episode,
  11695. 'answer' => $fullContent,
  11696. 'reasoning' => $fullReasoningContent,
  11697. 'usage' => $usage
  11698. ];
  11699. }
  11700. // 仅调用deepseek对话接口
  11701. private function chatOnly($post_data) {
  11702. $post_data['max_tokens'] = 300000;
  11703. $client = new Client(['timeout' => 1800, 'verify' => false]);
  11704. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  11705. $response = $result->getBody()->getContents();
  11706. $response_arr = json_decode($response, true);
  11707. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  11708. $fullContent = '';
  11709. $fullReasoningContent = [];
  11710. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  11711. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  11712. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  11713. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  11714. }
  11715. return [
  11716. 'fullContent' => $fullContent,
  11717. 'fullReasoningContent' => $fullReasoningContent,
  11718. 'usage' => $usage
  11719. ];
  11720. }
  11721. // 仅调用 GPT-5.4 对话接口(非流式)
  11722. private function gpt54ChatOnly($post_data) {
  11723. $apiKey = env('GPT_54_API_KEY');
  11724. if (empty($apiKey)) {
  11725. Utils::throwError('20003:GPT-5.4 API Key未配置');
  11726. }
  11727. // 先探活,服务不可用时自动重试
  11728. $this->ensureGptServiceAvailable();
  11729. $client = new Client(['timeout' => 1800, 'verify' => false]);
  11730. $headers = [
  11731. 'Authorization' => 'Bearer ' . $apiKey,
  11732. 'Content-Type' => 'application/json'
  11733. ];
  11734. // 移除 thinking 参数,GPT-5.4 不支持
  11735. if (isset($post_data['thinking'])) {
  11736. unset($post_data['thinking']);
  11737. }
  11738. if (isset($post_data['reasoning_effort'])) {
  11739. unset($post_data['reasoning_effort']);
  11740. }
  11741. $post_data['max_completion_tokens'] = 100000;
  11742. // 确保 stream 为 false
  11743. $post_data['stream'] = false;
  11744. $maxRetries = $this->gptRetryTimes();
  11745. $interval = $this->gptRetryInterval();
  11746. $attempt = 0;
  11747. while (true) {
  11748. try {
  11749. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  11750. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  11751. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  11752. 'json' => $post_data,
  11753. 'headers' => $headers
  11754. ]);
  11755. $response = $result->getBody()->getContents();
  11756. $response_arr = json_decode($response, true);
  11757. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  11758. $fullContent = '';
  11759. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  11760. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  11761. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  11762. }
  11763. return [
  11764. 'fullContent' => $fullContent,
  11765. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  11766. 'usage' => $usage
  11767. ];
  11768. } catch (\Exception $e) {
  11769. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  11770. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  11771. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  11772. throw $e;
  11773. }
  11774. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  11775. 'retry' => $attempt + 1,
  11776. 'max_retries' => $maxRetries,
  11777. 'error' => $e->getMessage()
  11778. ]);
  11779. sleep($interval);
  11780. $attempt++;
  11781. }
  11782. }
  11783. }
  11784. private function splitContent($content) {
  11785. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  11786. $chapters = [];
  11787. // 匹配章节标题格式:
  11788. // 1. 标题可能独占一行,也可能在正文末尾或中间
  11789. // 2. 格式支持:
  11790. // - **第一集**
  11791. // - 第一集:
  11792. // - ###第1章 重生
  11793. // - ##第2章 相救
  11794. // - 第三章 共处一室
  11795. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  11796. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  11797. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  11798. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  11799. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  11800. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  11801. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  11802. // 先在每个标题前插入换行符(如果前面不是换行的话)
  11803. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  11804. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  11805. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  11806. // 用正则找出所有章节标题的位置
  11807. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  11808. $titleCount = count($matches[0]);
  11809. for ($i = 0; $i < $titleCount; $i++) {
  11810. // 获取当前章节标题
  11811. $titleLine = trim($matches[0][$i][0]);
  11812. // 去除标题开头的特殊符号
  11813. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  11814. // 去除标题结尾的冒号和特殊符号
  11815. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  11816. $cleanTitle = trim($cleanTitle);
  11817. // 获取当前标题的结束位置
  11818. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  11819. // 获取下一个章节标题的开始位置(如果存在)
  11820. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  11821. // 提取章节内容(从标题结束到下一个标题开始)
  11822. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  11823. // 清理内容:去除前后空白和分隔线
  11824. $chapterContent = trim($chapterContent);
  11825. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  11826. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  11827. if (!empty($cleanTitle) && !empty($chapterContent)) {
  11828. $chapters[] = [
  11829. 'title' => $cleanTitle,
  11830. 'content' => $chapterContent
  11831. ];
  11832. }
  11833. }
  11834. } else {
  11835. // 如果没有匹配到章节,返回整个内容
  11836. $chapters[] = [
  11837. 'title' => '',
  11838. 'content' => $content
  11839. ];
  11840. }
  11841. return $chapters;
  11842. }
  11843. public function getContentByBid($bid) {
  11844. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  11845. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  11846. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  11847. $content = '';
  11848. foreach ($chapters as $chapter) {
  11849. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  11850. }
  11851. return $content;
  11852. }
  11853. public function getContentByScriptId($script_id) {
  11854. $content = '';
  11855. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  11856. if ($contents) {
  11857. $content = implode(PHP_EOL, $contents);
  11858. }else {
  11859. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  11860. }
  11861. return $content;
  11862. }
  11863. /**
  11864. * 根据文件类型提取文本内容
  11865. *
  11866. * @param mixed $file 文件对象或文件路径
  11867. * @return string
  11868. */
  11869. public function extractFileContent($file) {
  11870. // 获取文件路径和扩展名
  11871. if (is_string($file)) {
  11872. $filePath = $file;
  11873. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  11874. } else {
  11875. // Laravel UploadedFile 对象
  11876. $filePath = $file->getRealPath();
  11877. $extension = strtolower($file->getClientOriginalExtension());
  11878. }
  11879. $content = '';
  11880. switch ($extension) {
  11881. case 'txt':
  11882. $content = $this->extractTxtContent($filePath);
  11883. break;
  11884. case 'pdf':
  11885. $content = $this->extractPdfContent($filePath);
  11886. break;
  11887. case 'doc':
  11888. case 'docx':
  11889. $content = $this->extractWordContent($filePath);
  11890. break;
  11891. // case 'jpg':
  11892. // case 'jpeg':
  11893. // case 'png':
  11894. // case 'gif':
  11895. // case 'bmp':
  11896. // case 'webp':
  11897. // $content = $this->extractImageContent($filePath);
  11898. // break;
  11899. default:
  11900. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  11901. }
  11902. return $content;
  11903. }
  11904. /**
  11905. * 提取 TXT 文件内容
  11906. */
  11907. private function extractTxtContent($filePath) {
  11908. if (!file_exists($filePath)) {
  11909. Utils::throwError('20003:文件不存在');
  11910. }
  11911. $content = file_get_contents($filePath);
  11912. // 尝试检测并转换编码
  11913. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  11914. if ($encoding && $encoding !== 'UTF-8') {
  11915. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  11916. }
  11917. return trim($content);
  11918. }
  11919. /**
  11920. * 提取 PDF 文件内容
  11921. */
  11922. private function extractPdfContent($filePath) {
  11923. if (!file_exists($filePath)) {
  11924. Utils::throwError('20003:文件不存在');
  11925. }
  11926. try {
  11927. $parser = new PdfParser();
  11928. $pdf = $parser->parseFile($filePath);
  11929. $content = $pdf->getText();
  11930. return trim($content);
  11931. } catch (\Exception $e) {
  11932. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  11933. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  11934. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  11935. }
  11936. }
  11937. /**
  11938. * 提取 Word 文件内容(支持 doc 和 docx)
  11939. */
  11940. private function extractWordContent($filePath) {
  11941. if (!file_exists($filePath)) {
  11942. Utils::throwError('20003:文件不存在');
  11943. }
  11944. try {
  11945. $phpWord = WordIOFactory::load($filePath);
  11946. $content = '';
  11947. foreach ($phpWord->getSections() as $section) {
  11948. foreach ($section->getElements() as $element) {
  11949. $content .= $this->extractWordElementText($element);
  11950. }
  11951. }
  11952. return trim($content);
  11953. } catch (\Exception $e) {
  11954. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  11955. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  11956. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  11957. }
  11958. }
  11959. /**
  11960. * 递归提取 Word 元素中的文本
  11961. */
  11962. private function extractWordElementText($element) {
  11963. $text = '';
  11964. if (method_exists($element, 'getText')) {
  11965. $text .= $element->getText() . "\n";
  11966. } elseif (method_exists($element, 'getElements')) {
  11967. foreach ($element->getElements() as $childElement) {
  11968. $text .= $this->extractWordElementText($childElement);
  11969. }
  11970. }
  11971. return $text;
  11972. }
  11973. /**
  11974. * 提取图片内容(使用火山引擎 OCR)
  11975. */
  11976. private function extractImageContent($filePath) {
  11977. if (!file_exists($filePath)) {
  11978. Utils::throwError('20003:文件不存在');
  11979. }
  11980. try {
  11981. // 读取图片并转换为 base64
  11982. $imageData = file_get_contents($filePath);
  11983. $base64Image = base64_encode($imageData);
  11984. // 调用火山引擎 OCR 服务
  11985. $content = $this->callVolcEngineOCR($base64Image);
  11986. return trim($content);
  11987. } catch (\Exception $e) {
  11988. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  11989. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  11990. Utils::throwError('20003:图片识别失败');
  11991. }
  11992. }
  11993. /**
  11994. * 调用火山引擎 OCR 服务识别图片文字
  11995. *
  11996. * @param string $base64Image base64 编码的图片数据
  11997. * @return string 识别的文字内容
  11998. */
  11999. private function callVolcEngineOCR($base64Image) {
  12000. $method = 'POST';
  12001. $service = 'cv';
  12002. $host = 'visual.volcengineapi.com';
  12003. $region = env('VOLC_REGION', 'cn-north-1');
  12004. $access_key = env('VOLC_AK');
  12005. $secret_key = env('VOLC_SK');
  12006. $action = 'OCRNormal';
  12007. $version = '2020-08-26';
  12008. if (!$access_key || !$secret_key) {
  12009. Utils::throwError('20003:请配置火山引擎 AK/SK');
  12010. }
  12011. // 请求体
  12012. $body = json_encode([
  12013. 'image_base64' => $base64Image
  12014. ]);
  12015. // 生成签名
  12016. $headers = $this->getVolcEngineSignHeaders(
  12017. $method, $service, $host, $region,
  12018. "Action={$action}&Version={$version}",
  12019. $access_key, $secret_key, $body
  12020. );
  12021. $client = new Client(['timeout' => 1800, 'verify' => false]);
  12022. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  12023. 'headers' => $headers,
  12024. 'body' => $body
  12025. ]);
  12026. $response_arr = json_decode($response->getBody()->getContents(), true);
  12027. // 提取识别的文字
  12028. $textLines = [];
  12029. if (isset($response_arr['data']['line_texts'])) {
  12030. $textLines = $response_arr['data']['line_texts'];
  12031. } elseif (isset($response_arr['data']['ocr_infos'])) {
  12032. foreach ($response_arr['data']['ocr_infos'] as $info) {
  12033. if (isset($info['text'])) {
  12034. $textLines[] = $info['text'];
  12035. }
  12036. }
  12037. }
  12038. if (empty($textLines)) {
  12039. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  12040. return '';
  12041. }
  12042. return implode("\n", $textLines);
  12043. }
  12044. /**
  12045. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  12046. */
  12047. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  12048. $contentType = 'application/json';
  12049. $accept = 'application/json';
  12050. // 获取当前UTC时间
  12051. $t = new DateTime('now', new DateTimeZone('UTC'));
  12052. $xDate = $t->format('Ymd\THis\Z');
  12053. $dateStamp = $t->format('Ymd');
  12054. // 计算 body 的 sha256 哈希
  12055. $payloadHash = hash('sha256', $body);
  12056. // 1. 拼接规范请求串
  12057. $canonicalUri = '/';
  12058. $canonicalQueryString = $queryString;
  12059. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  12060. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  12061. $canonicalRequest = implode("\n", [
  12062. $method,
  12063. $canonicalUri,
  12064. $canonicalQueryString,
  12065. $canonicalHeaders,
  12066. $signedHeaders,
  12067. $payloadHash
  12068. ]);
  12069. // 2. 拼接待签名字符串
  12070. $algorithm = 'HMAC-SHA256';
  12071. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  12072. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  12073. $stringToSign = implode("\n", [
  12074. $algorithm,
  12075. $xDate,
  12076. $credentialScope,
  12077. $hashedCanonicalRequest
  12078. ]);
  12079. // 3. 计算签名
  12080. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  12081. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  12082. // 4. 添加签名到请求头
  12083. $authorizationHeader = sprintf(
  12084. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  12085. $algorithm,
  12086. $access_key,
  12087. $credentialScope,
  12088. $signedHeaders,
  12089. $signature
  12090. );
  12091. return [
  12092. 'Accept' => $accept,
  12093. 'Content-Type' => $contentType,
  12094. 'Host' => $host,
  12095. 'X-Date' => $xDate,
  12096. 'X-Content-Sha256'=> $payloadHash,
  12097. 'Authorization' => $authorizationHeader
  12098. ];
  12099. }
  12100. public function generateScriptWords($cid, $model = 'r1') {
  12101. ini_set('max_execution_time', 0);
  12102. if (!$cid) Utils::throwError('20003: 请选择章节!');
  12103. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  12104. // 模型兼容性处理和思考模式设置
  12105. $thinkingMode = 'disabled';
  12106. $reasoningEffort = 'high';
  12107. if ($model == 'r1') {
  12108. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  12109. $thinkingMode = 'enabled';
  12110. } else {
  12111. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  12112. $thinkingMode = 'disabled';
  12113. }
  12114. $messages = [
  12115. [
  12116. 'role' => 'system',
  12117. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  12118. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  12119. 2.非对话部分请全部用旁白角色代替
  12120. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  12121. ],
  12122. [
  12123. 'role' => 'user',
  12124. 'content' => $content
  12125. ]
  12126. ];
  12127. $post_data = [
  12128. 'model' => $model,
  12129. 'messages' => $messages,
  12130. // 'max_tokens' => 8192,
  12131. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  12132. 'frequency_penalty' => 0,
  12133. 'presence_penalty' => 0,
  12134. 'thinking' => ['type' => $thinkingMode],
  12135. 'response_format' => [
  12136. 'type' => 'text'
  12137. ],
  12138. 'stream' => false
  12139. ];
  12140. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  12141. // 根据模型类型选择调用方法
  12142. $fullContent = '';
  12143. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  12144. // DeepSeek 官方模型使用 DeepSeek API
  12145. $chatResult = $this->chatOnly($post_data);
  12146. } else if (in_array($model, $this->gpt_text_models)) {
  12147. // GPT-5.4 模型使用 TokenRouter API
  12148. $chatResult = $this->gpt54ChatOnly($post_data);
  12149. } else {
  12150. // 其他模型使用火山引擎API
  12151. $chatResult = $this->volcEngineChatCompletion($post_data);
  12152. }
  12153. if (is_array($chatResult)) {
  12154. $fullContent = $chatResult['fullContent'];
  12155. }
  12156. return $fullContent;
  12157. }
  12158. /**
  12159. * 智能化解析集数信息
  12160. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  12161. *
  12162. * @param string $prompt 用户输入的提示词
  12163. * @return int|null 解析出的集数,如果没有找到则返回null
  12164. */
  12165. private function extractEpisodeNumber($prompt)
  12166. {
  12167. if (empty($prompt)) {
  12168. return null;
  12169. }
  12170. // 定义各种可能的表达模式
  12171. $patterns = [
  12172. // 基本模式:改成N集、调整成N集、修改成N集
  12173. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  12174. // 扩展模式:分成N集、拆分成N集、分割成N集
  12175. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  12176. // 数量模式:N集、共N集、总共N集
  12177. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  12178. // 制作模式:制作N集、生成N集、创建N集
  12179. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  12180. // 计划模式:计划N集、预计N集、打算N集
  12181. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  12182. // 需要模式:需要N集、要N集
  12183. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  12184. // 中文数字模式:改成三集、调整成五集等
  12185. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  12186. // 英文数字模式
  12187. '/(?: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',
  12188. ];
  12189. // 中文数字转阿拉伯数字的映射
  12190. $chineseNumbers = [
  12191. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  12192. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  12193. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  12194. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  12195. ];
  12196. // 逐个尝试匹配模式
  12197. foreach ($patterns as $pattern) {
  12198. if (preg_match($pattern, $prompt, $matches)) {
  12199. $number = trim($matches[1]);
  12200. // 如果是中文数字,转换为阿拉伯数字
  12201. if (isset($chineseNumbers[$number])) {
  12202. return $chineseNumbers[$number];
  12203. }
  12204. // 如果是阿拉伯数字,直接返回
  12205. if (is_numeric($number)) {
  12206. $episodeNum = intval($number);
  12207. // 合理性检查:集数应该在1-100之间
  12208. if ($episodeNum >= 1 && $episodeNum <= 100) {
  12209. return $episodeNum;
  12210. }
  12211. }
  12212. }
  12213. }
  12214. return null;
  12215. }
  12216. /**
  12217. * 调用火山引擎对话(Chat) API
  12218. *
  12219. * @param array $params 包含以下参数:
  12220. * - model: 模型ID(必填)
  12221. * - messages: 消息列表(必填)
  12222. * - stream: 是否流式输出(可选,默认false)
  12223. * - max_tokens: 最大输出token数(可选)
  12224. * - temperature: 采样温度(可选,默认1)
  12225. * - top_p: 核采样概率(可选,默认0.7)
  12226. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  12227. * - presence_penalty: 存在惩罚系数(可选,默认0)
  12228. * - stop: 停止词(可选)
  12229. * - tools: 工具列表(可选)
  12230. * @return array|Generator 非流式返回数组,流式返回生成器
  12231. */
  12232. public function volcEngineChatCompletion(array $params)
  12233. {
  12234. $apiKey = env('VOLC_AI_API_KEY');
  12235. if (empty($apiKey)) {
  12236. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  12237. }
  12238. // 构建请求参数
  12239. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  12240. $requestData = [
  12241. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  12242. 'messages' => $params['messages'] ?? [],
  12243. ];
  12244. if (!in_array($originalModel, $this->valid_text_models)) {
  12245. Utils::throwError('20003:该模型不支持!');
  12246. }
  12247. // 添加可选参数
  12248. if (isset($params['stream'])) {
  12249. $requestData['stream'] = $params['stream'];
  12250. }
  12251. if (isset($params['stream_options'])) {
  12252. $requestData['stream_options'] = $params['stream_options'];
  12253. }
  12254. if (isset($params['max_tokens'])) {
  12255. $requestData['max_tokens'] = $params['max_tokens'];
  12256. }else if (isset($params['max_completion_tokens'])) {
  12257. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  12258. }else {
  12259. $requestData['max_completion_tokens'] = 100000;
  12260. }
  12261. if (isset($params['temperature'])) {
  12262. $requestData['temperature'] = $params['temperature'];
  12263. }
  12264. if (isset($params['top_p'])) {
  12265. $requestData['top_p'] = $params['top_p'];
  12266. }
  12267. if (isset($params['frequency_penalty'])) {
  12268. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  12269. }
  12270. if (isset($params['presence_penalty'])) {
  12271. $requestData['presence_penalty'] = $params['presence_penalty'];
  12272. }
  12273. if (isset($params['stop'])) {
  12274. $requestData['stop'] = $params['stop'];
  12275. }
  12276. if (isset($params['tools'])) {
  12277. $requestData['tools'] = $params['tools'];
  12278. }
  12279. if (isset($params['tool_choice'])) {
  12280. $requestData['tool_choice'] = $params['tool_choice'];
  12281. }
  12282. if (isset($params['response_format'])) {
  12283. $requestData['response_format'] = $params['response_format'];
  12284. }
  12285. if (isset($params['thinking'])) {
  12286. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  12287. if (is_array($params['thinking'])) {
  12288. $requestData['thinking'] = $params['thinking'];
  12289. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  12290. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  12291. }
  12292. } else {
  12293. $requestData['thinking'] = ['type' => $params['thinking']];
  12294. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  12295. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  12296. }
  12297. }
  12298. } else {
  12299. $requestData['thinking'] = ['type' => 'disabled'];
  12300. }
  12301. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  12302. $client = new Client(['verify' => false, 'timeout' => 1800]);
  12303. try {
  12304. // 判断是否为流式输出
  12305. $isStream = isset($params['stream']) && $params['stream'] === true;
  12306. if ($isStream) {
  12307. // 流式输出
  12308. // 流式请求默认声明返回 usage(未显式传参时)
  12309. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  12310. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  12311. } else {
  12312. // 非流式输出
  12313. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  12314. 'headers' => [
  12315. 'Authorization' => 'Bearer ' . $apiKey,
  12316. 'Content-Type' => 'application/json',
  12317. ],
  12318. 'json' => $requestData
  12319. ]);
  12320. $responseData = json_decode($response->getBody(), true);
  12321. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  12322. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  12323. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  12324. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  12325. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  12326. }
  12327. return [
  12328. 'fullContent' => $fullContent,
  12329. 'fullReasoningContent' => $fullReasoningContent,
  12330. 'usage' => $usage
  12331. ];
  12332. }
  12333. } catch (\Exception $e) {
  12334. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  12335. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  12336. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  12337. }
  12338. }
  12339. /**
  12340. * 火山引擎对话API流式输出
  12341. *
  12342. * @param Client $client HTTP客户端
  12343. * @param string $apiKey API密钥
  12344. * @param array $requestData 请求数据
  12345. * @return Generator
  12346. */
  12347. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  12348. {
  12349. try {
  12350. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  12351. 'headers' => [
  12352. 'Authorization' => 'Bearer ' . $apiKey,
  12353. 'Content-Type' => 'application/json',
  12354. ],
  12355. 'json' => $requestData,
  12356. 'stream' => true
  12357. ]);
  12358. $body = $response->getBody();
  12359. $buffer = '';
  12360. $fullContent = '';
  12361. $fullReasoningContent = '';
  12362. $usage = [];
  12363. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  12364. // 逐行读取流式响应
  12365. while (!$body->eof()) {
  12366. $chunk = $body->read(1024);
  12367. $buffer .= $chunk;
  12368. // 按行分割
  12369. $lines = explode("\n", $buffer);
  12370. $buffer = array_pop($lines);
  12371. foreach ($lines as $line) {
  12372. $line = trim($line);
  12373. if (empty($line)) {
  12374. continue;
  12375. }
  12376. // 检查是否是SSE数据行
  12377. if (strpos($line, 'data: ') !== 0) {
  12378. continue;
  12379. }
  12380. $data = substr($line, 6);
  12381. if ($data === '[DONE]') {
  12382. dLog('deepseek')->info('收到结束标记');
  12383. break 2;
  12384. }
  12385. try {
  12386. $json = json_decode($data, true);
  12387. if (json_last_error() !== JSON_ERROR_NONE) {
  12388. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  12389. continue;
  12390. }
  12391. if (isset($json['choices'][0]['delta'])) {
  12392. $delta = $json['choices'][0]['delta'];
  12393. // 处理思维链内容
  12394. if (isset($delta['reasoning_content'])) {
  12395. $fullReasoningContent .= $delta['reasoning_content'];
  12396. yield [
  12397. 'type' => 'reasoning',
  12398. 'content' => $delta['reasoning_content'],
  12399. 'full_reasoning' => $fullReasoningContent
  12400. ];
  12401. }
  12402. // 处理回答内容
  12403. if (isset($delta['content'])) {
  12404. $fullContent .= $delta['content'];
  12405. yield [
  12406. 'type' => 'content',
  12407. 'content' => $delta['content'],
  12408. ];
  12409. }
  12410. }
  12411. // 获取使用统计信息
  12412. if (isset($json['usage'])) {
  12413. $usage = $json['usage'];
  12414. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  12415. }
  12416. } catch (\Exception $e) {
  12417. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  12418. continue;
  12419. }
  12420. }
  12421. }
  12422. dLog('deepseek')->info('流式读取完成', [
  12423. 'content_length' => strlen($fullContent),
  12424. 'reasoning_length' => strlen($fullReasoningContent)
  12425. ]);
  12426. yield [
  12427. 'type' => 'done',
  12428. 'full_content' => $fullContent,
  12429. 'full_reasoning' => $fullReasoningContent,
  12430. 'usage' => $usage
  12431. ];
  12432. } catch (\Exception $e) {
  12433. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  12434. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  12435. throw $e;
  12436. }
  12437. }
  12438. /**
  12439. * 检查并创建图片生成任务
  12440. *
  12441. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  12442. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  12443. * @param string $nameKey 资源名称字段('role' 或 'scene')
  12444. * @param string $art_style 美术风格
  12445. * @return array 更新后的资源列表
  12446. */
  12447. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  12448. {
  12449. // 确保参数为数组
  12450. $merged_items = is_array($merged_items) ? $merged_items : [];
  12451. $global_items = is_array($global_items) ? $global_items : [];
  12452. // 构建全局资源映射表,用于快速查找
  12453. $global_map = [];
  12454. foreach ($global_items as $item) {
  12455. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  12456. if ($itemKey === '') {
  12457. continue;
  12458. }
  12459. $global_map[$itemKey] = $item;
  12460. }
  12461. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  12462. foreach ($merged_items as &$item) {
  12463. $item_name = getProp($item, $nameKey);
  12464. $item_description = getProp($item, 'description');
  12465. // $item_url = getProp($item, 'url');
  12466. // // 如果已有图片URL,跳过
  12467. // if (!empty($item_url)) {
  12468. // continue;
  12469. // }
  12470. // 如果是旁白角色,跳过
  12471. if ($nameKey === 'role' && $item_name === '旁白') {
  12472. continue;
  12473. }
  12474. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  12475. if ($itemKey === '') {
  12476. continue;
  12477. }
  12478. $need_create_task = false;
  12479. // 条件1:在全局资源中找不到匹配的名称
  12480. if (!isset($global_map[$itemKey])) {
  12481. $need_create_task = true;
  12482. } else {
  12483. // 条件2:名称匹配但描述或 pic_prompt 不一致
  12484. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  12485. $current_description = trim((string)$item_description);
  12486. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  12487. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  12488. // 如果 description 或 pic_prompt 有变化,需要重新生成
  12489. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  12490. $need_create_task = true;
  12491. }
  12492. }
  12493. // 如果需要创建任务,调用图片生成服务
  12494. if ($need_create_task) {
  12495. try {
  12496. // 优先使用 pic_prompt,如果没有则使用 description
  12497. $pic_prompt = getProp($item, 'pic_prompt');
  12498. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  12499. // 添加美术风格前缀
  12500. if ($art_style) {
  12501. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  12502. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  12503. $description = "{$prefix}:{$description}";
  12504. }
  12505. $params = [
  12506. 'prompt' => $description,
  12507. 'ref_img_urls' => []
  12508. ];
  12509. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12510. $task_id = $task->id;
  12511. if ($task_id) {
  12512. $item['task_id'] = $task_id;
  12513. $item['task_status'] = 'processing';
  12514. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  12515. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  12516. }
  12517. } catch (\Exception $e) {
  12518. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  12519. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  12520. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  12521. // 不抛出异常,继续处理其他资源
  12522. }
  12523. }
  12524. }
  12525. return $merged_items;
  12526. }
  12527. /**
  12528. * 同步新出现的主体和场景到全局
  12529. *
  12530. * @param int $anime_id 动漫ID
  12531. * @param array $merged_roles 合并后的角色列表
  12532. * @param array $merged_scenes 合并后的场景列表
  12533. * @param array $global_roles 全局角色列表
  12534. * @param array $global_scenes 全局场景列表
  12535. * @return void
  12536. */
  12537. private function syncNewResourcesToGlobal(
  12538. int $anime_id,
  12539. array $merged_roles,
  12540. array $merged_scenes,
  12541. array $global_roles,
  12542. array $global_scenes
  12543. ): void {
  12544. // 构建全局角色映射表
  12545. $global_role_map = [];
  12546. foreach ($global_roles as $role) {
  12547. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  12548. if ($roleKey !== '') {
  12549. $global_role_map[$roleKey] = $role;
  12550. }
  12551. }
  12552. // 构建全局场景映射表
  12553. $global_scene_map = [];
  12554. foreach ($global_scenes as $scene) {
  12555. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  12556. if ($sceneKey !== '') {
  12557. $global_scene_map[$sceneKey] = $scene;
  12558. }
  12559. }
  12560. $need_update = false;
  12561. $new_global_roles = $global_roles;
  12562. $new_global_scenes = $global_scenes;
  12563. // 检查并添加新角色到全局
  12564. foreach ($merged_roles as $role) {
  12565. $role_name = getProp($role, 'role');
  12566. // 跳过旁白
  12567. if ($role_name === '旁白') {
  12568. continue;
  12569. }
  12570. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  12571. if ($roleKey === '') {
  12572. continue;
  12573. }
  12574. // 如果全局中不存在该角色,添加到全局
  12575. if (!isset($global_role_map[$roleKey])) {
  12576. $new_global_roles[] = [
  12577. 'role' => $role_name,
  12578. 'description' => getProp($role, 'description', ''),
  12579. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  12580. 'voice_name' => getProp($role, 'voice_name', ''),
  12581. 'voice_type' => getProp($role, 'voice_type', ''),
  12582. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  12583. 'url' => getProp($role, 'url', ''),
  12584. 'task_id' => getProp($role, 'task_id', ''),
  12585. 'task_status' => getProp($role, 'task_status', ''),
  12586. ];
  12587. $global_role_map[$roleKey] = true; // 标记已添加
  12588. $need_update = true;
  12589. dLog('deepseek')->info("新角色同步到全局", [
  12590. 'anime_id' => $anime_id,
  12591. 'role' => $role_name,
  12592. 'task_id' => getProp($role, 'task_id', ''),
  12593. ]);
  12594. }
  12595. // else {
  12596. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  12597. // $global_role = $global_role_map[$roleKey];
  12598. // if (is_array($global_role)) {
  12599. // $updated = false;
  12600. // $update_fields = [];
  12601. // // 检查描述是否更新
  12602. // $current_description = trim((string)getProp($role, 'description'));
  12603. // $global_description = trim((string)getProp($global_role, 'description'));
  12604. // if ($current_description !== '' && $current_description !== $global_description) {
  12605. // $updated = true;
  12606. // $update_fields[] = 'description';
  12607. // }
  12608. // // 检查pic_prompt是否更新
  12609. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  12610. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  12611. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  12612. // $updated = true;
  12613. // $update_fields[] = 'pic_prompt';
  12614. // }
  12615. // // 检查图片任务信息是否更新
  12616. // $current_task_id = getProp($role, 'task_id');
  12617. // $global_task_id = getProp($global_role, 'task_id');
  12618. // if ($current_task_id && $current_task_id !== $global_task_id) {
  12619. // $updated = true;
  12620. // $update_fields[] = 'task_id';
  12621. // }
  12622. // // 如果有更新,同步到全局
  12623. // if ($updated) {
  12624. // foreach ($new_global_roles as &$global_role_item) {
  12625. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  12626. // if ($global_role_key === $roleKey) {
  12627. // if (in_array('description', $update_fields)) {
  12628. // $global_role_item['description'] = $current_description;
  12629. // }
  12630. // if (in_array('pic_prompt', $update_fields)) {
  12631. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  12632. // }
  12633. // if (in_array('task_id', $update_fields)) {
  12634. // $global_role_item['task_id'] = $current_task_id;
  12635. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  12636. // $global_role_item['url'] = getProp($role, 'url', '');
  12637. // }
  12638. // break;
  12639. // }
  12640. // }
  12641. // $need_update = true;
  12642. // dLog('deepseek')->info("角色信息更新到全局", [
  12643. // 'anime_id' => $anime_id,
  12644. // 'role' => $role_name,
  12645. // 'update_fields' => implode(',', $update_fields),
  12646. // ]);
  12647. // }
  12648. // }
  12649. // }
  12650. }
  12651. // 检查并添加新场景到全局
  12652. foreach ($merged_scenes as $scene) {
  12653. $scene_name = getProp($scene, 'scene');
  12654. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  12655. if ($sceneKey === '') {
  12656. continue;
  12657. }
  12658. // 如果全局中不存在该场景,添加到全局
  12659. if (!isset($global_scene_map[$sceneKey])) {
  12660. $new_global_scenes[] = [
  12661. 'scene' => $scene_name,
  12662. 'description' => getProp($scene, 'description', ''),
  12663. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  12664. 'url' => getProp($scene, 'url', ''),
  12665. 'task_id' => getProp($scene, 'task_id', ''),
  12666. 'task_status' => getProp($scene, 'task_status', ''),
  12667. ];
  12668. $global_scene_map[$sceneKey] = true; // 标记已添加
  12669. $need_update = true;
  12670. dLog('deepseek')->info("新场景同步到全局", [
  12671. 'anime_id' => $anime_id,
  12672. 'scene' => $scene_name,
  12673. 'task_id' => getProp($scene, 'task_id', ''),
  12674. ]);
  12675. }
  12676. // else {
  12677. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  12678. // $global_scene = $global_scene_map[$sceneKey];
  12679. // if (is_array($global_scene)) {
  12680. // $updated = false;
  12681. // $update_fields = [];
  12682. // // 检查描述是否更新
  12683. // $current_description = trim((string)getProp($scene, 'description'));
  12684. // $global_description = trim((string)getProp($global_scene, 'description'));
  12685. // if ($current_description !== '' && $current_description !== $global_description) {
  12686. // $updated = true;
  12687. // $update_fields[] = 'description';
  12688. // }
  12689. // // 检查pic_prompt是否更新
  12690. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  12691. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  12692. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  12693. // $updated = true;
  12694. // $update_fields[] = 'pic_prompt';
  12695. // }
  12696. // // 检查图片任务信息是否更新
  12697. // $current_task_id = getProp($scene, 'task_id');
  12698. // $global_task_id = getProp($global_scene, 'task_id');
  12699. // if ($current_task_id && $current_task_id !== $global_task_id) {
  12700. // $updated = true;
  12701. // $update_fields[] = 'task_id';
  12702. // }
  12703. // // 如果有更新,同步到全局
  12704. // if ($updated) {
  12705. // foreach ($new_global_scenes as &$global_scene_item) {
  12706. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  12707. // if ($global_scene_key === $sceneKey) {
  12708. // if (in_array('description', $update_fields)) {
  12709. // $global_scene_item['description'] = $current_description;
  12710. // }
  12711. // if (in_array('pic_prompt', $update_fields)) {
  12712. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  12713. // }
  12714. // if (in_array('task_id', $update_fields)) {
  12715. // $global_scene_item['task_id'] = $current_task_id;
  12716. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  12717. // $global_scene_item['url'] = getProp($scene, 'url', '');
  12718. // }
  12719. // break;
  12720. // }
  12721. // }
  12722. // $need_update = true;
  12723. // dLog('deepseek')->info("场景信息更新到全局", [
  12724. // 'anime_id' => $anime_id,
  12725. // 'scene' => $scene_name,
  12726. // 'update_fields' => implode(',', $update_fields),
  12727. // ]);
  12728. // }
  12729. // }
  12730. // }
  12731. }
  12732. // 如果有新增或更新,更新数据库
  12733. if ($need_update) {
  12734. $update_data = [
  12735. 'roles' => json_encode($new_global_roles, 256),
  12736. 'scenes' => json_encode($new_global_scenes, 256),
  12737. 'updated_at' => date('Y-m-d H:i:s'),
  12738. ];
  12739. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  12740. if ($result !== false) {
  12741. dLog('deepseek')->info("全局角色和场景更新成功", [
  12742. 'anime_id' => $anime_id,
  12743. 'roles_count' => count($new_global_roles),
  12744. 'scenes_count' => count($new_global_scenes),
  12745. ]);
  12746. } else {
  12747. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  12748. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  12749. }
  12750. }
  12751. }
  12752. }