DeepSeekService.php 672 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084
  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 Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Log;
  13. use Illuminate\Support\Facades\Redis;
  14. use OSS\Core\OssException;
  15. use OSS\OssClient;
  16. use Smalot\PdfParser\Parser as PdfParser;
  17. use TCPDF;
  18. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  19. use Predis\Command\Traits\Get\Get;
  20. class DeepSeekService
  21. {
  22. private $url;
  23. private $api_key;
  24. private $sys_message;
  25. private $headers;
  26. private $valid_text_models;
  27. private $gpt_text_models;
  28. protected $aiImageGenerationService;
  29. public function __construct(AIImageGenerationService $aiImageGenerationService) {
  30. $this->aiImageGenerationService = $aiImageGenerationService;
  31. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  32. $this->api_key = env('DEEPSEEK_API_KEY');
  33. $this->headers = [
  34. 'Authorization' => 'Bearer '.$this->api_key,
  35. 'Content-Type' => 'application/json; charset=UTF-8'
  36. ];
  37. // 火山引擎模型列表
  38. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  39. // GPT文本模型列表
  40. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  41. $this->sys_message = [
  42. 'role' => 'system',
  43. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  44. 强制要求:\n
  45. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  46. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  47. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  48. 普通要求:\n
  49. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  50. 2.<分集剧本>的要求如下:
  51.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  52.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  53.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  54.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  55. \n\n
  56. 示例如下:\n
  57. ###剧本名:西昆仑
  58. ###故事梗概
  59. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  60. ###剧本亮点
  61. 亮点1:绝境奇药,生死一线
  62. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  63. 亮点2:结拜兄妹,化解尴尬
  64. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  65. 亮点3:纤发夺命,情愫暗涌
  66. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  67. ###人物关系
  68. 阿雪与梁萧之间存在兄妹之情。
  69. ###核心矛盾
  70. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  71. ###主体列表
  72. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  73. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  74. 阴阳球:天地异宝,能化生精气,救人于危难。
  75. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  76. ###美术风格
  77. 基础画风风格词:厚涂古风
  78. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  79. ###场景列表
  80. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  81. ###分集剧本
  82. ##分集01
  83. 第1集: 第一集的标题
  84. 场景描述:地点、时间、场景
  85. 运镜:固定近距离
  86. 出场角色:男主、女主
  87. 台词内容:
  88. 女主: 女主对话
  89. 男主:男主对话
  90. 女主: 女主对话
  91. 男主: 男主对话
  92. ##分集02
  93. 第2集: 第二集的标题
  94. 场景描述:地点、时间、场景
  95. 运镜:固定近距离
  96. 出场角色:男主、女主
  97. 台词内容:
  98. 女主: 女主对话
  99. 男主:男主对话
  100. 女主: 女主对话
  101. 男主: 男主对话"
  102. ];
  103. }
  104. /**
  105. * 通用文生文方法 - 支持多模型流式输出和图片输入
  106. *
  107. * @param array $data 请求参数
  108. * @return \Generator 返回生成器,用于流式输出
  109. */
  110. public function generateText($data) {
  111. // 获取请求参数
  112. $model = getProp($data, 'model', 'deepseek-v3-2-251201'); // 默认使用deepseek-v3
  113. $messages = getProp($data, 'messages', []);
  114. $systemPrompt = getProp($data, 'system_prompt', '');
  115. $prompt = getProp($data, 'prompt', '');
  116. $images = getProp($data, 'images', []); // 支持多张图片
  117. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  118. // 如果没有提供messages,则根据system_prompt、content和images构建
  119. if (empty($messages)) {
  120. $messages = [];
  121. // 添加系统提示词
  122. if (!empty($systemPrompt)) {
  123. $messages[] = [
  124. 'role' => 'system',
  125. 'content' => $systemPrompt
  126. ];
  127. }
  128. // 构建用户消息内容(支持文本+图片)
  129. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  130. $userMessage = [
  131. 'role' => 'user',
  132. 'content' => []
  133. ];
  134. // 添加文本内容
  135. if (!empty($prompt)) {
  136. $userMessage['content'][] = [
  137. 'type' => 'text',
  138. 'text' => $prompt
  139. ];
  140. }
  141. // 处理上传的图片文件
  142. if (!empty($images)) {
  143. if (!is_array($images)) {
  144. $images = [$images];
  145. }
  146. foreach ($images as $image) {
  147. $imageBase64 = $this->processImageToBase64($image);
  148. if ($imageBase64) {
  149. $userMessage['content'][] = [
  150. 'type' => 'image_url',
  151. 'image_url' => [
  152. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  153. ]
  154. ];
  155. }
  156. }
  157. }
  158. // 处理图片URL
  159. if (!empty($imageUrls)) {
  160. if (!is_array($imageUrls)) {
  161. $imageUrls = [$imageUrls];
  162. }
  163. foreach ($imageUrls as $url) {
  164. if (!empty($url)) {
  165. $userMessage['content'][] = [
  166. 'type' => 'image_url',
  167. 'image_url' => [
  168. 'url' => $url
  169. ]
  170. ];
  171. }
  172. }
  173. }
  174. // 如果只有文本内容,简化为字符串格式
  175. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  176. $userMessage['content'] = $userMessage['content'][0]['text'];
  177. }
  178. $messages[] = $userMessage;
  179. }
  180. }
  181. // 验证messages不为空
  182. if (empty($messages)) {
  183. Utils::throwError('20003:请提供有效的对话内容');
  184. }
  185. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  186. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  187. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  188. if ($model === 'deepseek-chat') {
  189. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  190. $model = 'deepseek-v4-flash';
  191. $thinkingMode = 'disabled';
  192. } elseif ($model === 'deepseek-reasoner') {
  193. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  194. $model = 'deepseek-v4-flash';
  195. $thinkingMode = 'enabled';
  196. }
  197. // 构建请求参数
  198. $post_data = [
  199. 'model' => $model,
  200. 'messages' => $messages,
  201. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  202. 'temperature' => getProp($data, 'temperature', 1),
  203. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  204. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  205. 'thinking' => ['type' => $thinkingMode],
  206. 'stream' => true // 启用流式输出
  207. ];
  208. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  209. // 添加可选参数
  210. if (isset($data['top_p'])) {
  211. $post_data['top_p'] = $data['top_p'];
  212. }
  213. if (isset($data['response_format'])) {
  214. $post_data['response_format'] = $data['response_format'];
  215. }
  216. // 根据模型类型选择调用方法
  217. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  218. // DeepSeek 官方模型使用 DeepSeek API
  219. return $this->deepSeekStreamResponse($post_data);
  220. } else if (in_array($model, $this->gpt_text_models)) {
  221. // GPT 模型使用 TokenRouter API
  222. return $this->gpt54StreamResponse($post_data);
  223. } else if (in_array($model, $this->valid_text_models)) {
  224. // 火山引擎支持的模型使用火山引擎 API
  225. return $this->volcEngineChatCompletion($post_data);
  226. } else {
  227. Utils::throwError('20003:不支持的模型: ' . $model);
  228. }
  229. }
  230. public function createGenerateText($data) {
  231. $file = getProp($data, 'file');
  232. $uid = Site::getUid();
  233. $cpid = Site::getCpid();
  234. if (!$file) {
  235. Utils::throwError('20003:请上传文件');
  236. }
  237. // 提取文件内容
  238. $content = $this->extractFileContent($file);
  239. if (!$content) {
  240. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  241. }
  242. // 获取原始文件名(不含扩展名)作为script_name
  243. $originalName = $file->getClientOriginalName();
  244. $script_name = pathinfo($originalName, PATHINFO_FILENAME);
  245. if (!$script_name) {
  246. $script_name = '剧本_' . date('YmdHis');
  247. }
  248. // 如果剧本名称已存在,添加时间戳后缀
  249. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('is_deleted', 0)->exists()) {
  250. $script_name .= '_' . date('YmdHis');
  251. }
  252. // 插入数据到mp_scripts表
  253. $script_id = DB::table('mp_scripts')->insertGetId([
  254. 'script_name' => $script_name,
  255. 'user_id' => $uid,
  256. 'cpid' => $cpid,
  257. 'content' => $content,
  258. 'created_at' => date('Y-m-d H:i:s'),
  259. 'updated_at' => date('Y-m-d H:i:s')
  260. ]);
  261. return [
  262. 'script_id' => $script_id,
  263. 'script_name' => $script_name
  264. ];
  265. }
  266. /**
  267. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  268. *
  269. * @param array $data 请求参数
  270. * @return array 返回结果数组
  271. */
  272. public function newGenerateText($data) {
  273. // 获取请求参数
  274. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  275. $messages = getProp($data, 'messages', []);
  276. $systemPrompt = getProp($data, 'system_prompt', '');
  277. $prompt = getProp($data, 'prompt', '');
  278. $images = getProp($data, 'images', []); // 支持多张图片
  279. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  280. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  281. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  282. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  283. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  284. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  285. $originalContent = '';
  286. if ($script_id > 0) {
  287. $script = DB::table('mp_scripts')
  288. ->where('id', $script_id)
  289. ->where('is_deleted', 0)
  290. ->first();
  291. if (!$script) {
  292. Utils::throwError('20003:剧本不存在或已删除');
  293. }
  294. $originalContent = $script->content ?? '';
  295. if (empty($originalContent)) {
  296. Utils::throwError('20003:剧本内容为空');
  297. }
  298. // 将剧本内容添加到提示词前面
  299. if (!empty($originalContent)) {
  300. if (!empty($prompt)) {
  301. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  302. } else {
  303. $prompt = "原文内容:\n" . $originalContent;
  304. }
  305. }
  306. }
  307. // 新增: 如果提供了template_id,从数据库获取template_prompt
  308. if ($templateId > 0) {
  309. $template = DB::table('mp_prompt_templates')
  310. ->where('id', $templateId)
  311. ->where('is_deleted', 0)
  312. ->first();
  313. if (!$template) {
  314. Utils::throwError('20003:模板不存在或已删除');
  315. }
  316. $templatePrompt = $template->template_prompt ?? '';
  317. // 将模板提示词和用户输入的prompt组合
  318. // 模板为准,用户输入作为补充要求
  319. if (!empty($templatePrompt)) {
  320. if (!empty($prompt)) {
  321. $prompt = $templatePrompt . "\n\n" . $prompt;
  322. } else {
  323. $prompt = $templatePrompt;
  324. }
  325. }
  326. }
  327. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  328. if (empty($messages)) {
  329. $messages = [];
  330. // 添加系统提示词
  331. if (!empty($systemPrompt)) {
  332. $messages[] = [
  333. 'role' => 'system',
  334. 'content' => $systemPrompt
  335. ];
  336. }
  337. // 构建用户消息内容(支持文本+图片)
  338. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  339. $userMessage = [
  340. 'role' => 'user',
  341. 'content' => []
  342. ];
  343. // 添加文本内容
  344. if (!empty($prompt)) {
  345. $userMessage['content'][] = [
  346. 'type' => 'text',
  347. 'text' => $prompt
  348. ];
  349. }
  350. // 处理上传的图片文件
  351. if (!empty($images)) {
  352. if (!is_array($images)) {
  353. $images = [$images];
  354. }
  355. foreach ($images as $image) {
  356. $imageBase64 = $this->processImageToBase64($image);
  357. if ($imageBase64) {
  358. $userMessage['content'][] = [
  359. 'type' => 'image_url',
  360. 'image_url' => [
  361. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  362. ]
  363. ];
  364. }
  365. }
  366. }
  367. // 处理图片URL
  368. if (!empty($imageUrls)) {
  369. if (!is_array($imageUrls)) {
  370. $imageUrls = [$imageUrls];
  371. }
  372. foreach ($imageUrls as $url) {
  373. if (!empty($url)) {
  374. $userMessage['content'][] = [
  375. 'type' => 'image_url',
  376. 'image_url' => [
  377. 'url' => $url
  378. ]
  379. ];
  380. }
  381. }
  382. }
  383. // 如果只有文本内容,简化为字符串格式
  384. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  385. $userMessage['content'] = $userMessage['content'][0]['text'];
  386. }
  387. $messages[] = $userMessage;
  388. }
  389. }
  390. // 验证messages不为空
  391. if (empty($messages)) {
  392. Utils::throwError('20003:请提供有效的对话内容');
  393. }
  394. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  395. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  396. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  397. if ($model === 'deepseek-chat') {
  398. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  399. $model = 'deepseek-v4-flash';
  400. $thinkingMode = 'disabled';
  401. } elseif ($model === 'deepseek-reasoner') {
  402. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  403. $model = 'deepseek-v4-flash';
  404. $thinkingMode = 'enabled';
  405. }
  406. // 构建请求参数(非流式)
  407. $post_data = [
  408. 'model' => $model,
  409. 'messages' => $messages,
  410. 'temperature' => getProp($data, 'temperature', 1),
  411. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  412. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  413. 'thinking' => ['type' => $thinkingMode],
  414. 'stream' => false // 非流式输出
  415. ];
  416. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  417. // 添加可选参数
  418. if (isset($data['top_p'])) {
  419. $post_data['top_p'] = $data['top_p'];
  420. }
  421. // 新增: 根据response_format设置响应格式
  422. if ($responseFormat === 'json') {
  423. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  424. $hasJsonKeyword = false;
  425. foreach ($post_data['messages'] as $message) {
  426. if (isset($message['content'])) {
  427. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  428. if (stripos($content, 'json') !== false) {
  429. $hasJsonKeyword = true;
  430. break;
  431. }
  432. }
  433. }
  434. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  435. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  436. if (!$hasJsonKeyword) {
  437. $lastMessageIndex = count($post_data['messages']) - 1;
  438. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  439. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  440. // 如果content是字符串,直接追加
  441. if (is_string($lastContent)) {
  442. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  443. }
  444. // 如果content是数组(包含文本和图片),在文本部分追加
  445. else if (is_array($lastContent)) {
  446. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  447. if ($contentPart['type'] === 'text') {
  448. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  449. break;
  450. }
  451. }
  452. }
  453. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  454. }
  455. }
  456. // 设置response_format参数(所有支持的模型)
  457. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  458. // DeepSeek模型
  459. $post_data['response_format'] = ['type' => 'json_object'];
  460. } else if (in_array($model, $this->gpt_text_models)) {
  461. // GPT模型
  462. $post_data['response_format'] = ['type' => 'json_object'];
  463. } else if (in_array($model, $this->valid_text_models)) {
  464. // 火山引擎模型
  465. $post_data['response_format'] = ['type' => 'json_object'];
  466. }
  467. }
  468. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  469. $aiResult = null;
  470. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  471. // DeepSeek 官方模型使用现有的 chatOnly 方法
  472. $result = $this->chatOnly($post_data);
  473. // 记录实际使用的模型
  474. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  475. $aiResult = [
  476. 'content' => $result['fullContent'],
  477. 'reasoning_content' => $result['fullReasoningContent'],
  478. 'usage' => $result['usage'],
  479. 'model' => $model,
  480. 'finish_reason' => 'stop'
  481. ];
  482. } else if (in_array($model, $this->gpt_text_models)) {
  483. // GPT 模型使用现有的 gpt54ChatOnly 方法
  484. $result = $this->gpt54ChatOnly($post_data);
  485. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  486. $aiResult = [
  487. 'content' => $result['fullContent'],
  488. 'reasoning_content' => '',
  489. 'usage' => $result['usage'],
  490. 'model' => $model,
  491. 'finish_reason' => 'stop'
  492. ];
  493. } else if (in_array($model, $this->valid_text_models)) {
  494. // 火山引擎支持的模型使用火山引擎 API(非流式)
  495. $post_data['stream'] = false;
  496. $result = $this->volcEngineChatCompletion($post_data);
  497. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  498. 'requested_model' => $model,
  499. 'result_keys' => array_keys($result),
  500. 'has_fullContent' => isset($result['fullContent']),
  501. 'has_content' => isset($result['content'])
  502. ]);
  503. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  504. $aiResult = [
  505. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  506. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  507. 'usage' => $result['usage'] ?? [],
  508. 'model' => $model,
  509. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  510. ];
  511. } else {
  512. Utils::throwError('20003:不支持的模型: ' . $model);
  513. }
  514. // 新增: 如果提供了script_id,保存对话记录
  515. if ($script_id > 0 && $aiResult) {
  516. try {
  517. $uid = Site::getUid();
  518. $now = now();
  519. // 获取用户原始的prompt(不包含剧本内容)
  520. $originalPrompt = getProp($data, 'prompt', '');
  521. $recordsToInsert = [
  522. [
  523. 'uid' => $uid,
  524. 'script_id' => $script_id,
  525. 'sequence' => $sequence,
  526. 'role' => 'user',
  527. 'content' => $originalPrompt,
  528. 'created_at' => $now,
  529. 'updated_at' => $now,
  530. ],
  531. [
  532. 'uid' => $uid,
  533. 'script_id' => $script_id,
  534. 'sequence' => $sequence,
  535. 'role' => 'assistant',
  536. 'content' => $aiResult['content'],
  537. 'created_at' => $now,
  538. 'updated_at' => $now,
  539. ]
  540. ];
  541. DB::table('mp_script_records')->insert($recordsToInsert);
  542. // 获取刚插入的记录ID(假设按插入顺序返回)
  543. $insertedRecords = DB::table('mp_script_records')
  544. ->where('uid', $uid)
  545. ->where('script_id', $script_id)
  546. ->where('sequence', $sequence)
  547. ->orderBy('id', 'desc')
  548. ->limit(2)
  549. ->get()
  550. ->map(function ($record) {
  551. return [
  552. 'rid' => $record->id,
  553. 'script_id' => $record->script_id,
  554. 'sequence' => $record->sequence,
  555. 'role' => $record->role,
  556. 'content' => $record->content,
  557. 'created_at' => $record->created_at,
  558. ];
  559. })
  560. ->reverse()
  561. ->values()
  562. ->toArray();
  563. // 将记录信息添加到返回结果中
  564. $aiResult['records'] = $insertedRecords;
  565. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  566. } catch (\Exception $e) {
  567. // 记录错误但不影响主流程
  568. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  569. }
  570. }
  571. return $aiResult;
  572. }
  573. public function saveScriptChatHistory($data) {
  574. $uid = Site::getUid();
  575. $rid = getProp($data, 'rid');
  576. $script_id = getProp($data, 'script_id');
  577. $sequence = getProp($data, 'sequence', 0);
  578. $content = getProp($data, 'content');
  579. if (!$rid) {
  580. Utils::throwError('20003:请选择对话记录ID');
  581. }
  582. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  583. if (!$record) {
  584. Utils::throwError('20003:对话记录不存在');
  585. }
  586. if (!$script_id) {
  587. Utils::throwError('20003:请选择剧本');
  588. }
  589. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  590. if (!$script) {
  591. Utils::throwError('20003:剧本不存在');
  592. }
  593. // 批量插入数据
  594. return DB::table('mp_script_records')->where('id', $rid)->update([
  595. 'content' => $content,
  596. 'updated_at' => date('Y-m-d H:i:s')
  597. ]);
  598. }
  599. /**
  600. * 获取剧本的历史对话记录
  601. *
  602. * @param array $data 请求参数
  603. * @return array 返回历史记录数组
  604. */
  605. public function getScriptChatHistory($data) {
  606. $uid = Site::getUid();
  607. $script_id = getProp($data, 'script_id');
  608. $rid = getProp($data, 'rid');
  609. $sequence = getProp($data, 'sequence', null);
  610. if (!$script_id) {
  611. Utils::throwError('20003:请提供剧本ID');
  612. }
  613. // 验证剧本是否存在
  614. $script = DB::table('mp_scripts')
  615. ->where('id', $script_id)
  616. ->where('is_deleted', 0)
  617. ->first();
  618. if (!$script) {
  619. Utils::throwError('20003:剧本不存在');
  620. }
  621. // 构建查询
  622. $query = DB::table('mp_script_records')
  623. ->where('script_id', $script_id);
  624. // ->where('uid', $uid);
  625. // 如果提供了 sequence,则过滤指定剧集
  626. if ($sequence !== null) {
  627. $query->where('sequence', $sequence);
  628. }
  629. // 记录ID筛选
  630. if ($rid) {
  631. $query->where('id', $rid);
  632. }
  633. // 查询记录并按 id 正序排序
  634. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  635. ->orderBy('created_at', 'asc')
  636. ->orderBy('id', 'asc')
  637. ->get()
  638. ->map(function ($record) {
  639. return [
  640. 'rid' => $record->id,
  641. 'script_id' => $record->script_id,
  642. 'sequence' => $record->sequence,
  643. 'role' => $record->role,
  644. 'content' => $record->content,
  645. 'products' => $record->products ? json_decode($record->products) : [],
  646. 'created_at' => $record->created_at,
  647. ];
  648. })
  649. ->toArray();
  650. return $records;
  651. }
  652. /**
  653. * 处理图片转换为base64
  654. *
  655. * @param mixed $image 图片文件对象或文件路径
  656. * @return string|null base64编码的图片数据
  657. */
  658. private function processImageToBase64($image) {
  659. try {
  660. // 获取文件路径
  661. if (is_string($image)) {
  662. $filePath = $image;
  663. } else {
  664. // Laravel UploadedFile 对象
  665. $filePath = $image->getRealPath();
  666. }
  667. if (!file_exists($filePath)) {
  668. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  669. return null;
  670. }
  671. // 验证是否为图片文件
  672. $imageInfo = @getimagesize($filePath);
  673. if ($imageInfo === false) {
  674. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  675. return null;
  676. }
  677. // 读取图片并转换为base64
  678. $imageData = file_get_contents($filePath);
  679. $base64Image = base64_encode($imageData);
  680. dLog('deepseek')->info('图片转换成功', [
  681. 'size' => strlen($imageData),
  682. 'type' => $imageInfo['mime']
  683. ]);
  684. return $base64Image;
  685. } catch (\Exception $e) {
  686. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  687. return null;
  688. }
  689. }
  690. private function getArtStylePromptMappings($art_style='')
  691. {
  692. $arr = [
  693. '唯美真人风格' => [
  694. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  695. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  696. ],
  697. '真人古风风格' => [
  698. 'aliases' => ['真人古风风格', '真人古风'],
  699. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  700. ],
  701. '日系动漫风格' => [
  702. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  703. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  704. ],
  705. '国漫风格' => [
  706. 'aliases' => ['国漫风格', '国漫'],
  707. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  708. ],
  709. 'Q版卡通风格' => [
  710. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  711. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  712. ],
  713. '简约扁平风格' => [
  714. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  715. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  716. ],
  717. '武侠风格' => [
  718. 'aliases' => ['武侠风格', '武侠'],
  719. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  720. ],
  721. '古风仙侠风格' => [
  722. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  723. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  724. ],
  725. '新中式水墨风格' => [
  726. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  727. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  728. ],
  729. '写实插画风格' => [
  730. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  731. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  732. ],
  733. '3D卡通风格' => [
  734. 'aliases' => ['3D卡通风格', '3D卡通'],
  735. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  736. ],
  737. '条漫风格' => [
  738. 'aliases' => ['条漫风格', '条漫'],
  739. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  740. ],
  741. '赛博朋克风格' => [
  742. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  743. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  744. ],
  745. '暗黑悬疑风格' => [
  746. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  747. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  748. ],
  749. '治愈清新风格' => [
  750. 'aliases' => ['治愈清新风格', '治愈清新'],
  751. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  752. ],
  753. ];
  754. if($art_style) {
  755. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  756. }
  757. return $arr;
  758. $arr = [
  759. '唯美真人风格' => [
  760. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  761. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  762. 2. 色彩色调
  763. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  764. 3. 画质精度
  765. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  766. 4. 画面观感
  767. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  768. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  769. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  770. ],
  771. '真人古风风格' => [
  772. 'aliases' => ['真人古风风格', '真人古风'],
  773. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  774. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  775. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  776. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  777. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  778. ],
  779. '日系动漫风格' => [
  780. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  781. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  782. 正向提示词(中文)
  783. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  784. 必须遵守规则
  785. • 全程保持日系动漫风格,不混入其他画风
  786. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  787. • 画面适配所选画面比例,构图居中,主体突出
  788. • 线条干净、色彩统一,不杂乱、不突兀
  789. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  790. ],
  791. '国漫风格' => [
  792. 'aliases' => ['国漫风格', '国漫'],
  793. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  794. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  795. 必须遵守规则
  796. • 严格保持国漫画风,不串风格、不混画风
  797. • 角色形象统一,不随意改变五官、身材、服饰
  798. • 画面构图稳定,适合漫剧叙事展示
  799. • 色调统一,不出现脏色、杂色
  800. 禁止/避免词汇
  801. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  802. ],
  803. 'Q版卡通风格' => [
  804. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  805. 'prompt' => "风格说明
  806. 头大身小,造型可爱圆润,简约干净
  807. 正向提示词(中文)
  808. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  809. 必须遵守规则
  810. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  811. • 角色造型统一,表情可爱,不诡异
  812. • 画面简洁清爽,无多余复杂元素
  813. • 色彩明亮柔和,不刺眼
  814. 禁止/避免词汇
  815. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  816. ],
  817. '简约扁平风格' => [
  818. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  819. 'prompt' => "风格说明
  820. 色块简洁、无复杂渐变,现代极简风
  821. 正向提示词(中文)
  822. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  823. 必须遵守规则
  824. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  825. • 构图简洁,主体突出,无多余装饰
  826. • 色彩统一、干净,不杂乱
  827. 禁止/避免词汇
  828. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  829. ],
  830. '武侠风格' => [
  831. 'aliases' => ['武侠风格', '武侠'],
  832. 'prompt' => "风格说明
  833. 江湖气息,线条硬朗,动作感强
  834. 正向提示词(中文)
  835. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  836. 必须遵守规则
  837. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  838. • 角色形象、服饰、身材比例统一
  839. • 画面动作自然,不扭曲、不畸形
  840. 禁止/避免词汇
  841. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  842. ],
  843. '古风仙侠风格' => [
  844. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  845. 'prompt' => "风格说明
  846. 飘逸汉服、云雾仙气、唯美空灵
  847. 正向提示词(中文)
  848. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  849. 必须遵守规则
  850. • 保持古风仙侠统一画风,不混入现代、科幻元素
  851. • 角色服饰、发型、形象前后一致
  852. • 场景仙气飘逸,色调清雅统一
  853. • 画面唯美柔和,不阴暗、不诡异
  854. 禁止/避免词汇
  855. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  856. ],
  857. '新中式水墨风格' => [
  858. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  859. 'prompt' => "风格说明
  860. 淡墨渲染,毛笔笔触,留白意境
  861. 正向提示词(中文)
  862. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  863. 必须遵守规则
  864. • 严格保持水墨质感,不混入厚涂、写实、卡通
  865. • 色调淡雅统一,不浓艳杂乱
  866. • 画面干净有意境,不堆砌元素
  867. 禁止/避免词汇
  868. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  869. ],
  870. '写实插画风格' => [
  871. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  872. 'prompt' => "风格说明
  873. 接近真人比例,光影真实,质感细腻
  874. 正向提示词(中文)
  875. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  876. 必须遵守规则
  877. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  878. • 角色五官、身材、服饰高度统一
  879. • 画面清晰、光影自然、不扭曲
  880. 禁止/避免词汇
  881. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  882. ],
  883. '3D卡通风格' => [
  884. 'aliases' => ['3D卡通风格', '3D卡通'],
  885. 'prompt' => "风格说明
  886. 3D建模质感,柔和渲染,圆润可爱
  887. 正向提示词(中文)
  888. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  889. 必须遵守规则
  890. • 保持3D卡通统一质感,不出现2D杂乱线条
  891. • 角色模型、比例、形象前后一致
  892. • 画面干净,不模糊、不穿模
  893. 禁止/避免词汇
  894. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  895. ],
  896. '条漫风格' => [
  897. 'aliases' => ['条漫风格', '条漫'],
  898. 'prompt' => "风格说明
  899. 纵向分镜,上下滑动阅读,轻量化
  900. 正向提示词(中文)
  901. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  902. 必须遵守规则
  903. • 保持条漫纵向阅读逻辑,构图简洁
  904. • 画风统一,不混写实、3D、水墨
  905. • 画面干净,不杂乱
  906. 禁止/避免词汇
  907. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  908. ],
  909. '赛博朋克风格' => [
  910. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  911. 'prompt' => "风格说明
  912. 霓虹灯光、未来都市、暗色调、科技机械
  913. 正向提示词(中文)
  914. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  915. 必须遵守规则
  916. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  917. • 色调以暗调+霓虹为主,色彩统一
  918. • 画面科技感强,不杂乱
  919. 禁止/避免词汇
  920. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  921. ],
  922. '暗黑悬疑风格' => [
  923. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  924. 'prompt' => "风格说明
  925. 低饱和、冷色调、阴影重、神秘压抑
  926. 正向提示词(中文)
  927. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  928. 必须遵守规则
  929. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  930. • 画面氛围压抑神秘,但不低俗、不血腥
  931. • 角色形象统一,不崩坏
  932. 禁止/避免词汇
  933. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  934. ],
  935. '治愈清新风格' => [
  936. 'aliases' => ['治愈清新风格', '治愈清新'],
  937. 'prompt' => "风格说明
  938. 马卡龙色系、柔光、温暖干净
  939. 正向提示词(中文)
  940. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  941. 必须遵守规则
  942. • 保持治愈清新统一色调,不阴暗、不诡异
  943. • 画面柔和干净,无杂乱元素
  944. • 角色形象柔和可爱,不狰狞
  945. 禁止/避免词汇
  946. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  947. ],
  948. ];
  949. return $arr;
  950. }
  951. public function getArtStylePromptByInput($inputArtStyle): string
  952. {
  953. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  954. if ($normalizedInput === '') {
  955. return '';
  956. }
  957. return $this->getArtStylePromptMappings($normalizedInput);
  958. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  959. // foreach ($mapping['aliases'] as $alias) {
  960. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  961. // if ($normalizedAlias === '') {
  962. // continue;
  963. // }
  964. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  965. // return $mapping['prompt'];
  966. // }
  967. // }
  968. // }
  969. return '';
  970. }
  971. public function getArtStyleShortPromptByInput($inputArtStyle) {
  972. $stylePrefixes = [
  973. '唯美真人风格' => [
  974. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  975. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  976. ],
  977. '真人古风风格' => [
  978. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  979. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  980. ],
  981. '日系动漫风格' => [
  982. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  983. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  984. ],
  985. '国漫风格' => [
  986. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  987. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  988. ],
  989. 'Q版卡通风格' => [
  990. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  991. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  992. ],
  993. '简约扁平风格' => [
  994. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  995. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  996. ],
  997. '武侠风格' => [
  998. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  999. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  1000. ],
  1001. '古风仙侠风格' => [
  1002. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  1003. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  1004. ],
  1005. '新中式水墨风格' => [
  1006. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  1007. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  1008. ],
  1009. '写实插画风格' => [
  1010. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  1011. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  1012. ],
  1013. '3D卡通风格' => [
  1014. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  1015. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  1016. ],
  1017. '条漫风格' => [
  1018. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  1019. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  1020. ],
  1021. '赛博朋克风格' => [
  1022. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  1023. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  1024. ],
  1025. '暗黑悬疑风格' => [
  1026. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  1027. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  1028. ],
  1029. '治愈清新风格' => [
  1030. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  1031. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  1032. ]
  1033. ];
  1034. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  1035. }
  1036. private function normalizeArtStyleInput($value): string
  1037. {
  1038. $value = trim((string)$value);
  1039. if ($value === '') {
  1040. return '';
  1041. }
  1042. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  1043. return mb_strtolower($value, 'UTF-8');
  1044. }
  1045. private function replaceArtStyleSection(string $content, string $artStyle): string
  1046. {
  1047. if ($content === '' || $artStyle === '') {
  1048. return $content;
  1049. }
  1050. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  1051. if (!preg_match($pattern, $content)) {
  1052. return $content;
  1053. }
  1054. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  1055. }
  1056. /**
  1057. * DeepSeek流式输出处理方法
  1058. *
  1059. * @param array $post_data DeepSeek API请求参数
  1060. * @return \Generator 返回生成器,用于流式输出
  1061. */
  1062. private function deepSeekStreamResponse($post_data) {
  1063. // 设置最大输出tokens
  1064. $post_data['max_tokens'] = 300000;
  1065. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1066. $response = $client->post($this->url, [
  1067. 'json' => $post_data,
  1068. 'headers' => $this->headers,
  1069. 'stream' => true // 启用流式响应
  1070. ]);
  1071. $body = $response->getBody();
  1072. $fullContent = '';
  1073. $fullReasoningContent = '';
  1074. $usage = [];
  1075. $buffer = '';
  1076. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1077. // 逐行读取流式响应
  1078. while (!$body->eof()) {
  1079. $chunk = $body->read(1024); // 每次读取 1KB
  1080. $buffer .= $chunk;
  1081. // 按行分割
  1082. $lines = explode("\n", $buffer);
  1083. // 保留最后一个不完整的行
  1084. $buffer = array_pop($lines);
  1085. foreach ($lines as $line) {
  1086. $line = trim($line);
  1087. // 跳过空行
  1088. if (empty($line)) {
  1089. continue;
  1090. }
  1091. // 检查是否是 SSE 数据行
  1092. if (strpos($line, 'data: ') !== 0) {
  1093. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1094. continue;
  1095. }
  1096. $data = substr($line, 6); // 移除 "data: " 前缀
  1097. if ($data === '[DONE]') {
  1098. dLog('deepseek')->info('收到结束标记');
  1099. break 2; // 跳出两层循环
  1100. }
  1101. try {
  1102. $json = json_decode($data, true);
  1103. if (json_last_error() !== JSON_ERROR_NONE) {
  1104. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1105. continue;
  1106. }
  1107. if (isset($json['choices'][0]['delta'])) {
  1108. $delta = $json['choices'][0]['delta'];
  1109. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1110. if (isset($delta['reasoning_content'])) {
  1111. $fullReasoningContent .= $delta['reasoning_content'];
  1112. yield [
  1113. 'type' => 'reasoning',
  1114. 'content' => $delta['reasoning_content'],
  1115. 'full_reasoning' => $fullReasoningContent
  1116. ];
  1117. }
  1118. // 处理最终回答内容
  1119. if (isset($delta['content'])) {
  1120. $fullContent .= $delta['content'];
  1121. yield [
  1122. 'type' => 'content',
  1123. 'content' => $delta['content'],
  1124. ];
  1125. }
  1126. }
  1127. // 获取使用统计信息
  1128. if (isset($json['usage'])) {
  1129. $usage = $json['usage'];
  1130. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1131. }
  1132. } catch (\Exception $e) {
  1133. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1134. continue;
  1135. }
  1136. }
  1137. }
  1138. dLog('deepseek')->info('流式读取完成', [
  1139. 'content_length' => strlen($fullContent),
  1140. 'reasoning_length' => strlen($fullReasoningContent)
  1141. ]);
  1142. yield [
  1143. 'type' => 'done',
  1144. 'full_content' => $fullContent,
  1145. 'full_reasoning' => $fullReasoningContent,
  1146. 'usage' => $usage
  1147. ];
  1148. }
  1149. /**
  1150. * GPT 流式输出处理方法
  1151. *
  1152. * @param array $post_data GPT API请求参数
  1153. * @return \Generator 返回生成器,用于流式输出
  1154. */
  1155. private function gpt54StreamResponse($post_data) {
  1156. $apiKey = env('GPT_54_API_KEY');
  1157. if (empty($apiKey)) {
  1158. Utils::throwError('20003:GPT API Key未配置');
  1159. }
  1160. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1161. $headers = [
  1162. 'Authorization' => 'Bearer ' . $apiKey,
  1163. 'Content-Type' => 'application/json'
  1164. ];
  1165. // 移除 thinking 参数,GPT-5.4 不支持
  1166. if (isset($post_data['thinking'])) {
  1167. unset($post_data['thinking']);
  1168. }
  1169. if (isset($post_data['reasoning_effort'])) {
  1170. unset($post_data['reasoning_effort']);
  1171. }
  1172. $post_data['max_completion_tokens'] = 100000;
  1173. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  1174. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  1175. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  1176. 'json' => $post_data,
  1177. 'headers' => $headers
  1178. ]);
  1179. $body = $response->getBody();
  1180. $fullContent = '';
  1181. $usage = [];
  1182. $buffer = '';
  1183. dLog('deepseek')->info('开始读取 GPT 流式响应');
  1184. // 逐行读取流式响应
  1185. while (!$body->eof()) {
  1186. $chunk = $body->read(1024); // 每次读取 1KB
  1187. $buffer .= $chunk;
  1188. // 按行分割
  1189. $lines = explode("\n", $buffer);
  1190. // 保留最后一个不完整的行
  1191. $buffer = array_pop($lines);
  1192. foreach ($lines as $line) {
  1193. $line = trim($line);
  1194. // 跳过空行
  1195. if (empty($line)) {
  1196. continue;
  1197. }
  1198. // 检查是否是 SSE 数据行
  1199. if (strpos($line, 'data: ') !== 0) {
  1200. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1201. continue;
  1202. }
  1203. $data = substr($line, 6); // 移除 "data: " 前缀
  1204. if ($data === '[DONE]') {
  1205. dLog('deepseek')->info('收到结束标记');
  1206. break 2; // 跳出两层循环
  1207. }
  1208. try {
  1209. $json = json_decode($data, true);
  1210. if (json_last_error() !== JSON_ERROR_NONE) {
  1211. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1212. continue;
  1213. }
  1214. if (isset($json['choices'][0]['delta'])) {
  1215. $delta = $json['choices'][0]['delta'];
  1216. // 处理回答内容
  1217. if (isset($delta['content'])) {
  1218. $fullContent .= $delta['content'];
  1219. yield [
  1220. 'type' => 'content',
  1221. 'content' => $delta['content'],
  1222. ];
  1223. }
  1224. }
  1225. // 获取使用统计信息
  1226. if (isset($json['usage'])) {
  1227. $usage = $json['usage'];
  1228. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1229. }
  1230. } catch (\Exception $e) {
  1231. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1232. continue;
  1233. }
  1234. }
  1235. }
  1236. dLog('deepseek')->info('流式读取完成', [
  1237. 'content_length' => strlen($fullContent)
  1238. ]);
  1239. yield [
  1240. 'type' => 'done',
  1241. 'full_content' => $fullContent,
  1242. 'full_reasoning' => '',
  1243. 'usage' => $usage
  1244. ];
  1245. }
  1246. // 与推理模型对话
  1247. public function chatWithReasoner($data) {
  1248. $content = getProp($data, 'content');
  1249. $model = getProp($data, 'model', 'r1');
  1250. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1251. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1252. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1253. if ($model == 'r1') {
  1254. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  1255. $thinkingMode = 'disabled';
  1256. } else {
  1257. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  1258. $thinkingMode = 'disabled';
  1259. }
  1260. // 获取可选情感(根据音色可支持情感选)
  1261. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  1262. $emotion_list = [];
  1263. foreach ($timbre_emotion as $emotion) {
  1264. $tmp = explode(',', $emotion);
  1265. $emotion_list = array_merge($emotion_list, $tmp);
  1266. }
  1267. $emotion_list = array_unique($emotion_list);
  1268. $emotion_str = implode('、', $emotion_list);
  1269. // // 获取可选情感
  1270. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  1271. // $emotion_str = implode('、', $emotion_list);
  1272. // 是否启用情感
  1273. $enable_emotion = getProp($data, 'enable_emotion', 0);
  1274. if ($enable_emotion) {
  1275. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  1276. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1277. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  1278. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  1279. }else {
  1280. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  1281. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1282. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  1283. }
  1284. $messages = [
  1285. [
  1286. 'role' => 'system',
  1287. 'content' => $sys_content
  1288. ],
  1289. [
  1290. 'role' => 'user',
  1291. 'content' => $content
  1292. ]
  1293. ];
  1294. $post_data = [
  1295. 'model' => $model,
  1296. 'messages' => $messages,
  1297. // 'max_tokens' => 8192,
  1298. 'temperature' => 1,
  1299. 'frequency_penalty' => 0,
  1300. 'presence_penalty' => 0,
  1301. 'thinking' => ['type' => $thinkingMode],
  1302. 'response_format' => [
  1303. 'type' => 'text'
  1304. ],
  1305. 'stream' => false
  1306. ];
  1307. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1308. // 根据模型类型选择调用方法
  1309. $fullContent = '';
  1310. $usage = [];
  1311. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1312. // DeepSeek 官方模型使用 DeepSeek API
  1313. $chatResult = $this->chatOnly($post_data);
  1314. } else if (in_array($model, $this->gpt_text_models)) {
  1315. // GPT-5.4 模型使用 TokenRouter API
  1316. $chatResult = $this->gpt54ChatOnly($post_data);
  1317. } else {
  1318. // 其他模型使用火山引擎API
  1319. $chatResult = $this->volcEngineChatCompletion($post_data);
  1320. }
  1321. if (is_array($chatResult)) {
  1322. $fullContent = $chatResult['fullContent'];
  1323. $usage = $chatResult['usage'];
  1324. }
  1325. // 处理获取到的剧本数据
  1326. $script_content = handleScriptWords($fullContent, $enable_emotion);
  1327. $result = [
  1328. 'origin_content' => $fullContent,
  1329. 'roles' => getProp($script_content, 'roles'),
  1330. 'words' => getProp($script_content, 'words'),
  1331. ];
  1332. return $result;
  1333. }
  1334. public function resetParagraphAudio($data) {
  1335. $bid = getProp($data, 'bid');
  1336. $cid = getProp($data, 'cid');
  1337. $version_id = getProp($data, 'version_id');
  1338. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  1339. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  1340. 'generate_status' => '待制作',
  1341. 'updated_at' => date('Y-m-d H:i:s')
  1342. ]);
  1343. }
  1344. public function saveParagraphAudio($data) {
  1345. $bid = getProp($data, 'bid');
  1346. $cid = getProp($data, 'cid');
  1347. $version_id = getProp($data, 'version_id');
  1348. $sequence = getProp($data, 'sequence');
  1349. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  1350. // 获取所有情感
  1351. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1352. $emotion_list = array_flip($emotion_list);
  1353. // 获取音色支持情感
  1354. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  1355. $timbre_emotion = explode(',', $timbre_emotion);
  1356. $emotion = getProp($data, 'emotion');
  1357. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  1358. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  1359. $list = [
  1360. 'bid' => $bid,
  1361. 'cid' => $cid,
  1362. 'version_id' => $version_id,
  1363. 'sequence' => $sequence,
  1364. 'role' => getProp($data, 'role'),
  1365. 'gender' => getProp($data, 'gender'),
  1366. 'text' => trim(getProp($data, 'text')),
  1367. 'emotion' => $emotion,
  1368. 'emotion_type' => $emotion_type,
  1369. 'voice_type' => getProp($data, 'voice_type'),
  1370. 'voice_name' => getProp($data, 'voice_name'),
  1371. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  1372. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  1373. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  1374. 'pitch' => getProp($data, 'pitch', 0),
  1375. // 'paragraph_audio_url' => '',
  1376. 'generate_status' => '制作中',
  1377. 'error_msg' => '',
  1378. 'updated_at' => date('Y-m-d H:i:s')
  1379. ];
  1380. $continue = false;
  1381. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  1382. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  1383. $list['generate_status'] = '制作成功';
  1384. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1385. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  1386. $continue = true;
  1387. }
  1388. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  1389. if ($id) {
  1390. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  1391. }else {
  1392. $list['created_at'] = date('Y-m-d H:i:s');
  1393. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  1394. $boolen = $id ? true : false;
  1395. }
  1396. // 如果更新成功则加入查询队列
  1397. if ($boolen) {
  1398. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  1399. Redis::sadd($redis_key, $id);
  1400. }
  1401. if ($boolen && !$continue) {
  1402. $boolen = false;
  1403. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1404. // 根据ID通过API通知合成音频
  1405. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  1406. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  1407. $response = $result->getBody()->getContents();
  1408. $response_arr = json_decode($response, true);
  1409. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1410. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1411. Log::info('通知火山生成段落音频失败: '.$error_msg);
  1412. Utils::throwError('20003:通知火山生成段落音频失败');
  1413. }
  1414. $boolen = true;
  1415. }
  1416. return $boolen;
  1417. }
  1418. public function insertAudioEffect($data) {
  1419. $audio_id = getProp($data, 'audio_id');
  1420. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1421. $bid = getProp($chapter_audio, 'bid');
  1422. $version_id = getProp($chapter_audio, 'version_id');
  1423. $cid = getProp($chapter_audio, 'cid');
  1424. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1425. $audio_effect_json = getProp($data, 'audio_effect_json');
  1426. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  1427. try {
  1428. DB::beginTransaction();
  1429. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1430. if (!$count) {
  1431. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1432. }else {
  1433. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1434. }
  1435. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1436. 'audio_effect_status' => '添加中',
  1437. 'audio_effect_json' => $audio_effect_json,
  1438. 'updated_at' => date('Y-m-d H:i:s')
  1439. ]);
  1440. if (!$boolen1) {
  1441. DB::rollBack();
  1442. Utils::throwError('20003:更新生成数据失败');
  1443. }
  1444. $id = DB::table('mp_audio_tasks')->insertGetId([
  1445. 'audio_id' => $audio_id,
  1446. 'generate_status' => '执行中',
  1447. 'generate_json' => json_encode([], 256),
  1448. 'bid' => $bid,
  1449. 'book_name' => getProp($chapter_audio, 'book_name'),
  1450. 'version_id' => $version_id,
  1451. 'version_name' => getProp($chapter_audio, 'version_name'),
  1452. 'cid' => $cid,
  1453. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1454. 'task_name' => $task_name,
  1455. 'created_at' => date('Y-m-d H:i:s'),
  1456. 'updated_at' => date('Y-m-d H:i:s')
  1457. ]);
  1458. if (!$id) {
  1459. DB::rollBack();
  1460. Utils::throwError('20003:创建任务失败');
  1461. }
  1462. }catch (\Exception $e) {
  1463. DB::rollBack();
  1464. Utils::throwError('20003:'.$e->getMessage());
  1465. }
  1466. DB::commit();
  1467. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1468. // 根据ID通过API通知合成音频
  1469. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1470. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1471. $response = $result->getBody()->getContents();
  1472. $response_arr = json_decode($response, true);
  1473. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1474. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1475. Log::info('通知火山插入音效失败: '.$error_msg);
  1476. Utils::throwError('20003:通知火山插入音效失败');
  1477. }
  1478. return true;
  1479. }
  1480. public function insertBgm($data) {
  1481. $audio_id = getProp($data, 'audio_id');
  1482. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1483. $bid = getProp($chapter_audio, 'bid');
  1484. $version_id = getProp($chapter_audio, 'version_id');
  1485. $cid = getProp($chapter_audio, 'cid');
  1486. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1487. $bgm_json = getProp($data, 'bgm_json');
  1488. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1489. if (!$bgm_json) {
  1490. $bgm_json = getProp($data, 'audio_effect_json');
  1491. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1492. }
  1493. try {
  1494. DB::beginTransaction();
  1495. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1496. if (!$count) {
  1497. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1498. }else {
  1499. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1500. }
  1501. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1502. 'bgm_status' => '添加中',
  1503. 'bgm_json' => $bgm_json,
  1504. 'updated_at' => date('Y-m-d H:i:s')
  1505. ]);
  1506. if (!$boolen1) {
  1507. DB::rollBack();
  1508. Utils::throwError('20003:更新生成数据失败');
  1509. }
  1510. $id = DB::table('mp_audio_tasks')->insertGetId([
  1511. 'audio_id' => $audio_id,
  1512. 'generate_status' => '执行中',
  1513. 'generate_json' => json_encode([], 256),
  1514. 'bid' => $bid,
  1515. 'book_name' => getProp($chapter_audio, 'book_name'),
  1516. 'version_id' => $version_id,
  1517. 'version_name' => getProp($chapter_audio, 'version_name'),
  1518. 'cid' => $cid,
  1519. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1520. 'task_name' => $task_name,
  1521. 'created_at' => date('Y-m-d H:i:s'),
  1522. 'updated_at' => date('Y-m-d H:i:s')
  1523. ]);
  1524. if (!$id) {
  1525. DB::rollBack();
  1526. Utils::throwError('20003:创建任务失败');
  1527. }
  1528. }catch (\Exception $e) {
  1529. DB::rollBack();
  1530. Utils::throwError('20003:'.$e->getMessage());
  1531. }
  1532. DB::commit();
  1533. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1534. // 根据ID通过API通知合成音频
  1535. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1536. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1537. $response = $result->getBody()->getContents();
  1538. $response_arr = json_decode($response, true);
  1539. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1540. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1541. Log::info('通知火山插入bgm失败: '.$error_msg);
  1542. Utils::throwError('20003:通知火山插入bgm失败');
  1543. }
  1544. return true;
  1545. }
  1546. public function getParagraphAudios($data) {
  1547. $bid = getProp($data, 'bid');
  1548. $cid = getProp($data, 'cid');
  1549. $version_id = getProp($data, 'version_id');
  1550. $sequence = getProp($data, 'sequence');
  1551. // 获取已生成的音频
  1552. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  1553. if ($sequence) $query->where('sequence', $sequence);
  1554. $paragraph_audios = $query->orderBy('sequence')->get();
  1555. $result = [];
  1556. foreach($paragraph_audios as $item) {
  1557. $result[] = [
  1558. 'sequence' => getProp($item, 'sequence'),
  1559. 'role' => getProp($item, 'role'),
  1560. 'gender' => getProp($item, 'gender'),
  1561. 'text' => trim(getProp($item, 'text')),
  1562. 'emotion' => getProp($item, 'emotion'),
  1563. 'emotion_type' => getProp($item, 'emotion_type'),
  1564. 'voice_type' => getProp($item, 'voice_type'),
  1565. 'voice_name' => getProp($item, 'voice_name'),
  1566. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1567. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1568. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1569. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1570. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  1571. ];
  1572. }
  1573. return $result;
  1574. }
  1575. // 新增合成任务
  1576. public function addGenerateTask($data) {
  1577. $bid = getProp($data, 'bid');
  1578. $cid = getProp($data, 'cid');
  1579. $version_id = getProp($data, 'version_id');
  1580. $generate_json = getProp($data, 'generate_json');
  1581. // 获取已生成的音频
  1582. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  1583. $paragraph_list = [];
  1584. foreach($paragraph_audios as $item) {
  1585. $paragraph_list[getProp($item, 'sequence')] = [
  1586. 'role' => getProp($item, 'role'),
  1587. 'gender' => getProp($item, 'gender'),
  1588. 'text' => trim(getProp($item, 'text')),
  1589. 'emotion' => getProp($item, 'emotion'),
  1590. 'emotion_type' => getProp($item, 'emotion_type'),
  1591. 'voice_type' => getProp($item, 'voice_type'),
  1592. 'voice_name' => getProp($item, 'voice_name'),
  1593. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1594. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1595. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1596. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1597. ];
  1598. }
  1599. // 更新角色-音色信息
  1600. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  1601. $existed_role_info = json_decode($existed_role_info, true);
  1602. if (!$existed_role_info) $existed_role_info = [];
  1603. // 获取情感信息
  1604. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1605. $emotion_list = array_flip($emotion_list);
  1606. // 获取音色对应情感组
  1607. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  1608. $timbre_emotion_list = [];
  1609. foreach($timbre_emotions as $item) {
  1610. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  1611. }
  1612. // 构造生成音频的json
  1613. $words = json_decode($generate_json, true);
  1614. // 最终合成前的参数组
  1615. $mp_chapter_paragraph_audios = [];
  1616. $sequence = 1;
  1617. $complete_paragraph_sequences = [];
  1618. foreach($words as &$word) {
  1619. 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:参数格式有误');
  1620. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  1621. $role = getProp($word, 'role');
  1622. $word['gender'] = (int)$word['gender'];
  1623. // 判断音色对应情感是否支持,不支持则调整为中性
  1624. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  1625. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  1626. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  1627. if (isset($emotion_list[getProp($word, 'emotion')])) {
  1628. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  1629. }else {
  1630. $word['emotion'] = '中性';
  1631. $word['emotion_type'] = 'neutral';
  1632. }
  1633. $existed_role_info[$role] = [
  1634. 'timbre_type' => $word['voice_type'],
  1635. 'timbre_name' => $word['voice_name'],
  1636. 'emotion' => $word['emotion'],
  1637. 'emotion_type' => $word['emotion_type'],
  1638. 'speed_ratio' => $word['speed_ratio'],
  1639. 'loudness_ratio'=> $word['loudness_ratio'],
  1640. 'emotion_scale' => $word['emotion_scale'],
  1641. 'pitch' => $word['pitch']
  1642. ];
  1643. $word['paragraph_audio_url'] = '';
  1644. // 判断生成参数是否相同,相同则直接使用已生成的音频
  1645. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  1646. // 如果音频存在并且参数都未改变则使用已生成的音频
  1647. if (getProp($paragraph, 'paragraph_audio_url')) {
  1648. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  1649. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  1650. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  1651. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  1652. // {
  1653. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1654. // }
  1655. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1656. }
  1657. $tmp = $word;
  1658. // 组装章节分句音频数据
  1659. // $tmp['sequence'] = getProp($word, 'sequence');
  1660. // $tmp['text'] = getProp($word, 'text');
  1661. // $tmp['emotion'] = getProp($word, 'emotion');
  1662. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  1663. // $tmp['voice_name'] = getProp($word, 'voice_name');
  1664. // $tmp['voice_type'] = getProp($word, 'voice_type');
  1665. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  1666. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  1667. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  1668. $tmp['bid'] = $bid;
  1669. $tmp['version_id'] = $version_id;
  1670. $tmp['cid'] = $cid;
  1671. $tmp['sequence'] = $sequence;
  1672. $tmp['created_at'] = date('Y-m-d H:i:s');
  1673. $tmp['updated_at'] = date('Y-m-d H:i:s');
  1674. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  1675. $mp_chapter_paragraph_audios[] = $tmp;
  1676. $complete_paragraph_sequences[] = $sequence;
  1677. $sequence++;
  1678. }
  1679. $generate_json = json_encode($words, 256);
  1680. // 判断是否有未生成字幕的段落
  1681. $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();
  1682. if ($no_subtitle_sequences) {
  1683. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  1684. }
  1685. try {
  1686. DB::beginTransaction();
  1687. $role_info = json_encode($existed_role_info, 256);
  1688. $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')]);
  1689. if (!$boolen) {
  1690. DB::rollBack();
  1691. Utils::throwError('20003:更新角色信息失败');
  1692. }
  1693. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  1694. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  1695. if (!$count) {
  1696. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1697. }else {
  1698. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1699. }
  1700. $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')]);
  1701. if (!$boolen1) {
  1702. DB::rollBack();
  1703. Utils::throwError('20003:更新生成数据失败');
  1704. }
  1705. $id = DB::table('mp_audio_tasks')->insertGetId([
  1706. 'audio_id' => getProp($chapter_audio, 'id'),
  1707. 'generate_status' => '执行中',
  1708. 'generate_json' => $generate_json,
  1709. 'bid' => $bid,
  1710. 'book_name' => getProp($chapter_audio, 'book_name'),
  1711. 'version_id' => $version_id,
  1712. 'version_name' => getProp($chapter_audio, 'version_name'),
  1713. 'cid' => $cid,
  1714. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1715. 'task_name' => $task_name,
  1716. 'created_at' => date('Y-m-d H:i:s'),
  1717. 'updated_at' => date('Y-m-d H:i:s')
  1718. ]);
  1719. if (!$id) {
  1720. DB::rollBack();
  1721. Utils::throwError('20003:创建任务失败');
  1722. }
  1723. // 删除不在段落序号范围内的其他数据
  1724. if ($complete_paragraph_sequences) {
  1725. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  1726. }
  1727. // // 删除章节分句音频数据并重新插入
  1728. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  1729. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  1730. // if (!$boolen3) {
  1731. // DB::rollBack();
  1732. // Utils::throwError('20003:更新章节分句音频失败');
  1733. // }
  1734. } catch (\Exception $e) {
  1735. DB::rollBack();
  1736. Utils::throwError('20003:'.$e->getMessage());
  1737. }
  1738. DB::commit();
  1739. // 通知火山生成音频
  1740. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1741. // 根据ID通过API通知合成音频
  1742. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  1743. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  1744. $response = $result->getBody()->getContents();
  1745. $response_arr = json_decode($response, true);
  1746. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1747. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1748. Log::info('通知火山生成音频失败: '.$error_msg);
  1749. Utils::throwError('20003:通知火山生成音频失败');
  1750. }
  1751. return true;
  1752. }
  1753. public function timbreList($data) {
  1754. $gender = getProp($data, 'gender');
  1755. $timbre_name = getProp($data, 'voice_name');
  1756. $category_id = getProp($data, 'category_id');
  1757. $age_stage = getProp($data, 'age_stage');
  1758. $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');
  1759. if ($gender) {
  1760. $query->where('gender', $gender);
  1761. }
  1762. if ($timbre_name) {
  1763. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  1764. }
  1765. if ($category_id) {
  1766. $query->where(function ($query) use ($category_id) {
  1767. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  1768. });
  1769. }
  1770. if ($age_stage) {
  1771. $query->where('age_stage', $age_stage);
  1772. }
  1773. $list = $query->get()->map(function ($value) {
  1774. $value = (array)$value;
  1775. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  1776. return $value;
  1777. })->toArray();
  1778. return $list;
  1779. }
  1780. // 生成火山临时token
  1781. public function setStsToken() {
  1782. // ************* 配置参数 *************
  1783. $method = 'GET';
  1784. $service = 'sts';
  1785. $host = 'open.volcengineapi.com';
  1786. $region = env('VOLC_REGION');
  1787. $endpoint = 'https://open.volcengineapi.com';
  1788. // $endpoint = 'https://tos-cn-beijing.volces.com';
  1789. $access_key = env('VOLC_AK');
  1790. $secret_key = env('VOLC_SK');
  1791. // 获取缓存中的token,如果没有则请求接口
  1792. $token = Redis::get('volc_sts_token');
  1793. if (!$token) {
  1794. // 查询参数
  1795. $query_parameters = [
  1796. 'Action' => 'AssumeRole',
  1797. 'RoleSessionName' => 'user@zw',
  1798. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  1799. 'Version' => '2018-01-01'
  1800. ];
  1801. // 生成URL编码的查询字符串
  1802. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  1803. // 获取签名头信息
  1804. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  1805. // 构建完整URL
  1806. $request_url = $endpoint . '?' . $request_parameters;
  1807. $client = new Client(['verify' => false]);
  1808. $response = $client->get($request_url, ['headers' => $headers]);
  1809. $response_arr = json_decode($response->getBody()->getContents(), true);
  1810. $result = [
  1811. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  1812. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  1813. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  1814. 'Region' => env('VOLC_REGION'),
  1815. 'Endpoint' => env('VOLC_END_POINT'),
  1816. 'Bucket' => env('VOLC_BUCKET'),
  1817. ];
  1818. // 缓存token
  1819. Redis::setex('volc_sts_token', 3000, json_encode($result));
  1820. return $result;
  1821. } else {
  1822. return json_decode($token, true);
  1823. }
  1824. // $response = $response['Response'];
  1825. // $access_key = $response['Credentials']['AccessKeyId'];
  1826. // $secret_key = $response['Credentials']['AccessKeySecret'];
  1827. // $security_token = $response['Credentials']['SecurityToken'];
  1828. // $expiration = $response['Credentials']['Expiration'];
  1829. // dd($response_arr);
  1830. }
  1831. public function emotionGroups($data) {
  1832. $id = getProp($data, 'group_id');
  1833. $group_name = getProp($data, 'group_name');
  1834. $voice_type = getProp($data, 'voice_type');
  1835. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  1836. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  1837. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  1838. if ($group_name) {
  1839. $query->where('group_name', 'like', "%{$group_name}%");
  1840. }
  1841. if ($id) {
  1842. $query->where('id', $id);
  1843. }
  1844. if ($voice_type) {
  1845. $query->where('voice_type', $voice_type);
  1846. }
  1847. return $query->orderBy('id')->get()->map(function ($value) {
  1848. return (array)$value;
  1849. })->toArray();
  1850. }
  1851. private function sign($key, $msg) {
  1852. return hash_hmac('sha256', $msg, $key, true);
  1853. }
  1854. // 生成签名密钥
  1855. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  1856. $kDate = $this->sign($key, $dateStamp);
  1857. $kRegion = $this->sign($kDate, $regionName);
  1858. $kService = $this->sign($kRegion, $serviceName);
  1859. $kSigning = $this->sign($kService, 'request');
  1860. return $kSigning;
  1861. }
  1862. // 获取签名头信息
  1863. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  1864. $contenttype = 'application/x-www-form-urlencoded';
  1865. $accept = 'application/json';
  1866. // 获取当前UTC时间
  1867. $t = new DateTime('now', new DateTimeZone('UTC'));
  1868. $xdate = $t->format('Ymd\THis\Z');
  1869. $datestamp = $t->format('Ymd');
  1870. // 1. 拼接规范请求串
  1871. $canonical_uri = '/';
  1872. $canonical_querystring = $request_parameters;
  1873. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  1874. $signed_headers = 'content-type;host;x-date';
  1875. // 空请求体的SHA256哈希
  1876. $payload_hash = hash('sha256', '');
  1877. $canonical_request = implode("\n", [
  1878. $method,
  1879. $canonical_uri,
  1880. $canonical_querystring,
  1881. $canonical_headers,
  1882. $signed_headers,
  1883. $payload_hash
  1884. ]);
  1885. // 2. 拼接待签名字符串
  1886. $algorithm = 'HMAC-SHA256';
  1887. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  1888. $hashed_canonical_request = hash('sha256', $canonical_request);
  1889. $string_to_sign = implode("\n", [
  1890. $algorithm,
  1891. $xdate,
  1892. $credential_scope,
  1893. $hashed_canonical_request
  1894. ]);
  1895. // 3. 计算签名
  1896. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  1897. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  1898. // 4. 添加签名到请求头
  1899. $authorization_header = sprintf(
  1900. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  1901. $algorithm,
  1902. $access_key,
  1903. $credential_scope,
  1904. $signed_headers,
  1905. $signature
  1906. );
  1907. return [
  1908. 'Accept' => $accept,
  1909. 'Content-Type' => $contenttype,
  1910. 'X-Date' => $xdate,
  1911. 'Authorization' => $authorization_header
  1912. ];
  1913. }
  1914. // 文字合成语音(火山引擎)
  1915. public function tts($data) {
  1916. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  1917. $headers = [
  1918. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  1919. 'Content-Type' => 'application/json; charset=UTF-8'
  1920. ];
  1921. $post_data = [
  1922. 'app' => [
  1923. 'appid' => env('VOLC_APPID'),
  1924. 'token' => env('VOLC_TOKEN'),
  1925. 'cluster' => 'volcano_tts'
  1926. ],
  1927. 'user' => [
  1928. 'uid' => 'mp_audio'
  1929. ],
  1930. // 'audio' => [
  1931. // 'voice_type' =>
  1932. // ],
  1933. ];
  1934. }
  1935. public function scriptList($data) {
  1936. $uid = Site::getUid();
  1937. $script_id = getProp($data, 'script_id');
  1938. $script_name = getProp($data, 'script_name');
  1939. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  1940. if ($script_id) {
  1941. $query->where('id', $script_id);
  1942. }
  1943. if ($script_name) {
  1944. $query->where('script_name', 'like', "%{$script_name}%");
  1945. }
  1946. return $query->orderBy('created_at', 'desc')->paginate(12);
  1947. }
  1948. public function scripts($data) {
  1949. $uid = Site::getUid();
  1950. $script_id = getProp($data, 'script_id');
  1951. $script_name = getProp($data, 'script_name');
  1952. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  1953. if ($script_id) {
  1954. $query->where('id', $script_id);
  1955. }
  1956. if ($script_name) {
  1957. $query->where('script_name', 'like', "%{$script_name}%");
  1958. }
  1959. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  1960. return (array)$value;
  1961. })->toArray();
  1962. }
  1963. public function scriptInfo($data) {
  1964. $uid = Site::getUid();
  1965. $script_id = getProp($data, 'script_id');
  1966. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  1967. // ->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();
  1968. ->selectRaw('id as script_id, script_name')->first();
  1969. if (!$script) Utils::throwError('20003:该剧本不存在!');
  1970. $script = (array)$script;
  1971. // 获取分集组信息
  1972. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  1973. ->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')
  1974. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  1975. $value = (array)$value;
  1976. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  1977. return (array)$value;
  1978. })->toArray();
  1979. $script['group'] = $groups;
  1980. return $script;
  1981. }
  1982. public function createScript($data) {
  1983. $script_name = getProp($data, 'script_name');
  1984. $uid = Site::getUid(); // 获取当前用户ID
  1985. $cpid = Site::getCpid(); // 获取当前公司组ID
  1986. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  1987. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  1988. $script_name .= '_'.date('YmdHis');
  1989. }
  1990. return DB::table('mp_scripts')->insertGetId([
  1991. 'script_name' => $script_name,
  1992. 'user_id' => $uid,
  1993. 'cpid' => $cpid,
  1994. 'created_at' => date('Y-m-d H:i:s'),
  1995. 'updated_at' => date('Y-m-d H:i:s')
  1996. ]);
  1997. }
  1998. public function editScript($data) {
  1999. $script_id = getProp($data, 'script_id');
  2000. $script_name = getProp($data, 'script_name');
  2001. $uid = Site::getUid(); // 获取当前用户ID
  2002. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  2003. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  2004. if ($id && (int)$id !== (int)$script_id) {
  2005. $script_name .= '_'.date('YmdHis');
  2006. }
  2007. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2008. 'script_name' => $script_name,
  2009. 'updated_at' => date('Y-m-d H:i:s')
  2010. ]);
  2011. }
  2012. public function delScript($data) {
  2013. $script_id = getProp($data, 'script_id');
  2014. $uid = Site::getUid(); // 获取当前用户ID
  2015. if (!$script_id) Utils::throwError('20003:请选择剧本');
  2016. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2017. 'is_deleted' => 1,
  2018. 'updated_at' => date('Y-m-d H:i:s')
  2019. ]);
  2020. }
  2021. public function createEpisode($data) {
  2022. $script_id = getProp($data, 'script_id');
  2023. $group_name = getProp($data, 'group_name');
  2024. $remark = getProp($data, 'remark');
  2025. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  2026. $uid = Site::getUid(); // 获取当前用户ID
  2027. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  2028. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  2029. $group_name .= '_'.date('YmdHis');
  2030. }
  2031. return DB::table('mp_script_episode_group')->insertGetId([
  2032. 'script_id' => $script_id,
  2033. 'group_name' => $group_name,
  2034. 'user_id' => $uid,
  2035. 'remark' => $remark,
  2036. 'created_at' => date('Y-m-d H:i:s'),
  2037. 'updated_at' => date('Y-m-d H:i:s')
  2038. ]);
  2039. }
  2040. public function editEpisode($data) {
  2041. $group_id = getProp($data, 'group_id');
  2042. $start_episode_number = getProp($data, 'start_episode_number');
  2043. $end_episode_number = getProp($data, 'end_episode_number');
  2044. $group_name = getProp($data, 'group_name');
  2045. $uid = Site::getUid(); // 获取当前用户ID
  2046. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  2047. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  2048. if ($id && (int)$id !== (int)$group_id) {
  2049. $group_name .= '_'.date('YmdHis');
  2050. }
  2051. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2052. 'group_name' => $group_name,
  2053. 'start_episode_number' => $start_episode_number,
  2054. 'end_episode_number' => $end_episode_number,
  2055. 'updated_at' => date('Y-m-d H:i:s')
  2056. ]);
  2057. }
  2058. public function delEpisode($data) {
  2059. $group_id = getProp($data, 'group_id');
  2060. $uid = Site::getUid(); // 获取当前用户ID
  2061. if (!$group_id) Utils::throwError('20003:请选择分集');
  2062. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2063. 'is_deleted' => 1,
  2064. 'updated_at' => date('Y-m-d H:i:s')
  2065. ]);
  2066. }
  2067. /**
  2068. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2069. *
  2070. * @param array $data 包含以下参数:
  2071. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2072. * - question: 用户问题(可选)
  2073. * - model: 使用的模型(r1 或 v3,默认 v3)
  2074. * @return \Generator 返回生成器,用于流式输出
  2075. */
  2076. public function generateEpisodes($data) {
  2077. $script_id = getProp($data, 'script_id');
  2078. $group_id = getProp($data, 'group_id');
  2079. // $file = getProp($data, 'file');
  2080. $file = '';
  2081. $content = getProp($data, 'content', '');
  2082. // $bid = getProp($data, 'bid', 0);
  2083. $bid = 0;
  2084. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2085. if (!$group) {
  2086. Utils::throwError('20003:剧本分集不存在');
  2087. }
  2088. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  2089. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  2090. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  2091. $prompt = getProp($data, 'prompt');
  2092. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  2093. $model = getProp($data, 'model');
  2094. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2095. Utils::throwError('20003:该模型不存在!');
  2096. }
  2097. // 检查是否存在重叠的剧集序号范围
  2098. $exists_groups = DB::table('mp_script_episode_group')
  2099. ->where('script_id', $script_id)
  2100. ->where('id', '<>', $group_id) // 排除当前组
  2101. ->where('is_deleted', 0)
  2102. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2103. // 检查新范围是否与现有范围重叠
  2104. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2105. // 新范围的开始在现有范围内
  2106. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2107. ->where('end_episode_number', '>=', $start_episode_sequence);
  2108. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2109. // 新范围的结束在现有范围内
  2110. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2111. ->where('end_episode_number', '>=', $end_episode_sequence);
  2112. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2113. // 新范围完全包含现有范围
  2114. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2115. ->where('end_episode_number', '<=', $end_episode_sequence);
  2116. });
  2117. })
  2118. ->select('start_episode_number', 'end_episode_number')
  2119. ->get();
  2120. if ($exists_groups->isNotEmpty()) {
  2121. $conflict_ranges = [];
  2122. foreach ($exists_groups as $group) {
  2123. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2124. }
  2125. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2126. }
  2127. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2128. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2129. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2130. if ($model === 'deepseek-chat') {
  2131. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2132. $model = 'deepseek-v4-flash';
  2133. $thinkingMode = 'disabled';
  2134. } elseif ($model === 'deepseek-reasoner') {
  2135. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2136. $model = 'deepseek-v4-flash';
  2137. $thinkingMode = 'enabled';
  2138. }
  2139. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2140. if (!$script) {
  2141. Utils::throwError('20003:剧本不存在');
  2142. }
  2143. $content = getProp($group, 'content');
  2144. if (!$file && !$content && !$bid) {
  2145. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2146. }
  2147. // 提取文件内容
  2148. if ($file) {
  2149. $content = $this->extractFileContent($file);
  2150. if (!$content) {
  2151. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2152. }
  2153. } elseif ($bid) {
  2154. $content = $this->getContentByBid($bid);
  2155. if (!$content) {
  2156. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2157. }
  2158. } elseif ($content) {
  2159. $content = filterContent($content);
  2160. } elseif ($prompt) {
  2161. $content = filterContent($prompt);
  2162. } else {
  2163. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2164. }
  2165. // 构建消息
  2166. $messages = [
  2167. $this->sys_message,
  2168. [
  2169. 'role' => 'user',
  2170. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2171. ]
  2172. ];
  2173. $post_data = [
  2174. 'model' => $model,
  2175. 'messages' => $messages,
  2176. // 'max_tokens' => 8192,
  2177. 'temperature' => 0.7,
  2178. 'frequency_penalty' => 0,
  2179. 'presence_penalty' => 0,
  2180. 'thinking' => ['type' => $thinkingMode],
  2181. 'response_format' => ['type' => 'text'],
  2182. 'stream' => true
  2183. ];
  2184. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2185. // 根据模型类型选择调用方法
  2186. $fullContent = '';
  2187. $fullReasoningContent = '';
  2188. $usage = [];
  2189. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2190. // DeepSeek 官方模型使用 DeepSeek API
  2191. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2192. } else if (in_array($model, $this->gpt_text_models)) {
  2193. // GPT-5.4 模型使用 TokenRouter API
  2194. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2195. } else {
  2196. // 其他模型使用火山引擎API
  2197. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2198. }
  2199. // 处理流式输出
  2200. foreach ($streamGenerator as $chunk) {
  2201. if (isset($chunk['type'])) {
  2202. if ($chunk['type'] === 'done') {
  2203. // 最终结果
  2204. $fullContent = $chunk['full_content'];
  2205. $fullReasoningContent = $chunk['full_reasoning'];
  2206. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2207. } else {
  2208. // 逐块yield数据
  2209. yield $chunk;
  2210. }
  2211. }
  2212. }
  2213. dLog('deepseek')->info('完整内容: '.$fullContent);
  2214. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2215. // 处理完整内容并返回最终结果
  2216. $script_arr = [];
  2217. if ($fullContent) {
  2218. $script_arr = extractScriptContent($fullContent);
  2219. }
  2220. logDB('deepseek', 'info', '解析内容', $script_arr);
  2221. if (!$script_arr['episodes']) {
  2222. Utils::throwError('20003:未生成剧本相关信息');
  2223. // yield [
  2224. // 'type' => 'done',
  2225. // 'script' => $script_arr,
  2226. // 'msg' => '未生成剧本相关信息',
  2227. // 'answer' => $fullContent,
  2228. // 'reasoning' => $fullReasoningContent,
  2229. // 'usage' => $usage
  2230. // ];
  2231. // return ;
  2232. }
  2233. try {
  2234. DB::beginTransaction();
  2235. // // 返回前保存剧本内容
  2236. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2237. // 'content' => $content,
  2238. // 'updated_at' => date('Y-m-d H:i:s')
  2239. // ]);
  2240. // if (!$boolen) {
  2241. // Utils::throwError('20003:保存剧本内容失败');
  2242. // }
  2243. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2244. // 'start_episode_number' => $start_episode_sequence,
  2245. // 'end_episode_number' => $end_episode_sequence,
  2246. // 'updated_at' => date('Y-m-d H:i:s')
  2247. // ]);
  2248. // if (!$boolen1) {
  2249. // Utils::throwError('20003:保存分集失败');
  2250. // }
  2251. $episode_content = '';
  2252. $episodes = [];
  2253. foreach ($script_arr['episodes'] as $item) {
  2254. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  2255. // $episodes[] = [
  2256. // 'script_id' => $script_id,
  2257. // 'episode_number' => $item['episode_number'],
  2258. // 'episode_name' => $item['episode_name'],
  2259. // 'episode_content' => $item['episode_content'],
  2260. // 'created_at' => date('Y-m-d H:i:s'),
  2261. // 'updated_at' => date('Y-m-d H:i:s'),
  2262. // ];
  2263. }
  2264. if ($episode_content) {
  2265. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2266. 'episode_content' => $episode_content,
  2267. 'updated_at' => date('Y-m-d H:i:s')
  2268. ]);
  2269. if (!$boolen2) {
  2270. Utils::throwError('20003:保存分集内容失败');
  2271. }
  2272. }else {
  2273. Utils::throwError('20003:分集剧本解析失败');
  2274. }
  2275. }catch (\Exception $e) {
  2276. DB::rollBack();
  2277. Utils::throwError('20003:'.$e->getMessage());
  2278. }
  2279. DB::commit();
  2280. yield [
  2281. 'type' => 'done',
  2282. 'script' => $script_arr,
  2283. 'episode_content' => $episode_content,
  2284. 'answer' => $fullContent,
  2285. 'reasoning' => $fullReasoningContent,
  2286. 'usage' => $usage
  2287. ];
  2288. }
  2289. public function chatWithFileStream($data) {
  2290. $script_id = getProp($data, 'script_id');
  2291. $group_id = getProp($data, 'group_id');
  2292. $file = getProp($data, 'file');
  2293. $content = getProp($data, 'content', '');
  2294. $bid = getProp($data, 'bid', 0);
  2295. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2296. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2297. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  2298. $prompt = getProp($data, 'prompt');
  2299. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2300. if (!empty($prompt)) {
  2301. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2302. }
  2303. $question = getProp($data, 'question', $baseQuestion);
  2304. $model = getProp($data, 'model');
  2305. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2306. Utils::throwError('20003:该模型不存在!');
  2307. }
  2308. // 检查是否存在重叠的剧集序号范围
  2309. $exists_groups = DB::table('mp_script_episode_group')
  2310. ->where('script_id', $script_id)
  2311. ->where('id', '<>', $group_id)
  2312. ->where('is_deleted', 0)
  2313. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2314. // 检查新范围是否与现有范围重叠
  2315. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2316. // 新范围的开始在现有范围内
  2317. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2318. ->where('end_episode_number', '>=', $start_episode_sequence);
  2319. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2320. // 新范围的结束在现有范围内
  2321. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2322. ->where('end_episode_number', '>=', $end_episode_sequence);
  2323. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2324. // 新范围完全包含现有范围
  2325. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2326. ->where('end_episode_number', '<=', $end_episode_sequence);
  2327. });
  2328. })
  2329. ->select('start_episode_number', 'end_episode_number')
  2330. ->get();
  2331. if ($exists_groups->isNotEmpty()) {
  2332. $conflict_ranges = [];
  2333. foreach ($exists_groups as $group) {
  2334. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2335. }
  2336. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2337. }
  2338. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2339. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2340. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2341. if ($model === 'deepseek-chat') {
  2342. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2343. $model = 'deepseek-v4-flash';
  2344. $thinkingMode = 'disabled';
  2345. } elseif ($model === 'deepseek-reasoner') {
  2346. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2347. $model = 'deepseek-v4-flash';
  2348. $thinkingMode = 'enabled';
  2349. }
  2350. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2351. if (!$script) {
  2352. Utils::throwError('20003:剧本不存在');
  2353. }
  2354. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2355. if (!$group) {
  2356. Utils::throwError('20003:剧本分集不存在');
  2357. }
  2358. if (!$file && !$content && !$bid) {
  2359. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2360. }
  2361. // 提取文件内容
  2362. if ($file) {
  2363. $content = $this->extractFileContent($file);
  2364. if (!$content) {
  2365. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2366. }
  2367. } elseif ($bid) {
  2368. $content = $this->getContentByBid($bid);
  2369. if (!$content) {
  2370. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2371. }
  2372. } elseif ($content) {
  2373. $content = filterContent($content);
  2374. } elseif ($prompt) {
  2375. $content = filterContent($prompt);
  2376. } else {
  2377. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2378. }
  2379. // 构建消息
  2380. $messages = [
  2381. [
  2382. 'role' => 'system',
  2383. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  2384. 强制要求:\n
  2385. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2386. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  2387. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  2388. 普通要求:\n
  2389. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  2390. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  2391. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  2392. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  2393. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  2394. 示例如下:\n
  2395. ###剧本名:西昆仑
  2396. ###故事梗概
  2397. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2398. ###剧本亮点
  2399. 亮点1:绝境奇药,生死一线
  2400. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2401. 亮点2:结拜兄妹,化解尴尬
  2402. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2403. 亮点3:纤发夺命,情愫暗涌
  2404. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2405. ###人物关系
  2406. 阿雪与梁萧之间存在兄妹之情。
  2407. ###核心矛盾
  2408. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2409. ###主体列表
  2410. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2411. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2412. 阴阳球:天地异宝,能化生精气,救人于危难。
  2413. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2414. ###美术风格
  2415. 基础画风风格词:厚涂古风
  2416. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2417. ###场景列表
  2418. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  2419. [
  2420. 'role' => 'user',
  2421. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2422. ]
  2423. ];
  2424. $post_data = [
  2425. 'model' => $model,
  2426. 'messages' => $messages,
  2427. // 'max_tokens' => 8192,
  2428. 'temperature' => 0.7,
  2429. 'frequency_penalty' => 0,
  2430. 'presence_penalty' => 0,
  2431. 'thinking' => ['type' => $thinkingMode],
  2432. 'response_format' => ['type' => 'text'],
  2433. 'stream' => true
  2434. ];
  2435. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2436. // 根据模型类型选择调用方法
  2437. $fullContent = '';
  2438. $fullReasoningContent = '';
  2439. $usage = [];
  2440. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2441. // DeepSeek 官方模型使用 DeepSeek API
  2442. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2443. } else if (in_array($model, $this->gpt_text_models)) {
  2444. // GPT-5.4 模型使用 TokenRouter API
  2445. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2446. } else {
  2447. // 其他模型使用火山引擎API
  2448. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2449. }
  2450. // 处理流式输出
  2451. foreach ($streamGenerator as $chunk) {
  2452. if (isset($chunk['type'])) {
  2453. if ($chunk['type'] === 'done') {
  2454. // 最终结果
  2455. $fullContent = $chunk['full_content'];
  2456. $fullReasoningContent = $chunk['full_reasoning'];
  2457. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2458. } else {
  2459. // 逐块yield数据
  2460. yield $chunk;
  2461. }
  2462. }
  2463. }
  2464. dLog('deepseek')->info('完整内容: '.$fullContent);
  2465. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2466. // 处理完整内容并返回最终结果
  2467. $script_arr = [];
  2468. if ($fullContent) {
  2469. $script_arr = extractScriptContent($fullContent);
  2470. }
  2471. logDB('deepseek', 'info', '解析内容', $script_arr);
  2472. if (!$script_arr['roles']) {
  2473. Utils::throwError('20003:未生成剧本相关信息');
  2474. // yield [
  2475. // 'type' => 'done',
  2476. // 'script' => $script_arr,
  2477. // 'msg' => '未生成剧本相关信息',
  2478. // 'answer' => $fullContent,
  2479. // 'reasoning' => $fullReasoningContent,
  2480. // 'usage' => $usage
  2481. // ];
  2482. }
  2483. try {
  2484. DB::beginTransaction();
  2485. // // 返回前保存剧本内容
  2486. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2487. // 'content' => $content,
  2488. // 'status' => '解析完成',
  2489. // 'updated_at' => date('Y-m-d H:i:s')
  2490. // ]);
  2491. // if (!$boolen) {
  2492. // Utils::throwError('20003:保存剧本内容失败');
  2493. // }
  2494. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2495. 'start_episode_number' => $start_episode_sequence,
  2496. 'end_episode_number' => $end_episode_sequence,
  2497. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2498. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2499. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2500. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2501. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2502. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2503. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2504. 'status' => '解析完成',
  2505. 'content' => $content,
  2506. 'updated_at' => date('Y-m-d H:i:s')
  2507. ]);
  2508. if (!$boolen1) {
  2509. Utils::throwError('20003:保存分集失败');
  2510. }
  2511. // $episodes = [];
  2512. // foreach ($script_arr['episodes'] as $item) {
  2513. // $episodes[] = [
  2514. // 'script_id' => $script_id,
  2515. // 'episode_number' => $item['episode_number'],
  2516. // 'episode_name' => $item['episode_name'],
  2517. // 'episode_content' => $item['episode_content'],
  2518. // 'created_at' => date('Y-m-d H:i:s'),
  2519. // 'updated_at' => date('Y-m-d H:i:s'),
  2520. // ];
  2521. // }
  2522. // if ($episodes) {
  2523. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2524. // if (!$boolen2) {
  2525. // Utils::throwError('20003:保存分集内容失败');
  2526. // }
  2527. // }else {
  2528. // Utils::throwError('20003:分集剧本解析失败');
  2529. // }
  2530. }catch (\Exception $e) {
  2531. DB::rollBack();
  2532. Utils::throwError('20003:'.$e->getMessage());
  2533. }
  2534. DB::commit();
  2535. yield [
  2536. 'type' => 'done',
  2537. 'script' => $script_arr,
  2538. 'answer' => $fullContent,
  2539. 'reasoning' => $fullReasoningContent,
  2540. 'usage' => $usage
  2541. ];
  2542. }
  2543. /**
  2544. * 上传文件识别文字内容并与 DeepSeek 进行对话
  2545. *
  2546. * @param array $data 包含以下参数:
  2547. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2548. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  2549. * - model: 使用的模型(r1 或 v3,默认 v3)
  2550. * @return array
  2551. */
  2552. public function chatWithFile($data) {
  2553. $script_id = getProp($data, 'script_id');
  2554. $file = getProp($data, 'file');
  2555. $content = getProp($data, 'content', '');
  2556. $bid = getProp($data, 'bid', 0);
  2557. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2558. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2559. $prompt = getProp($data, 'prompt');
  2560. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2561. if (!empty($prompt)) {
  2562. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2563. }
  2564. $question = getProp($data, 'question', $baseQuestion);
  2565. // 处理文本模型
  2566. $model = getProp($data, 'model');
  2567. if (!$model) {
  2568. // 用户没有输入,使用默认值
  2569. $model = 'doubao-seed-2-0-mini-260215';
  2570. }
  2571. // 验证模型是否在可用模型表中
  2572. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2573. $model = 'doubao-seed-2-0-mini-260215';
  2574. }
  2575. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2576. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2577. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2578. if ($model === 'deepseek-chat') {
  2579. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2580. $model = 'deepseek-v4-flash';
  2581. $thinkingMode = 'disabled';
  2582. } elseif ($model === 'deepseek-reasoner') {
  2583. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2584. $model = 'deepseek-v4-flash';
  2585. $thinkingMode = 'enabled';
  2586. }
  2587. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2588. if (!$script) {
  2589. Utils::throwError('20003:剧本不存在');
  2590. }
  2591. if (!$file && !$content && !$bid) {
  2592. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2593. }
  2594. // 提取文件内容
  2595. if ($file) {
  2596. $content = $this->extractFileContent($file);
  2597. if (!$content) {
  2598. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2599. }
  2600. } elseif ($bid) {
  2601. $content = $this->getContentByBid($bid);
  2602. if (!$content) {
  2603. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2604. }
  2605. } elseif ($content) {
  2606. $content = filterContent($content);
  2607. } elseif ($prompt) {
  2608. $content = filterContent($prompt);
  2609. } else {
  2610. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2611. }
  2612. // 构建消息
  2613. $messages = [
  2614. $this->sys_message,
  2615. [
  2616. 'role' => 'user',
  2617. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2618. ]
  2619. ];
  2620. $post_data = [
  2621. 'model' => $model,
  2622. 'messages' => $messages,
  2623. // 'max_tokens' => 8192,
  2624. 'temperature' => 0.7,
  2625. 'frequency_penalty' => 0,
  2626. 'presence_penalty' => 0,
  2627. 'thinking' => ['type' => $thinkingMode],
  2628. 'response_format' => ['type' => 'text'],
  2629. 'stream' => false
  2630. ];
  2631. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2632. // 根据模型类型选择调用方法
  2633. $fullContent = '';
  2634. $usage = [];
  2635. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2636. // DeepSeek 官方模型使用 DeepSeek API
  2637. $chatResult = $this->chatOnly($post_data);
  2638. } else if (in_array($model, $this->gpt_text_models)) {
  2639. // GPT-5.4 模型使用 TokenRouter API
  2640. $chatResult = $this->gpt54ChatOnly($post_data);
  2641. } else {
  2642. // 其他模型使用火山引擎API
  2643. $chatResult = $this->volcEngineChatCompletion($post_data);
  2644. }
  2645. if (is_array($chatResult)) {
  2646. $fullContent = $chatResult['fullContent'];
  2647. $usage = $chatResult['usage'];
  2648. }
  2649. $script_arr = [];
  2650. // 处理结果
  2651. if ($fullContent) {
  2652. $script_arr = extractScriptContent($fullContent);
  2653. }
  2654. // 返回前保存剧本内容
  2655. DB::table('mp_scripts')->where('id', $script_id)->update([
  2656. 'content' => $content,
  2657. 'updated_at' => date('Y-m-d H:i:s')
  2658. ]);
  2659. return [
  2660. 'script' => $script_arr,
  2661. 'answer' => $fullContent,
  2662. 'usage' => $usage
  2663. ];
  2664. }
  2665. public function getEpisodeContent($data) {
  2666. $group_id = getProp($data, 'group_id');
  2667. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  2668. }
  2669. public function saveEpisodeContent($data) {
  2670. $script_id = getProp($data, 'script_id');
  2671. $group_id = getProp($data, 'group_id');
  2672. $start_episode_sequence = getProp($data, 'start_episode_number');
  2673. $end_episode_sequence = getProp($data, 'end_episode_number');
  2674. // 检查是否存在重叠的剧集序号范围
  2675. $exists_groups = DB::table('mp_script_episode_group')
  2676. ->where('script_id', $script_id)
  2677. ->where('id', '<>', $group_id) // 排除当前组
  2678. ->where('is_deleted', 0)
  2679. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2680. // 检查新范围是否与现有范围重叠
  2681. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2682. // 新范围的开始在现有范围内
  2683. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2684. ->where('end_episode_number', '>=', $start_episode_sequence);
  2685. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2686. // 新范围的结束在现有范围内
  2687. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2688. ->where('end_episode_number', '>=', $end_episode_sequence);
  2689. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2690. // 新范围完全包含现有范围
  2691. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2692. ->where('end_episode_number', '<=', $end_episode_sequence);
  2693. });
  2694. })
  2695. ->select('start_episode_number', 'end_episode_number')
  2696. ->get();
  2697. if ($exists_groups->isNotEmpty()) {
  2698. $conflict_ranges = [];
  2699. foreach ($exists_groups as $group) {
  2700. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2701. }
  2702. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2703. }
  2704. $episode_content = getProp($data, 'episode_content');
  2705. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  2706. 'content' => $episode_content,
  2707. 'start_episode_number' => $start_episode_sequence,
  2708. 'end_episode_number' => $end_episode_sequence,
  2709. 'updated_at' => date('Y-m-d H:i:s')
  2710. ]);
  2711. $script_arr =getProp($data, 'script', []);
  2712. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  2713. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2714. $script_id = getProp($data, 'script_id');
  2715. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  2716. try {
  2717. DB::beginTransaction();
  2718. $update_data = [
  2719. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2720. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2721. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2722. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2723. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2724. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2725. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2726. 'status' => 3,
  2727. 'start_episode_sequence' => $start_episode_sequence,
  2728. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  2729. 'episode_num' => count($script_arr['episodes']),
  2730. 'updated_at' => date('Y-m-d H:i:s')
  2731. ];
  2732. // 保存剧本内容
  2733. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  2734. if (!$boolen) {
  2735. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  2736. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  2737. Utils::throwError('20003:剧本内容保存失败');
  2738. }
  2739. // 保存分集内容
  2740. // 删除历史分集内容
  2741. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  2742. $episodes = [];
  2743. $sequence = 1;
  2744. foreach ($script_arr['episodes'] as $episode) {
  2745. $segment_number = 1;
  2746. foreach($episode['segments'] as $segment) {
  2747. $episodes[] = [
  2748. 'script_id' => $script_id,
  2749. 'episode_number' => $episode['episode_number'],
  2750. 'title' => $episode['title'],
  2751. // 'content' => $episode['content'],
  2752. 'content' => '',
  2753. 'segment_number' => $segment_number,
  2754. 'segment_content' => $segment['segment_content'],
  2755. 'sequence' => $sequence,
  2756. 'created_at' => date('Y-m-d H:i:s'),
  2757. 'updated_at' => date('Y-m-d H:i:s')
  2758. ];
  2759. $sequence++;
  2760. $segment_number++;
  2761. }
  2762. }
  2763. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2764. if (!$boolen2) {
  2765. dLog('deepseek')->info('分集内容保存失败', $episodes);
  2766. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  2767. Utils::throwError('20003:分集内容保存失败');
  2768. }
  2769. } catch (\Exception $e) {
  2770. DB::rollBack();
  2771. Utils::throwError('20003:'.$e->getMessage());
  2772. }
  2773. DB::commit();
  2774. return true;
  2775. }
  2776. public function getBookContent($data) {
  2777. $bid = getProp($data, 'bid');
  2778. $start_sequence = getProp($data, 'start_sequence');
  2779. $end_sequence = getProp($data, 'end_sequence');
  2780. $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])
  2781. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  2782. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  2783. return $return_content;
  2784. }
  2785. public function exportScript($data) {
  2786. $filename = getProp($data, 'filename');
  2787. $script_id = getProp($data, 'script_id');
  2788. $group_id = getProp($data, 'group_id');
  2789. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  2790. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  2791. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2792. $script = (array)$script;
  2793. // 获取分集组信息
  2794. if ($group_id) {
  2795. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2796. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2797. ->get()->map(function($value) {
  2798. return (array)$value;
  2799. })->toArray();
  2800. }else {
  2801. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2802. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2803. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  2804. return (array)$value;
  2805. })->toArray();
  2806. }
  2807. if (!$groups) Utils::throwError('20003:分集不存在');
  2808. $script['group'] = $groups;
  2809. $export_type = getProp($data, 'export_type', 'txt');
  2810. // 生成文件名
  2811. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  2812. // 根据导出类型生成不同格式的文件
  2813. switch ($export_type) {
  2814. case 'txt':
  2815. return $this->exportScriptAsTxt($script, $filename);
  2816. case 'pdf':
  2817. return $this->exportScriptAsPdf($script, $filename);
  2818. default:
  2819. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  2820. }
  2821. }
  2822. /**
  2823. * 导出剧本为TXT格式
  2824. */
  2825. private function exportScriptAsTxt($script, $filename) {
  2826. // 构建TXT内容
  2827. $content = $this->buildScriptContent($script);
  2828. // 设置响应头,直接下载
  2829. header('Content-Type: text/plain; charset=utf-8');
  2830. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  2831. header('Content-Length: ' . strlen($content));
  2832. // 输出内容并结束
  2833. echo $content;
  2834. exit();
  2835. }
  2836. /**
  2837. * 导出剧本为PDF格式
  2838. */
  2839. private function exportScriptAsPdf($script, $filename) {
  2840. // 使用HTML转PDF的方式来更好地支持中文
  2841. $htmlContent = $this->buildScriptHtmlForPdf($script);
  2842. // 创建PDF实例
  2843. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  2844. // 设置文档信息
  2845. $pdf->SetCreator('剧本导出系统');
  2846. $pdf->SetAuthor('系统');
  2847. $pdf->SetTitle($script['script_name']);
  2848. $pdf->SetSubject('剧本导出');
  2849. // 设置边距
  2850. $pdf->SetMargins(15, 15, 15);
  2851. $pdf->SetAutoPageBreak(TRUE, 15);
  2852. // 添加页面
  2853. $pdf->AddPage();
  2854. // 注册并使用 simsun.ttf 字体
  2855. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  2856. // 使用HTML内容生成PDF
  2857. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  2858. // 直接输出PDF文件供下载
  2859. header('Content-Type: application/pdf');
  2860. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  2861. // 直接输出PDF内容
  2862. $pdf->Output($filename . '.pdf', 'D');
  2863. exit();
  2864. }
  2865. /**
  2866. * 构建用于PDF的HTML内容
  2867. */
  2868. private function buildScriptHtmlForPdf($script) {
  2869. $html = '<style>
  2870. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  2871. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  2872. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  2873. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  2874. .info { margin-bottom: 8px; }
  2875. .group { margin-bottom: 30px; page-break-inside: avoid; }
  2876. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  2877. .segment { margin-bottom: 10px; margin-left: 20px; }
  2878. .episode-content { white-space: pre-wrap; }
  2879. </style>';
  2880. // 标题
  2881. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  2882. // 处理分组数据
  2883. if (!empty($script['group']) && is_array($script['group'])) {
  2884. $groups = (array)$script['group'];
  2885. foreach ($groups as $group) {
  2886. $html .= '<div class="group">';
  2887. // 分组标题
  2888. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  2889. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  2890. // 故事梗概
  2891. if (!empty($group['intro'])) {
  2892. $html .= '<h3>故事梗概</h3>';
  2893. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  2894. }
  2895. // 剧本亮点
  2896. if (!empty($group['highlights'])) {
  2897. $html .= '<h3>剧本亮点</h3>';
  2898. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  2899. }
  2900. // 人物关系
  2901. if (!empty($group['role_relationship'])) {
  2902. $html .= '<h3>人物关系</h3>';
  2903. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  2904. }
  2905. // 核心矛盾
  2906. if (!empty($group['core_contradiction'])) {
  2907. $html .= '<h3>核心矛盾</h3>';
  2908. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  2909. }
  2910. // 主体列表
  2911. if (!empty($group['roles']) && is_array($group['roles'])) {
  2912. $html .= '<h3>主体列表</h3>';
  2913. $html .= '<ul>';
  2914. foreach ($group['roles'] as $role) {
  2915. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  2916. }
  2917. $html .= '</ul>';
  2918. }
  2919. // 美术风格
  2920. if (!empty($group['art_style'])) {
  2921. $html .= '<h3>美术风格</h3>';
  2922. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  2923. }
  2924. // 场景列表
  2925. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  2926. $html .= '<h3>场景列表</h3>';
  2927. $html .= '<ul>';
  2928. foreach ($group['scenes'] as $scene) {
  2929. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  2930. }
  2931. $html .= '</ul>';
  2932. }
  2933. // 分集剧本
  2934. if (!empty($group['episode_content'])) {
  2935. $html .= '<h3>分集剧本</h3>';
  2936. // 去除零宽字符和其他不可见字符
  2937. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  2938. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  2939. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  2940. }
  2941. $html .= '</div>';
  2942. }
  2943. }
  2944. return $html;
  2945. }
  2946. /**
  2947. * 构建PDF内容
  2948. */
  2949. private function buildPdfContent($pdf, $script) {
  2950. // 标题
  2951. $pdf->SetFont('dejavusans', 'B', 18);
  2952. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  2953. $pdf->Ln(5);
  2954. // 基本信息
  2955. $pdf->SetFont('dejavusans', '', 12);
  2956. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  2957. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  2958. $pdf->Ln(5);
  2959. // 剧本简介
  2960. if (!empty($script['intro'])) {
  2961. $pdf->SetFont('dejavusans', 'B', 14);
  2962. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  2963. $pdf->SetFont('dejavusans', '', 12);
  2964. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  2965. $pdf->Ln(3);
  2966. }
  2967. // 亮点
  2968. if (!empty($script['highlights'])) {
  2969. $pdf->SetFont('dejavusans', 'B', 14);
  2970. $pdf->Cell(0, 10, '亮点', 0, 1);
  2971. $pdf->SetFont('dejavusans', '', 12);
  2972. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  2973. $pdf->Ln(3);
  2974. }
  2975. // 核心矛盾
  2976. if (!empty($script['core_contradiction'])) {
  2977. $pdf->SetFont('dejavusans', 'B', 14);
  2978. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  2979. $pdf->SetFont('dejavusans', '', 12);
  2980. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  2981. $pdf->Ln(3);
  2982. }
  2983. // 艺术风格
  2984. if (!empty($script['art_style'])) {
  2985. $pdf->SetFont('dejavusans', 'B', 14);
  2986. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  2987. $pdf->SetFont('dejavusans', '', 12);
  2988. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  2989. $pdf->Ln(3);
  2990. }
  2991. // 备注
  2992. if (!empty($script['remark'])) {
  2993. $pdf->SetFont('dejavusans', 'B', 14);
  2994. $pdf->Cell(0, 10, '备注', 0, 1);
  2995. $pdf->SetFont('dejavusans', '', 12);
  2996. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  2997. $pdf->Ln(3);
  2998. }
  2999. // 角色列表
  3000. if (!empty($script['roles']) && is_array($script['roles'])) {
  3001. $pdf->SetFont('dejavusans', 'B', 14);
  3002. $pdf->Cell(0, 10, '角色列表', 0, 1);
  3003. $pdf->SetFont('dejavusans', '', 12);
  3004. foreach ($script['roles'] as $index => $role) {
  3005. if (is_array($role) || is_object($role)) {
  3006. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  3007. } else {
  3008. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  3009. }
  3010. }
  3011. $pdf->Ln(3);
  3012. }
  3013. // 角色关系
  3014. if (!empty($script['role_relationship'])) {
  3015. $pdf->SetFont('dejavusans', 'B', 14);
  3016. $pdf->Cell(0, 10, '角色关系', 0, 1);
  3017. $pdf->SetFont('dejavusans', '', 12);
  3018. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  3019. $pdf->Ln(3);
  3020. }
  3021. // 场景列表
  3022. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  3023. $pdf->SetFont('dejavusans', 'B', 14);
  3024. $pdf->Cell(0, 10, '场景列表', 0, 1);
  3025. $pdf->SetFont('dejavusans', '', 12);
  3026. foreach ($script['scenes'] as $index => $scene) {
  3027. if (is_array($scene) || is_object($scene)) {
  3028. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  3029. } else {
  3030. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  3031. }
  3032. }
  3033. $pdf->Ln(5);
  3034. }
  3035. // 分集内容
  3036. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  3037. $pdf->SetFont('dejavusans', 'B', 16);
  3038. $pdf->Cell(0, 12, '分集内容', 0, 1);
  3039. $pdf->Ln(3);
  3040. foreach ($script['episodes'] as $episode) {
  3041. // 检查是否需要新页面
  3042. if ($pdf->GetY() > 250) {
  3043. $pdf->AddPage();
  3044. }
  3045. $pdf->SetFont('dejavusans', 'B', 14);
  3046. $episodeTitle = '第' . $episode['episode_number'] . '集';
  3047. if (!empty($episode['title'])) {
  3048. $episodeTitle .= ':' . $episode['title'];
  3049. }
  3050. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  3051. // 处理分段内容
  3052. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  3053. $pdf->SetFont('dejavusans', '', 12);
  3054. foreach ($episode['segments'] as $segment) {
  3055. if (!empty($segment['segment_content'])) {
  3056. // 如果有分段编号,显示分段标题
  3057. if (!empty($segment['segment_number'])) {
  3058. $pdf->SetFont('dejavusans', 'B', 12);
  3059. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  3060. $pdf->SetFont('dejavusans', '', 12);
  3061. }
  3062. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  3063. $pdf->Ln(2);
  3064. }
  3065. }
  3066. }
  3067. $pdf->Ln(5);
  3068. }
  3069. }
  3070. }
  3071. /**
  3072. * 构建剧本文本内容
  3073. */
  3074. private function buildScriptContent($script) {
  3075. $content = '';
  3076. $groups = $script['group'];
  3077. $groups = (array)$groups;
  3078. foreach ($groups as $group) {
  3079. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  3080. // 剧本基本信息
  3081. if (!empty($group['intro'])) {
  3082. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  3083. }
  3084. if (!empty($group['highlights'])) {
  3085. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  3086. }
  3087. if (!empty($group['role_relationship'])) {
  3088. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  3089. }
  3090. if (!empty($group['core_contradiction'])) {
  3091. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  3092. }
  3093. if (!empty($group['roles']) && is_array($group['roles'])) {
  3094. $content .= "###主体列表\n";
  3095. foreach ($group['roles'] as $role) {
  3096. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  3097. }
  3098. $content .= "\n\n";
  3099. }
  3100. if (!empty($group['art_style'])) {
  3101. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  3102. }
  3103. // 场景信息
  3104. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3105. $content .= "###场景列表\n";
  3106. foreach ($group['scenes'] as $scene) {
  3107. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  3108. }
  3109. $content .= "\n\n";
  3110. }
  3111. // 分集内容
  3112. if (!empty($group['episode_content'])) {
  3113. $content .= "###分集剧本\n";
  3114. $content .= $group['episode_content'];
  3115. // foreach ($script['episodes'] as $episode) {
  3116. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  3117. // // if (!empty($episode['episode_name'])) {
  3118. // // $content .= ":" . $episode['episode_name'];
  3119. // // }
  3120. // // $content .= "\n";
  3121. // $content .= $episode['episode_content'] . "\n\n";
  3122. // }
  3123. }
  3124. }
  3125. return $content;
  3126. }
  3127. /**
  3128. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3129. *
  3130. * @param array $data 包含以下参数:
  3131. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3132. * - question: 用户问题(可选)
  3133. * - model: 使用的模型(r1 或 v3,默认 v3)
  3134. * @return \Generator 返回生成器,用于流式输出
  3135. */
  3136. public function addChat($data) {
  3137. $uid = Site::getUid();
  3138. $anime_id = getProp($data, 'anime_id');
  3139. if (!$anime_id) Utils::throwError('20003:请选择对话');
  3140. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3141. if (!$anime) Utils::throwError('20003:对话不存在');
  3142. $file = getProp($data, 'file');
  3143. $content = getProp($data, 'content', '');
  3144. $bid = getProp($data, 'bid', 0);
  3145. $script_id = getProp($data, 'script_id', 0);
  3146. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  3147. $prompt = getProp($data, 'prompt');
  3148. $user_anime_name = getProp($anime, 'anime_name');
  3149. // 处理文本模型
  3150. $model = getProp($data, 'model');
  3151. if (!$model) {
  3152. // 用户没有输入,从anime表获取
  3153. $model = getProp($anime, 'model');
  3154. if (!$model) {
  3155. // anime表也没有,使用默认值
  3156. $model = 'doubao-seed-2-0-mini-260215';
  3157. }
  3158. }
  3159. // 验证模型是否在可用模型表中
  3160. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3161. $model = 'doubao-seed-2-0-mini-260215';
  3162. }
  3163. $is_multi = getProp($anime, 'is_multi');
  3164. $is_single = (int)$is_multi !== 1;
  3165. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3166. if ($prompt) {
  3167. $question .= "本次修改要求如下:\n{$prompt}";
  3168. }
  3169. // if (!$file && !$content && !$bid) {
  3170. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3171. // }
  3172. // 提取文件内容
  3173. if ($file) {
  3174. $content = $this->extractFileContent($file);
  3175. if (!$content) {
  3176. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3177. }
  3178. } elseif ($script_id) {
  3179. $content = $this->getContentByScriptId($script_id);
  3180. if (!$content) {
  3181. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3182. }
  3183. } elseif ($bid) {
  3184. $content = $this->getContentByBid($bid);
  3185. if (!$content) {
  3186. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3187. }
  3188. } elseif ($content) {
  3189. $content = filterContent($content);
  3190. } else {
  3191. $content = getProp($anime, 'content');
  3192. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3193. $need_generate_content = true;
  3194. }
  3195. }
  3196. // 美术风格
  3197. $input_art_style = getProp($data, 'art_style');
  3198. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3199. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3200. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3201. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3202. 中年女:邻居阿姨
  3203. 老年男:幽默大爷
  3204. 老年女:婆婆
  3205. 萌娃:奶气萌娃";
  3206. // 判断是否需要生成原文内容
  3207. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3208. // 如果需要生成原文内容,添加额外的要求
  3209. $content_generation_requirement = $need_generate_content
  3210. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3211. : "";
  3212. // 美术风格
  3213. if (!$mappedArtStyle) {
  3214. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3215. }else {
  3216. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3217. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3218. }else {
  3219. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3220. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3221. }
  3222. }
  3223. $systemPrompt = $is_single
  3224. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3225. 强制要求:
  3226. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3227. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3228. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3229. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3230. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3231. 普通要求:
  3232. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3233. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3234. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  3235. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3236. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3237. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3238. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3239. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3240. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3241. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3242. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3243. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3244. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3245. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3246. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3247. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3248. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3249. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3250. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3251. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3252. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3253. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3254. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3255. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3256. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3257. 5.{$mappedArtStyle_prompt}\n\n
  3258. 示例如下:\n
  3259. ###剧本名:西昆仑
  3260. ###故事梗概
  3261. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3262. ###剧本亮点
  3263. 亮点1:绝境奇药,生死一线
  3264. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3265. 亮点2:结拜兄妹,化解尴尬
  3266. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3267. 亮点3:纤发夺命,情愫暗涌
  3268. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3269. ###人物关系
  3270. 阿雪与梁萧之间存在兄妹之情。
  3271. ###核心矛盾
  3272. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3273. ###主体列表
  3274. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3275. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3276. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3277. 姿态:站立。}{{甜心小美}}
  3278. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3279. 全景,正面拍摄,青年女性,亚洲人。
  3280. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3281. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3282. 姿态:站立。}{{阳光青年}}
  3283. ###美术风格
  3284. 基础画风风格词:厚涂古风
  3285. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3286. ###场景列表
  3287. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3288. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3289. 无人物。}
  3290. ###分镜剧本
  3291. ##第1幕:徐家老旧厨房 白天 室内
  3292. 分镜1
  3293. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3294. 场景:徐家老旧厨房
  3295. 构图设计:全景,低角度仰视
  3296. 运镜调度:手持拍摄
  3297. 配音角色:旁白
  3298. 出镜角色:许芸-校服装、徐母
  3299. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3300. 画面类型:普通画面
  3301. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3302. 分镜2
  3303. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3304. 场景:徐家老旧厨房
  3305. 构图设计:近景,徐母面部特写
  3306. 运镜调度:固定镜头
  3307. 配音角色:徐母
  3308. 出镜角色:徐母
  3309. 台词内容:问我夜不归宿死哪儿去了。
  3310. 画面类型:对口型
  3311. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3312. ##第2幕:徐家简陋客厅 黄昏 室内
  3313. 分镜3
  3314. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3315. 场景:徐家简陋客厅
  3316. 构图设计:全景,景深虚化
  3317. 运镜调度:固定镜头
  3318. 配音角色:旁白
  3319. 出镜角色:无
  3320. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3321. 画面类型:普通画面
  3322. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3323. 分镜4
  3324. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3325. 场景:徐家简陋客厅
  3326. 构图设计:特写,火车票
  3327. 运镜调度:固定镜头
  3328. 配音角色:旁白
  3329. 出镜角色:无
  3330. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3331. 画面类型:普通画面
  3332. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  3333. "
  3334. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3335. 强制要求:\n
  3336. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3337. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3338. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3339. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3340. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3341. 普通要求:\n
  3342. 1.剧本名(必须生成)必须与文档内容高度相关
  3343. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3344. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3345. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3346. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3347. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3348. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3349. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3350. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3351. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3352. 4.{$mappedArtStyle_prompt}\n\n
  3353. 示例如下:\n
  3354. ###剧本名:西昆仑
  3355. ###故事梗概
  3356. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3357. ###剧本亮点
  3358. 亮点1:绝境奇药,生死一线
  3359. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3360. 亮点2:结拜兄妹,化解尴尬
  3361. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3362. 亮点3:纤发夺命,情愫暗涌
  3363. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3364. ###人物关系
  3365. 阿雪与梁萧之间存在兄妹之情。
  3366. ###核心矛盾
  3367. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3368. ###主体列表
  3369. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3370. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3371. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3372. 姿态:站立。}{{甜心小美}}
  3373. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3374. 全景,正面拍摄,青年女性,亚洲人。
  3375. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3376. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3377. 姿态:站立。}{{阳光青年}}
  3378. ###美术风格
  3379. 基础画风风格词:厚涂古风
  3380. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3381. ###场景列表
  3382. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3383. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3384. 无人物。}";
  3385. // 构建消息
  3386. $messages = [
  3387. [
  3388. 'role' => 'system',
  3389. 'content' => $systemPrompt
  3390. ],
  3391. [
  3392. 'role' => 'user',
  3393. 'content' => "以下是文档内容:
  3394. {$content}
  3395. 用户问题:
  3396. {$question}"
  3397. ]
  3398. ];
  3399. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3400. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3401. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3402. if ($model === 'deepseek-chat') {
  3403. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3404. $model = 'deepseek-v4-flash';
  3405. $thinkingMode = 'disabled';
  3406. } elseif ($model === 'deepseek-reasoner') {
  3407. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3408. $model = 'deepseek-v4-flash';
  3409. $thinkingMode = 'enabled';
  3410. }
  3411. $post_data = [
  3412. 'model' => $model,
  3413. 'messages' => $messages,
  3414. // 'max_tokens' => 8192,
  3415. 'temperature' => 0.7,
  3416. 'frequency_penalty' => 0,
  3417. 'presence_penalty' => 0,
  3418. 'response_format' => ['type' => 'text'],
  3419. 'thinking' => ['type'=>$thinkingMode],
  3420. 'stream' => true // 启用流式输出
  3421. ];
  3422. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3423. // 根据模型类型选择调用方法
  3424. $fullContent = '';
  3425. $fullReasoningContent = '';
  3426. $usage = [];
  3427. try {
  3428. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3429. // DeepSeek 官方模型使用 DeepSeek API
  3430. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3431. } else if (in_array($model, $this->gpt_text_models)) {
  3432. // GPT-5.4 模型使用 TokenRouter API
  3433. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3434. } else {
  3435. // 其他模型使用火山引擎API
  3436. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3437. }
  3438. // 验证返回值类型
  3439. if (!is_iterable($streamGenerator)) {
  3440. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  3441. dLog('deepseek')->error('addChat流式生成器无效', [
  3442. 'generator_type' => $errorType,
  3443. 'model' => $model,
  3444. 'anime_id' => $anime_id
  3445. ]);
  3446. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  3447. 'type' => $errorType,
  3448. 'model' => $model
  3449. ]);
  3450. yield [
  3451. 'type' => 'error',
  3452. 'script' => [],
  3453. 'episode' => [],
  3454. 'answer' => '',
  3455. 'reasoning' => '',
  3456. 'usage' => [],
  3457. 'error' => '接口返回数据异常,请重新请求'
  3458. ];
  3459. return;
  3460. }
  3461. // 处理流式输出
  3462. foreach ($streamGenerator as $chunk) {
  3463. if (isset($chunk['type'])) {
  3464. if ($chunk['type'] === 'done') {
  3465. // 最终结果
  3466. $fullContent = $chunk['full_content'];
  3467. $fullReasoningContent = $chunk['full_reasoning'];
  3468. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3469. } else {
  3470. // 逐块yield数据
  3471. yield $chunk;
  3472. }
  3473. }
  3474. }
  3475. } catch (\Exception $e) {
  3476. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  3477. 'model' => $model,
  3478. 'anime_id' => $anime_id,
  3479. 'trace' => $e->getTraceAsString()
  3480. ]);
  3481. logDB('deepseek', 'error', 'addChat流式处理失败', [
  3482. 'error' => $e->getMessage(),
  3483. 'model' => $model
  3484. ]);
  3485. yield [
  3486. 'type' => 'error',
  3487. 'script' => [],
  3488. 'episode' => [],
  3489. 'answer' => '',
  3490. 'reasoning' => '',
  3491. 'usage' => [],
  3492. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  3493. ];
  3494. return;
  3495. }
  3496. dLog('deepseek')->info('完整内容: '.$fullContent);
  3497. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3498. // 处理完整内容并返回最终结果
  3499. $script_arr = [];
  3500. if ($fullContent) {
  3501. $script_arr = handleScriptContent($fullContent);
  3502. dLog('deepseek')->info('解析内容', $script_arr);
  3503. logDB('deepseek', 'info', '解析内容', $script_arr);
  3504. }
  3505. if (empty($script_arr['roles'])) {
  3506. // 未生成剧本相关内容,保存对话记录并返回提示
  3507. dLog('deepseek')->info('未生成剧本相关的内容');
  3508. try {
  3509. DB::beginTransaction();
  3510. $now = date('Y-m-d H:i:s');
  3511. // 保存对话记录
  3512. $records = [
  3513. [
  3514. 'uid' => $uid,
  3515. 'anime_id' => $anime_id,
  3516. 'sequence' => 0,
  3517. 'role' => 'user',
  3518. 'content' => $prompt,
  3519. 'created_at' => $now,
  3520. 'updated_at' => $now
  3521. ],
  3522. [
  3523. 'uid' => $uid,
  3524. 'anime_id' => $anime_id,
  3525. 'sequence' => 0,
  3526. 'role' => 'assistant',
  3527. // 'content' => $fullContent,
  3528. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  3529. 'created_at' => $now,
  3530. 'updated_at' => $now
  3531. ]
  3532. ];
  3533. DB::table('mp_anime_records')->insert($records);
  3534. DB::commit();
  3535. } catch (\Exception $e) {
  3536. DB::rollBack();
  3537. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3538. }
  3539. yield [
  3540. 'type' => 'done',
  3541. 'script' => [],
  3542. 'episode' => [],
  3543. 'answer' => $fullContent,
  3544. 'reasoning' => $fullReasoningContent,
  3545. 'usage' => $usage,
  3546. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  3547. ];
  3548. return;
  3549. }
  3550. // 如果需要生成原文内容,从script_arr中提取
  3551. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  3552. $content = $script_arr['content'];
  3553. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  3554. if (!$content) {
  3555. yield [
  3556. 'type' => 'done',
  3557. 'script' => [],
  3558. 'episode' => [],
  3559. 'answer' => $fullContent,
  3560. 'reasoning' => $fullReasoningContent,
  3561. 'usage' => $usage,
  3562. 'error' => '未生成剧本内容,请调整提示词再试'
  3563. ];
  3564. return;
  3565. }
  3566. }
  3567. // 替换美术风格
  3568. if ($mappedArtStyle !== '') {
  3569. $script_arr['art_style'] = $mappedArtStyle;
  3570. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  3571. }
  3572. // 新建动漫
  3573. if ($user_anime_name == '新剧本策划') {
  3574. $anime_name = getProp($script_arr, 'script_name');
  3575. // if (!$anime_name) {
  3576. // // 未识别到剧本名,保存对话记录并返回提示
  3577. // dLog('deepseek')->info('未能识别到剧本名称');
  3578. // try {
  3579. // DB::beginTransaction();
  3580. // $now = date('Y-m-d H:i:s');
  3581. // // 保存对话记录
  3582. // $records = [
  3583. // [
  3584. // 'uid' => $uid,
  3585. // 'anime_id' => $anime_id,
  3586. // 'sequence' => 0,
  3587. // 'role' => 'user',
  3588. // 'content' => $prompt,
  3589. // 'created_at' => $now,
  3590. // 'updated_at' => $now
  3591. // ],
  3592. // [
  3593. // 'uid' => $uid,
  3594. // 'anime_id' => $anime_id,
  3595. // 'sequence' => 0,
  3596. // 'role' => 'assistant',
  3597. // 'content' => '未能生成剧本名称,请重试',
  3598. // 'created_at' => $now,
  3599. // 'updated_at' => $now
  3600. // ]
  3601. // ];
  3602. // DB::table('mp_anime_records')->insert($records);
  3603. // DB::commit();
  3604. // } catch (\Exception $e) {
  3605. // DB::rollBack();
  3606. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3607. // }
  3608. // yield [
  3609. // 'type' => 'done',
  3610. // 'script' => [],
  3611. // 'episode' => [],
  3612. // 'answer' => $fullContent,
  3613. // 'reasoning' => $fullReasoningContent,
  3614. // 'usage' => $usage,
  3615. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  3616. // ];
  3617. // return;
  3618. // }
  3619. // 确认对话名称唯一性
  3620. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  3621. $anime_name = $anime_name . '_' . date('YmdHis');
  3622. }
  3623. }else {
  3624. $anime_name = $user_anime_name;
  3625. }
  3626. $table_data = [
  3627. 'user_id' => $uid,
  3628. 'anime_name' => $anime_name,
  3629. 'model' => $model,
  3630. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3631. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3632. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3633. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3634. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3635. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3636. 'art_style_type' => $input_art_style,
  3637. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3638. 'status' => '解析完成',
  3639. 'content' => $content,
  3640. 'is_multi' => $is_multi,
  3641. 'ace_mode' => $ace_mode,
  3642. 'generate_status' => '待执行',
  3643. 'updated_at' => date('Y-m-d H:i:s')
  3644. ];
  3645. if ($table_data['content']) {
  3646. $chapters = $this->splitContent($table_data['content']);
  3647. $chapter_count = count($chapters);
  3648. if ($chapter_count > 0) {
  3649. $table_data['start_episode_sequence'] = 1;
  3650. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  3651. }
  3652. }
  3653. // 如果有剧本ID则进行绑定
  3654. if ($script_id) {
  3655. $table_data['script_id'] = $script_id;
  3656. }
  3657. $single_episode = [];
  3658. try {
  3659. DB::beginTransaction();
  3660. $now = date('Y-m-d H:i:s');
  3661. // 更新动漫大纲
  3662. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3663. if (!$boolen) {
  3664. dLog('deepseek')->info('动漫保存失败', $table_data);
  3665. Utils::throwError('20003:动漫保存失败');
  3666. }
  3667. // 保存对话记录
  3668. $records = [
  3669. [
  3670. 'uid' => $uid,
  3671. 'anime_id' => $anime_id,
  3672. 'sequence' => 0,
  3673. 'role' => 'user',
  3674. 'content' => $prompt,
  3675. 'created_at' => date('Y-m-d H:i:s'),
  3676. 'updated_at' => date('Y-m-d H:i:s')
  3677. ],
  3678. [
  3679. 'uid' => $uid,
  3680. 'anime_id' => $anime_id,
  3681. 'sequence' => 0,
  3682. 'role' => 'assistant',
  3683. 'content' => $fullContent,
  3684. 'created_at' => date('Y-m-d H:i:s'),
  3685. 'updated_at' => date('Y-m-d H:i:s')
  3686. ]
  3687. ];
  3688. // 保存对话记录
  3689. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3690. if (!$boolen3) {
  3691. Utils::throwError('20003:对话记录保存失败');
  3692. }
  3693. if ($is_single) {
  3694. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3695. if (empty($episode_arr['acts'])) {
  3696. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3697. }
  3698. $saveResult = $this->saveEpisodeVersionData(
  3699. $anime_id,
  3700. 1,
  3701. $episode_arr,
  3702. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3703. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3704. null,
  3705. null,
  3706. false,
  3707. $content,
  3708. $now
  3709. );
  3710. $single_episode = $saveResult['episode'];
  3711. $episode_id = $saveResult['episode_id'];
  3712. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3713. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3714. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3715. 'updated_at' => $now
  3716. ]);
  3717. if ($boolen5 === false) {
  3718. Utils::throwError('20003:单剧集主表资源同步失败');
  3719. }
  3720. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3721. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3722. $episode_record_content = '确认分镜大纲';
  3723. if ($content !== '') {
  3724. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  3725. }
  3726. $episode_records = [
  3727. [
  3728. 'uid' => $uid,
  3729. 'anime_id' => $anime_id,
  3730. 'role' => 'user',
  3731. 'content' => $episode_record_content,
  3732. 'sequence' => 1,
  3733. 'episode_id' => $episode_id,
  3734. 'created_at' => $now,
  3735. 'updated_at' => $now
  3736. ],
  3737. [
  3738. 'uid' => $uid,
  3739. 'anime_id' => $anime_id,
  3740. 'role' => 'assistant',
  3741. 'content' => $fullContent,
  3742. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3743. 'sequence' => 1,
  3744. 'episode_id' => $episode_id,
  3745. 'created_at' => $now,
  3746. 'updated_at' => $now
  3747. ]
  3748. ];
  3749. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3750. if (!$boolen4) {
  3751. Utils::throwError('20003:单剧集分镜记录保存失败');
  3752. }
  3753. }
  3754. }catch (\Exception $e) {
  3755. DB::rollBack();
  3756. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  3757. yield [
  3758. 'type' => 'done',
  3759. 'answer' => $fullContent,
  3760. 'reasoning' => $fullReasoningContent,
  3761. 'usage' => $usage,
  3762. 'error' => $e->getMessage(),
  3763. ];
  3764. return;
  3765. }
  3766. DB::commit();
  3767. dLog('deepseek')->info('保存完毕');
  3768. if ($is_single && !empty($single_episode)) {
  3769. // $this->batchSetGlobalRoleImg([
  3770. // 'anime_id' => $anime_id,
  3771. // ]);
  3772. // $this->batchSetGlobalSceneImg([
  3773. // 'anime_id' => $anime_id,
  3774. // ]);
  3775. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  3776. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  3777. }
  3778. $table_data['anime_id'] = $anime_id;
  3779. $table_data['roles'] = json_decode($table_data['roles'], true);
  3780. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  3781. // $table_data['episodes'] = $script_arr['episodes'];
  3782. unset($table_data['created_at']);
  3783. unset($table_data['updated_at']);
  3784. unset($table_data['status']);
  3785. dLog('deepseek')->info('开始返回');
  3786. yield [
  3787. 'type' => 'done',
  3788. 'script' => $table_data,
  3789. 'episode' => $single_episode,
  3790. 'answer' => $fullContent,
  3791. 'reasoning' => $fullReasoningContent,
  3792. 'usage' => $usage
  3793. ];
  3794. }
  3795. public function reGenerateAnime($data) {
  3796. $uid = Site::getUid();
  3797. $file = getProp($data, 'file');
  3798. $content = getProp($data, 'content', '');
  3799. $bid = getProp($data, 'bid', 0);
  3800. $script_id = getProp($data, 'script_id', 0);
  3801. $anime_id = getProp($data, 'anime_id');
  3802. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3803. if (!$anime) {
  3804. Utils::throwError('20003:该对话不存在');
  3805. }
  3806. $user_anime_name = getProp($anime, 'anime_name');
  3807. $prompt = getProp($data, 'prompt');
  3808. // 处理文本模型
  3809. $model = getProp($data, 'model');
  3810. if (!$model) {
  3811. // 用户没有输入,从anime表获取
  3812. $model = getProp($anime, 'model');
  3813. if (!$model) {
  3814. // anime表也没有,使用默认值
  3815. $model = 'doubao-seed-2-0-mini-260215';
  3816. }
  3817. }
  3818. // 验证模型是否在可用模型表中
  3819. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3820. $model = 'doubao-seed-2-0-mini-260215';
  3821. }
  3822. $is_multi = getProp($anime, 'is_multi', 1);
  3823. $is_single = (int)$is_multi !== 1;
  3824. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  3825. if ($is_single) {
  3826. $episode_exists = DB::table('mp_anime_episodes')
  3827. ->where('anime_id', $anime_id)
  3828. ->where('sequence', 1)
  3829. ->exists();
  3830. if ($episode_exists) {
  3831. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  3832. }
  3833. }
  3834. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3835. if ($prompt) {
  3836. $question .= "本次修改要求如下:\n{$prompt}";
  3837. }
  3838. // 提取文件内容
  3839. if ($file) {
  3840. $content = $this->extractFileContent($file);
  3841. if (!$content) {
  3842. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3843. }
  3844. } elseif ($script_id) {
  3845. $content = $this->getContentByScriptId($script_id);
  3846. if (!$content) {
  3847. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3848. }
  3849. } elseif ($bid) {
  3850. $content = $this->getContentByBid($bid);
  3851. if (!$content) {
  3852. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3853. }
  3854. } elseif ($content) {
  3855. $content = filterContent($content);
  3856. }else {
  3857. $content = filterContent(getProp($anime, 'content'));
  3858. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3859. $need_generate_content = true;
  3860. }
  3861. }
  3862. // 判断是否需要生成原文内容
  3863. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3864. // 如果需要生成原文内容,添加额外的要求
  3865. $content_generation_requirement = $need_generate_content
  3866. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3867. : "";
  3868. // 美术风格
  3869. $input_art_style = getProp($anime, 'art_style');
  3870. if (!$input_art_style) {
  3871. $input_art_style = getProp($data, 'art_style');
  3872. }
  3873. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3874. // 美术风格
  3875. if (!$mappedArtStyle) {
  3876. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3877. }else {
  3878. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3879. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3880. }else {
  3881. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3882. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3883. }
  3884. }
  3885. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3886. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3887. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3888. 中年女:邻居阿姨
  3889. 老年男:幽默大爷
  3890. 老年女:婆婆
  3891. 萌娃:奶气萌娃";
  3892. $system_message = ['role'=>'system', 'content'=>$is_single
  3893. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3894. 强制要求:
  3895. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3896. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3897. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3898. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3899. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3900. 普通要求:
  3901. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3902. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3903. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3904. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3905. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3906. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3907. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3908. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3909. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3910. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3911. 3.$mappedArtStyle_prompt\n\n
  3912. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3913. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3914. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3915. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3916. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3917. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3918. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3919. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3920. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3921. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3922. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3923. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3924. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3925. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3926. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3927. 示例如下:\n
  3928. ###剧本名:西昆仑
  3929. ###故事梗概
  3930. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3931. ###剧本亮点
  3932. 亮点1:绝境奇药,生死一线
  3933. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3934. 亮点2:结拜兄妹,化解尴尬
  3935. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3936. 亮点3:纤发夺命,情愫暗涌
  3937. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3938. ###人物关系
  3939. 阿雪与梁萧之间存在兄妹之情。
  3940. ###核心矛盾
  3941. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3942. ###主体列表
  3943. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3944. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3945. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3946. 姿态:站立。}{{甜心小美}}
  3947. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3948. 全景,正面拍摄,青年女性,亚洲人。
  3949. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3950. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3951. 姿态:站立。}{{阳光青年}}
  3952. ###美术风格
  3953. 基础画风风格词:厚涂古风
  3954. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3955. ###场景列表
  3956. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3957. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3958. 无人物。}
  3959. ###分镜剧本
  3960. ##第1幕:徐家老旧厨房 白天 室内
  3961. 分镜1
  3962. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3963. 场景:徐家老旧厨房
  3964. 构图设计:全景,低角度仰视
  3965. 运镜调度:手持拍摄
  3966. 配音角色:旁白
  3967. 出镜角色:许芸-校服装、徐母
  3968. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3969. 画面类型:普通画面
  3970. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3971. 分镜2
  3972. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3973. 场景:徐家老旧厨房
  3974. 构图设计:近景,徐母面部特写
  3975. 运镜调度:固定镜头
  3976. 配音角色:徐母
  3977. 出镜角色:徐母
  3978. 台词内容:问我夜不归宿死哪儿去了。
  3979. 画面类型:对口型
  3980. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3981. ##第2幕:徐家简陋客厅 黄昏 室内
  3982. 分镜3
  3983. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3984. 场景:徐家简陋客厅
  3985. 构图设计:全景,景深虚化
  3986. 运镜调度:固定镜头
  3987. 配音角色:旁白
  3988. 出镜角色:无
  3989. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3990. 画面类型:普通画面
  3991. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3992. 分镜4
  3993. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3994. 场景:徐家简陋客厅
  3995. 构图设计:特写,火车票
  3996. 运镜调度:固定镜头
  3997. 配音角色:旁白
  3998. 出镜角色:无
  3999. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4000. 画面类型:普通画面
  4001. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4002. "
  4003. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4004. 强制要求:\n
  4005. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4006. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4007. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4008. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4009. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4010. 普通要求:\n
  4011. 1.剧本名(必须生成)必须与文档内容高度相关
  4012. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4013. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4014. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4015. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4016. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4017. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4018. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4019. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4020. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4021. 4.$mappedArtStyle_prompt\n\n
  4022. 示例如下:\n
  4023. ###剧本名:西昆仑
  4024. ###故事梗概
  4025. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4026. ###剧本亮点
  4027. 亮点1:绝境奇药,生死一线
  4028. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4029. 亮点2:结拜兄妹,化解尴尬
  4030. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4031. 亮点3:纤发夺命,情愫暗涌
  4032. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4033. ###人物关系
  4034. 阿雪与梁萧之间存在兄妹之情。
  4035. ###核心矛盾
  4036. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4037. ###主体列表
  4038. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4039. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4040. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4041. 姿态:站立。}{{甜心小美}}
  4042. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4043. 全景,正面拍摄,青年女性,亚洲人。
  4044. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4045. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4046. 姿态:站立。}{{阳光青年}}
  4047. ###美术风格
  4048. 基础画风风格词:厚涂古风
  4049. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4050. ###场景列表
  4051. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4052. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4053. 无人物。}"];
  4054. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  4055. $episode_count = $this->extractEpisodeNumber($prompt);
  4056. if ((int)getProp($anime, 'is_multi') !== 1) {
  4057. yield [
  4058. 'type' => 'done',
  4059. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  4060. 'reasoning' => '',
  4061. 'usage' => []
  4062. ];
  4063. return;
  4064. }
  4065. if ($episode_count) {
  4066. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  4067. $system_message = [
  4068. 'role' => 'system',
  4069. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4070. 强制要求:\n
  4071. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4072. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4073. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4074. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4075. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4076. 普通要求:\n
  4077. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4078. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4079. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4080. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4081. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4082. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4083. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4084. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4085. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4086. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  4087. 示例如下:\n
  4088. ###剧本名:西昆仑
  4089. ###故事梗概
  4090. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4091. ###剧本亮点
  4092. 亮点1:绝境奇药,生死一线
  4093. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4094. 亮点2:结拜兄妹,化解尴尬
  4095. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4096. 亮点3:纤发夺命,情愫暗涌
  4097. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4098. ###人物关系
  4099. 阿雪与梁萧之间存在兄妹之情。
  4100. ###核心矛盾
  4101. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4102. ###主体列表
  4103. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4104. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4105. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4106. 姿态:站立。}{{甜心小美}}
  4107. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4108. 全景,正面拍摄,青年女性,亚洲人。
  4109. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4110. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4111. 姿态:站立。}{{阳光青年}}
  4112. ###美术风格
  4113. 基础画风风格词:厚涂古风
  4114. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4115. ###场景列表
  4116. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4117. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4118. 无人物。}
  4119. ###分集详细内容
  4120. ##第1章 重生
  4121. 我重生了。
  4122. 源于一个男人偏执的暗恋。
  4123. ##第2章 相救
  4124. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  4125. 我眼睛扫向站在锅炉后的卞大伟。"
  4126. ];
  4127. // 构建消息
  4128. $messages = [
  4129. $system_message,
  4130. [
  4131. 'role' => 'user',
  4132. 'content' => "以下是文档内容:
  4133. {$content}
  4134. 用户问题:
  4135. {$question}"
  4136. ]
  4137. ];
  4138. }else {
  4139. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  4140. // 构建消息
  4141. $messages = [
  4142. $system_message,
  4143. [
  4144. 'role' => 'user',
  4145. 'content' => "以下是文档内容:
  4146. {$content}
  4147. 用户问题:
  4148. {$question}"
  4149. ]
  4150. ];
  4151. }else {
  4152. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  4153. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  4154. return (array)$value;
  4155. })->toArray();
  4156. array_unshift($messages, $system_message);
  4157. $messages[] = [
  4158. 'role' => 'user',
  4159. 'content' => $prompt
  4160. ];
  4161. }
  4162. }
  4163. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4164. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4165. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4166. if ($model === 'deepseek-chat') {
  4167. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4168. $model = 'deepseek-v4-flash';
  4169. $thinkingMode = 'disabled';
  4170. } elseif ($model === 'deepseek-reasoner') {
  4171. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4172. $model = 'deepseek-v4-flash';
  4173. $thinkingMode = 'enabled';
  4174. }
  4175. $post_data = [
  4176. 'model' => $model,
  4177. 'messages' => $messages,
  4178. // 'max_tokens' => 8192,
  4179. 'temperature' => 0.7,
  4180. 'frequency_penalty' => 0,
  4181. 'presence_penalty' => 0,
  4182. 'response_format' => ['type' => 'text'],
  4183. 'thinking' => ['type' => $thinkingMode],
  4184. 'stream' => true // 启用流式输出
  4185. ];
  4186. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4187. // 根据模型类型选择调用方法
  4188. $fullContent = '';
  4189. $fullReasoningContent = '';
  4190. $usage = [];
  4191. // dd($post_data);
  4192. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  4193. try {
  4194. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4195. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4196. } else if (in_array($model, $this->gpt_text_models)) {
  4197. // GPT-5.4 模型使用 TokenRouter API
  4198. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4199. } else {
  4200. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4201. }
  4202. // 验证返回值类型
  4203. if (!is_iterable($streamGenerator)) {
  4204. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4205. dLog('deepseek')->error('方法名流式生成器无效', [
  4206. 'generator_type' => $errorType,
  4207. 'model' => $model,
  4208. // 添加其他上下文信息
  4209. ]);
  4210. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  4211. 'type' => $errorType,
  4212. 'model' => $model
  4213. ]);
  4214. yield [
  4215. 'type' => 'error',
  4216. // 根据方法返回相应的空数据结构
  4217. 'answer' => '',
  4218. 'reasoning' => '',
  4219. 'usage' => [],
  4220. 'error' => '接口返回数据异常,请重新请求'
  4221. ];
  4222. return;
  4223. }
  4224. // 处理流式输出
  4225. foreach ($streamGenerator as $chunk) {
  4226. if (isset($chunk['type'])) {
  4227. if ($chunk['type'] === 'done') {
  4228. $fullContent = $chunk['full_content'];
  4229. $fullReasoningContent = $chunk['full_reasoning'];
  4230. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4231. } else {
  4232. yield $chunk;
  4233. }
  4234. }
  4235. }
  4236. } catch (\Exception $e) {
  4237. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  4238. 'model' => $model,
  4239. 'trace' => $e->getTraceAsString()
  4240. ]);
  4241. logDB('deepseek', 'error', '方法名流式处理失败', [
  4242. 'error' => $e->getMessage(),
  4243. 'model' => $model
  4244. ]);
  4245. yield [
  4246. 'type' => 'error',
  4247. // 根据方法返回相应的空数据结构
  4248. 'answer' => '',
  4249. 'reasoning' => '',
  4250. 'usage' => [],
  4251. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4252. ];
  4253. return;
  4254. }
  4255. dLog('deepseek')->info('完整内容: '.$fullContent);
  4256. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4257. // 处理完整内容并返回最终结果
  4258. $script_arr = [];
  4259. if ($fullContent) {
  4260. $script_arr = handleScriptContent($fullContent);
  4261. dLog('deepseek')->info('解析内容', $script_arr);
  4262. logDB('deepseek', 'info', '解析内容', $script_arr);
  4263. }
  4264. if (empty($script_arr['roles'])) {
  4265. // 未生成剧本相关内容,保存对话记录并返回提示
  4266. dLog('deepseek')->info('未生成剧本相关的内容');
  4267. try {
  4268. $now = date('Y-m-d H:i:s');
  4269. // 保存对话记录
  4270. $records = [
  4271. [
  4272. 'uid' => $uid,
  4273. 'anime_id' => $anime_id,
  4274. 'sequence' => 0,
  4275. 'role' => 'user',
  4276. 'content' => $prompt,
  4277. 'created_at' => $now,
  4278. 'updated_at' => $now
  4279. ],
  4280. [
  4281. 'uid' => $uid,
  4282. 'anime_id' => $anime_id,
  4283. 'sequence' => 0,
  4284. 'role' => 'assistant',
  4285. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  4286. 'created_at' => $now,
  4287. 'updated_at' => $now
  4288. ]
  4289. ];
  4290. DB::table('mp_anime_records')->insert($records);
  4291. } catch (\Exception $e) {
  4292. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4293. }
  4294. yield [
  4295. 'type' => 'done',
  4296. 'script' => [],
  4297. 'episode' => [],
  4298. 'answer' => $fullContent,
  4299. 'reasoning' => $fullReasoningContent,
  4300. 'usage' => $usage,
  4301. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4302. ];
  4303. return;
  4304. }
  4305. // 替换美术风格
  4306. if ($mappedArtStyle !== '') {
  4307. $script_arr['art_style'] = $mappedArtStyle;
  4308. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4309. }
  4310. if ($user_anime_name != '新剧本策划') {
  4311. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  4312. // 确认对话名称唯一性
  4313. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4314. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  4315. }
  4316. }else {
  4317. $anime_name = $user_anime_name;
  4318. }
  4319. $table_data = [
  4320. 'user_id' => $uid,
  4321. 'model' => $model,
  4322. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4323. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4324. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4325. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4326. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4327. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4328. 'art_style_type' => $input_art_style,
  4329. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4330. 'status' => '解析完成',
  4331. 'generate_status' => '待执行',
  4332. 'updated_at' => date('Y-m-d H:i:s')
  4333. ];
  4334. if ($anime_name) $table_data['anime_name'] = $anime_name;
  4335. // 如果是修改集数,则将content内容更新(会改变原文)
  4336. if (isset($episode_count) && $episode_count > 0) {
  4337. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  4338. $table_data['start_episode_sequence'] = 1;
  4339. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  4340. }else {
  4341. // 如果需要生成原文内容,从script_arr中提取
  4342. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4343. $table_data['content'] = $script_arr['content'];
  4344. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  4345. if (!$table_data['content']) {
  4346. yield [
  4347. 'type' => 'done',
  4348. 'script' => [],
  4349. 'episode' => [],
  4350. 'answer' => $fullContent,
  4351. 'reasoning' => $fullReasoningContent,
  4352. 'usage' => $usage,
  4353. 'error' => '未生成剧本内容,请调整提示词再试'
  4354. ];
  4355. return;
  4356. }
  4357. }
  4358. if (isset($table_data['content']) && $table_data['content']) {
  4359. $chapters = $this->splitContent($table_data['content']);
  4360. $chapter_count = count($chapters);
  4361. if ($chapter_count > 0) {
  4362. $table_data['start_episode_sequence'] = 1;
  4363. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4364. }
  4365. }
  4366. }
  4367. $single_episode = [];
  4368. try {
  4369. DB::beginTransaction();
  4370. $now = date('Y-m-d H:i:s');
  4371. // 更新动漫大纲
  4372. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4373. if (!$boolen) {
  4374. dLog('deepseek')->info('对话修改失败', $table_data);
  4375. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  4376. Utils::throwError('20003:对话修改失败');
  4377. }
  4378. // 保存对话记录
  4379. $records = [
  4380. [
  4381. 'uid' => $uid,
  4382. 'anime_id' => $anime_id,
  4383. 'sequence' => 0,
  4384. 'role' => 'user',
  4385. 'content' => $prompt,
  4386. 'created_at' => $now,
  4387. 'updated_at' => $now
  4388. ],
  4389. [
  4390. 'uid' => $uid,
  4391. 'anime_id' => $anime_id,
  4392. 'sequence' => 0,
  4393. 'role' => 'assistant',
  4394. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4395. 'content' => $fullContent,
  4396. 'created_at' => $now,
  4397. 'updated_at' => $now
  4398. ]
  4399. ];
  4400. // 保存对话记录
  4401. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4402. if (!$boolen3) {
  4403. Utils::throwError('20003:对话记录保存失败');
  4404. }
  4405. // 单剧集模式:生成并保存剧集信息
  4406. if ($is_single) {
  4407. $anime_name = getProp($anime, 'anime_name', '未命名');
  4408. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4409. if (empty($episode_arr['acts'])) {
  4410. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4411. }
  4412. $saveResult = $this->saveEpisodeVersionData(
  4413. $anime_id,
  4414. 1,
  4415. $episode_arr,
  4416. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4417. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4418. null,
  4419. null,
  4420. false,
  4421. $content,
  4422. $now
  4423. );
  4424. $single_episode = $saveResult['episode'];
  4425. $episode_id = $saveResult['episode_id'];
  4426. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4427. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4428. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4429. 'updated_at' => $now
  4430. ]);
  4431. if ($boolen5 === false) {
  4432. Utils::throwError('20003:单剧集主表资源同步失败');
  4433. }
  4434. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4435. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4436. $episode_record_content = '确认分镜大纲';
  4437. if ($content !== '') {
  4438. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4439. }
  4440. $episode_records = [
  4441. [
  4442. 'uid' => $uid,
  4443. 'anime_id' => $anime_id,
  4444. 'role' => 'user',
  4445. 'content' => $episode_record_content,
  4446. 'sequence' => 1,
  4447. 'episode_id' => $episode_id,
  4448. 'created_at' => $now,
  4449. 'updated_at' => $now
  4450. ],
  4451. [
  4452. 'uid' => $uid,
  4453. 'anime_id' => $anime_id,
  4454. 'role' => 'assistant',
  4455. 'content' => $fullContent,
  4456. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4457. 'sequence' => 1,
  4458. 'episode_id' => $episode_id,
  4459. 'created_at' => $now,
  4460. 'updated_at' => $now
  4461. ]
  4462. ];
  4463. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4464. if (!$boolen4) {
  4465. Utils::throwError('20003:单剧集分镜记录保存失败');
  4466. }
  4467. }
  4468. }catch (\Exception $e) {
  4469. DB::rollBack();
  4470. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  4471. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  4472. yield [
  4473. 'type' => 'done',
  4474. 'answer' => $fullContent,
  4475. 'reasoning' => $fullReasoningContent,
  4476. 'usage' => $usage,
  4477. 'error' => $e->getMessage(),
  4478. ];
  4479. return;
  4480. }
  4481. DB::commit();
  4482. dLog('deepseek')->info('保存完毕');
  4483. if ($is_single && !empty($single_episode)) {
  4484. // $this->batchSetGlobalRoleImg([
  4485. // 'anime_id' => $anime_id,
  4486. // ]);
  4487. // $this->batchSetGlobalSceneImg([
  4488. // 'anime_id' => $anime_id,
  4489. // ]);
  4490. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4491. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4492. }
  4493. $table_data['anime_id'] = $anime_id;
  4494. $table_data['roles'] = json_decode($table_data['roles'], true);
  4495. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4496. unset($table_data['updated_at']);
  4497. unset($table_data['status']);
  4498. yield [
  4499. 'type' => 'done',
  4500. 'script' => $table_data,
  4501. 'episode' => $single_episode,
  4502. 'answer' => $fullContent,
  4503. 'reasoning' => $fullReasoningContent,
  4504. 'usage' => $usage
  4505. ];
  4506. }
  4507. public function chat($data) {
  4508. $uid = Site::getUid();
  4509. $anime_id = getProp($data, 'anime_id');
  4510. $file = getProp($data, 'file');
  4511. $content = getProp($data, 'content', '');
  4512. $bid = getProp($data, 'bid', 0);
  4513. $script_id = getProp($data, 'script_id', 0);
  4514. $episode_number = getProp($data, 'episode_number', 1);
  4515. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4516. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4517. if (!$anime) Utils::throwError('20003:该对话不存在!');
  4518. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  4519. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  4520. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  4521. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  4522. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  4523. $roles = is_array($roles) ? $roles : [];
  4524. $scenes = is_array($scenes) ? $scenes : [];
  4525. // 获取最后一集序号
  4526. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  4527. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  4528. // 转换主体列表和场景列表的格式
  4529. // 获取参考主体或场景
  4530. if ((int)$episode_number === 1) {
  4531. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  4532. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  4533. }else {
  4534. $prev_episode_number = $episode_number - 1;
  4535. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  4536. }
  4537. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  4538. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  4539. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  4540. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  4541. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4542. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4543. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4544. 中年女:邻居阿姨
  4545. 老年男:幽默大爷
  4546. 老年女:婆婆
  4547. 萌娃:奶气萌娃";
  4548. if ($roles_content) {
  4549. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  4550. 主体范围:\n {$roles_content}\n
  4551. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  4552. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4553. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4554. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4555. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4556. }else {
  4557. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4558. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4559. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4560. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4561. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4562. }
  4563. if ($scenes_content) {
  4564. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  4565. 场景范围:\n {$scenes_content}\n
  4566. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  4567. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4568. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4569. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4570. }else {
  4571. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4572. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4573. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4574. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4575. }
  4576. // 提取文件内容
  4577. if ($file) {
  4578. $uploaded_content = $this->extractFileContent($file);
  4579. if (!$uploaded_content) {
  4580. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4581. }
  4582. } elseif ($script_id) {
  4583. $uploaded_content = $this->getContentByScriptId($script_id);
  4584. if (!$uploaded_content) {
  4585. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4586. }
  4587. } elseif ($bid) {
  4588. $uploaded_content = $this->getContentByBid($bid);
  4589. if (!$uploaded_content) {
  4590. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4591. }
  4592. } elseif ($content) {
  4593. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  4594. }
  4595. // elseif ($prompt) {
  4596. // $uploaded_content = filterContent($prompt);
  4597. // }
  4598. else {
  4599. $uploaded_content = '';
  4600. }
  4601. $input_art_style = getProp($anime, 'art_style');
  4602. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4603. // 美术风格
  4604. if (!$mappedArtStyle) {
  4605. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4606. }else {
  4607. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4608. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4609. }else {
  4610. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4611. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4612. }
  4613. }
  4614. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4615. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4616. // 强制要求:
  4617. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4618. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4619. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4620. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4621. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  4622. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  4623. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  4624. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  4625. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  4626. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  4627. // - 分镜要和场景列表、人物主体保持一致\n
  4628. // 普通要求:
  4629. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4630. // {$role_demo}
  4631. // {$scene_demo}
  4632. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4633. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4634. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4635. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4636. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4637. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4638. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4639. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4640. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4641. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4642. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4643. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4644. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4645. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4646. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4647. // 5.$mappedArtStyle_prompt\n\n
  4648. // 示例格式:\n
  4649. // 第1集:隐形的守护者
  4650. // ###故事梗概
  4651. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4652. // ###美术风格
  4653. // 基础画风风格词:韩漫二次元
  4654. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4655. // ###主体列表
  4656. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4657. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4658. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4659. // ###场景列表
  4660. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4661. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4662. // 无人物。}
  4663. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4664. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4665. // 无人物。}
  4666. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4667. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4668. // 无人物。}
  4669. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4670. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4671. // 无人物。}
  4672. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4673. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4674. // 无人物。}
  4675. // ###分镜剧本
  4676. // ##第1幕:徐家老旧厨房 白天 室内
  4677. // 分镜1
  4678. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4679. // 场景:徐家老旧厨房
  4680. // 构图设计:全景,低角度仰视
  4681. // 运镜调度:手持拍摄
  4682. // 配音角色:旁白
  4683. // 出镜角色:许芸-校服装、徐母
  4684. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4685. // 画面类型:普通画面
  4686. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4687. // 分镜2
  4688. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4689. // 场景:徐家老旧厨房
  4690. // 构图设计:近景,徐母面部特写
  4691. // 运镜调度:固定镜头
  4692. // 配音角色:徐母
  4693. // 出镜角色:徐母
  4694. // 台词内容:问我夜不归宿死哪儿去了。
  4695. // 画面类型:对口型
  4696. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4697. // ##第2幕:徐家简陋客厅 黄昏 室内
  4698. // 分镜3
  4699. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4700. // 场景:徐家简陋客厅
  4701. // 构图设计:全景,景深虚化
  4702. // 运镜调度:固定镜头
  4703. // 配音角色:旁白
  4704. // 出镜角色:无
  4705. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4706. // 画面类型:普通画面
  4707. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4708. // 分镜4
  4709. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4710. // 场景:徐家简陋客厅
  4711. // 构图设计:特写,火车票
  4712. // 运镜调度:固定镜头
  4713. // 配音角色:旁白
  4714. // 出镜角色:无
  4715. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4716. // 画面类型:普通画面
  4717. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4718. // \n\n";
  4719. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  4720. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  4721. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  4722. 普通要求:
  4723. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4724. {$role_demo}
  4725. {$scene_demo}
  4726. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4727. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4728. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4729. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  4730. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4731. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4732. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4733. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4734. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4735. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4736. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4737. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4738. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4739. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4740. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4741. 5.$mappedArtStyle_prompt
  4742. 6.《情绪-视听语言映射表》:
  4743. 6.1 场景空间与时间心理学 (Scene & Temporality)
  4744. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4745. -----|---------|------------|----------------
  4746. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  4747. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  4748. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  4749. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  4750. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  4751. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4752. -----|---------|------------|----------------
  4753. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  4754. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  4755. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  4756. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  4757. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  4758. --------|---------|--------------|-------------
  4759. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  4760. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  4761. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  4762. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  4763. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  4764. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  4765. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  4766. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  4767. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  4768. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  4769. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  4770. -----|---------|------------|------------
  4771. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  4772. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  4773. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  4774. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  4775. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  4776. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  4777. --------|---------|--------------|----------
  4778. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  4779. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  4780. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  4781. 6.6 声音设计与潜意识影响 (Soundscape)
  4782. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  4783. -----|---------|------------|------------------
  4784. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  4785. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  4786. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  4787. 理论基石:
  4788. - The Five C's of Cinematography by Joseph V. Mascelli
  4789. - Film Art: An Introduction by David Bordwell
  4790. - Sight, Sound, Motion by Herbert Zettl
  4791. - Notes on the Cinematograph by Robert Bresson
  4792. \n\n
  4793. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  4794. 示例格式:\n
  4795. 第1集:隐形的守护者
  4796. ###故事梗概
  4797. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4798. ###美术风格
  4799. 基础画风风格词:韩漫二次元
  4800. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4801. ###主体列表
  4802. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4803. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4804. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4805. ###场景列表
  4806. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4807. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4808. 无人物。}
  4809. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4810. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4811. 无人物。}
  4812. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4813. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4814. 无人物。}
  4815. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4816. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4817. 无人物。}
  4818. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4819. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4820. 无人物。}
  4821. ###分镜剧本
  4822. ##第1幕:徐家老旧厨房 白天 室内
  4823. 分镜1
  4824. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4825. 场景:徐家老旧厨房
  4826. 构图设计:全景,低角度仰视
  4827. 运镜调度:手持拍摄
  4828. 配音角色:旁白
  4829. 出镜角色:许芸-校服装、徐母
  4830. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4831. 画面类型:普通画面
  4832. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4833. 分镜2
  4834. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4835. 场景:徐家老旧厨房
  4836. 构图设计:近景,徐母面部特写
  4837. 运镜调度:固定镜头
  4838. 配音角色:徐母
  4839. 出镜角色:徐母
  4840. 台词内容:问我夜不归宿死哪儿去了。
  4841. 画面类型:对口型
  4842. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4843. ##第2幕:徐家简陋客厅 黄昏 室内
  4844. 分镜3
  4845. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4846. 场景:徐家简陋客厅
  4847. 构图设计:全景,景深虚化
  4848. 运镜调度:固定镜头
  4849. 配音角色:旁白
  4850. 出镜角色:无
  4851. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4852. 画面类型:普通画面
  4853. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4854. 分镜4
  4855. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4856. 场景:徐家简陋客厅
  4857. 构图设计:特写,火车票
  4858. 运镜调度:固定镜头
  4859. 配音角色:旁白
  4860. 出镜角色:无
  4861. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4862. 画面类型:普通画面
  4863. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4864. \n\n";
  4865. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4866. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  4867. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  4868. $prompt = $origin_prompt;
  4869. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  4870. // 获取章节内容
  4871. $full_content = getProp($anime, 'content');
  4872. if ($uploaded_content) {
  4873. $full_content = $uploaded_content;
  4874. }
  4875. // 根据章节内容拆分章节
  4876. $chapters = $this->splitContent($full_content);
  4877. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  4878. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  4879. $messages = [];
  4880. if ($prompt == '确认分镜大纲') {
  4881. // 暂时保留
  4882. $content = $chapter_content;
  4883. if ($is_single) $content = $full_content; // 单剧集使用全文
  4884. if (!$content) {
  4885. Utils::throwError('20003:章节内容无法获取,请确认');
  4886. }
  4887. $question = $is_single
  4888. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  4889. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  4890. // 构建消息
  4891. $messages[] =
  4892. [
  4893. 'role' => 'user',
  4894. 'content' => $question
  4895. ];
  4896. }else if ($prompt == '继续策划下一集') {
  4897. if ($is_single) {
  4898. Utils::throwError('20003:单剧集不支持继续策划下一集');
  4899. }
  4900. $content = $chapter_content;
  4901. if (!$content) {
  4902. Utils::throwError('20003:章节内容无法获取,请确认');
  4903. }
  4904. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  4905. // 获取上一集最后记录
  4906. $prev_sequence = $episode_number - 1;
  4907. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  4908. // 构建消息
  4909. $messages[] =
  4910. [
  4911. 'role' => 'user',
  4912. 'content' => $question
  4913. ];
  4914. }else {
  4915. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  4916. if (!$content) {
  4917. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  4918. }
  4919. if (!$content) {
  4920. Utils::throwError('20003:章节内容无法获取,请确认');
  4921. }
  4922. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  4923. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  4924. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  4925. if ($origin_prompt) {
  4926. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  4927. }
  4928. $messages[] =
  4929. [
  4930. 'role' => 'user',
  4931. 'content' => $question
  4932. ];
  4933. }
  4934. // 处理文本模型
  4935. $model = getProp($data, 'model');
  4936. if (!$model) {
  4937. // 用户没有输入,从anime表获取
  4938. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4939. $model = getProp($anime, 'model');
  4940. if (!$model) {
  4941. // anime表也没有,使用默认值
  4942. $model = 'doubao-seed-2-0-mini-260215';
  4943. }
  4944. }
  4945. // 验证模型是否在可用模型表中
  4946. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4947. $model = 'doubao-seed-2-0-mini-260215';
  4948. }
  4949. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4950. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4951. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4952. if ($model === 'deepseek-chat') {
  4953. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4954. $model = 'deepseek-v4-flash';
  4955. $thinkingMode = 'disabled';
  4956. } elseif ($model === 'deepseek-reasoner') {
  4957. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4958. $model = 'deepseek-v4-flash';
  4959. $thinkingMode = 'enabled';
  4960. }
  4961. $post_data = [
  4962. 'model' => $model,
  4963. 'messages' => $messages,
  4964. // 'max_tokens' => 8192,
  4965. 'temperature' => 0.2,
  4966. 'frequency_penalty' => 0,
  4967. 'presence_penalty' => 0,
  4968. 'response_format' => ['type' => 'text'],
  4969. 'thinking' => ['type' => $thinkingMode],
  4970. 'stream' => true // 启用流式输出
  4971. ];
  4972. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4973. // 根据模型类型选择调用方法
  4974. $fullContent = '';
  4975. $fullReasoningContent = '';
  4976. $usage = [];
  4977. try {
  4978. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4979. // DeepSeek 官方模型使用 DeepSeek API
  4980. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4981. } else if (in_array($model, $this->gpt_text_models)) {
  4982. // GPT-5.4 模型使用 TokenRouter API
  4983. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4984. } else {
  4985. // 其他模型使用火山引擎API
  4986. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4987. }
  4988. // 验证返回值类型
  4989. if (!is_iterable($streamGenerator)) {
  4990. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4991. dLog('deepseek')->error('chat流式生成器无效', [
  4992. 'generator_type' => $errorType,
  4993. 'model' => $model,
  4994. 'anime_id' => $anime_id,
  4995. 'episode_number' => $episode_number
  4996. ]);
  4997. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  4998. 'type' => $errorType,
  4999. 'model' => $model
  5000. ]);
  5001. yield [
  5002. 'type' => 'error',
  5003. 'episode' => [],
  5004. 'answer' => '',
  5005. 'reasoning' => '',
  5006. 'usage' => [],
  5007. 'error' => '接口返回数据异常,请重新请求'
  5008. ];
  5009. return;
  5010. }
  5011. // 处理流式输出
  5012. foreach ($streamGenerator as $chunk) {
  5013. if (isset($chunk['type'])) {
  5014. if ($chunk['type'] === 'done') {
  5015. // 最终结果
  5016. $fullContent = $chunk['full_content'];
  5017. $fullReasoningContent = $chunk['full_reasoning'];
  5018. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5019. } else {
  5020. // 逐块yield数据
  5021. yield $chunk;
  5022. }
  5023. }
  5024. }
  5025. } catch (\Exception $e) {
  5026. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  5027. 'model' => $model,
  5028. 'anime_id' => $anime_id,
  5029. 'episode_number' => $episode_number,
  5030. 'trace' => $e->getTraceAsString()
  5031. ]);
  5032. logDB('deepseek', 'error', 'chat流式处理失败', [
  5033. 'error' => $e->getMessage(),
  5034. 'model' => $model
  5035. ]);
  5036. yield [
  5037. 'type' => 'error',
  5038. 'episode' => [],
  5039. 'answer' => '',
  5040. 'reasoning' => '',
  5041. 'usage' => [],
  5042. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5043. ];
  5044. return;
  5045. }
  5046. dLog('deepseek')->info('完整内容: '.$fullContent);
  5047. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5048. // 处理完整内容并返回最终结果
  5049. $episode_arr = handleEpisodeContent($fullContent);
  5050. logDB('deepseek', 'info', '解析内容', $episode_arr);
  5051. if (empty($episode_arr['acts'])) {
  5052. // 未生成剧本相关内容,保存对话记录并返回提示
  5053. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  5054. try {
  5055. $now = date('Y-m-d H:i:s');
  5056. // 保存对话记录
  5057. $records = [
  5058. [
  5059. 'uid' => $uid,
  5060. 'anime_id' => $anime_id,
  5061. 'sequence' => $episode_number,
  5062. 'role' => 'user',
  5063. 'content' => $prompt,
  5064. 'created_at' => $now,
  5065. 'updated_at' => $now
  5066. ],
  5067. [
  5068. 'uid' => $uid,
  5069. 'anime_id' => $anime_id,
  5070. 'sequence' => $episode_number,
  5071. 'role' => 'assistant',
  5072. 'content' => $fullContent,
  5073. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5074. 'created_at' => $now,
  5075. 'updated_at' => $now
  5076. ]
  5077. ];
  5078. DB::table('mp_anime_records')->insert($records);
  5079. } catch (\Exception $e) {
  5080. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5081. }
  5082. yield [
  5083. 'type' => 'done',
  5084. 'episode' => [],
  5085. 'answer' => $fullContent,
  5086. 'reasoning' => $fullReasoningContent,
  5087. 'usage' => $usage,
  5088. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  5089. ];
  5090. return;
  5091. }
  5092. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  5093. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  5094. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  5095. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  5096. $now = date('Y-m-d H:i:s');
  5097. try {
  5098. DB::beginTransaction();
  5099. $saveResult = $this->saveEpisodeVersionData(
  5100. $anime_id,
  5101. $episode_number,
  5102. $episode_arr,
  5103. $existing_roles,
  5104. $existing_scenes,
  5105. $current_episode,
  5106. $base_episode,
  5107. $is_regenerate_version,
  5108. $content,
  5109. $now
  5110. );
  5111. $episode = $saveResult['episode'];
  5112. $episode_id = $saveResult['episode_id'];
  5113. $merged_roles = $saveResult['merged_roles'];
  5114. $merged_scenes = $saveResult['merged_scenes'];
  5115. $record_content = $origin_prompt;
  5116. if ($uploaded_content !== '') {
  5117. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  5118. }
  5119. $records = [
  5120. [
  5121. 'uid' => $uid,
  5122. 'anime_id' => $anime_id,
  5123. 'role' => 'user',
  5124. 'content' => $record_content,
  5125. 'sequence' => $episode_number,
  5126. 'episode_id' => $episode_id,
  5127. 'created_at' => $now,
  5128. 'updated_at' => $now
  5129. ],
  5130. [
  5131. 'uid' => $uid,
  5132. 'anime_id' => $anime_id,
  5133. 'role' => 'assistant',
  5134. 'content' => $fullContent,
  5135. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5136. 'sequence' => $episode_number,
  5137. 'episode_id' => $episode_id,
  5138. 'created_at' => $now,
  5139. 'updated_at' => $now
  5140. ]
  5141. ];
  5142. $boolen4 = DB::table('mp_anime_records')->insert($records);
  5143. if (!$boolen4) {
  5144. Utils::throwError('20003:对话记录保存失败');
  5145. }
  5146. // 保存模型和内容到anime表
  5147. $update_anime_data = [
  5148. 'model' => $model,
  5149. 'updated_at' => $now
  5150. ];
  5151. if ($uploaded_content) {
  5152. $update_anime_data['content'] = $uploaded_content;
  5153. }
  5154. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  5155. }catch (\Exception $e) {
  5156. DB::rollBack();
  5157. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5158. yield [
  5159. 'type' => 'done',
  5160. 'answer' => $fullContent,
  5161. 'reasoning' => $fullReasoningContent,
  5162. 'usage' => $usage,
  5163. 'error' => $e->getMessage(),
  5164. ];
  5165. return;
  5166. }
  5167. DB::commit();
  5168. if ($is_global_generate_pics) {
  5169. // // 批量生成全局角色图片
  5170. // $this->batchSetGlobalRoleImg([
  5171. // 'anime_id' => $anime_id,
  5172. // ], true);
  5173. // // 批量生成全局场景图片
  5174. // $this->batchSetGlobalSceneImg([
  5175. // 'anime_id' => $anime_id,
  5176. // ], true);
  5177. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5178. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5179. }
  5180. $episode['episode_id'] = $episode_id;
  5181. $episode['roles'] = $merged_roles;
  5182. $episode['scenes'] = $merged_scenes;
  5183. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  5184. yield [
  5185. 'type' => 'done',
  5186. 'episode' => $episode,
  5187. 'answer' => $fullContent,
  5188. 'reasoning' => $fullReasoningContent,
  5189. 'usage' => $usage
  5190. ];
  5191. }
  5192. public function addChatForAce($data) {
  5193. $uid = Site::getUid();
  5194. $anime_id = getProp($data, 'anime_id');
  5195. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5196. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5197. if (!$anime) Utils::throwError('20003:对话不存在');
  5198. $file = getProp($data, 'file');
  5199. $content = getProp($data, 'content', '');
  5200. $bid = getProp($data, 'bid', 0);
  5201. $script_id = getProp($data, 'script_id', 0);
  5202. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5203. $prompt = getProp($data, 'prompt');
  5204. $extra_products = getProp($data, 'products', []);
  5205. if (!$extra_products) {
  5206. $extra_products = getProp($anime, 'extra_products');
  5207. if ($extra_products) {
  5208. $extra_products = json_decode($extra_products, true);
  5209. }else {
  5210. $extra_products = [];
  5211. }
  5212. }else {
  5213. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  5214. }
  5215. $user_anime_name = getProp($anime, 'anime_name');
  5216. // 处理提示词
  5217. if ($prompt && $extra_products) {
  5218. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  5219. foreach($extra_products as $item) {
  5220. $product_name = getProp($item, 'product_name');
  5221. if ($product_name) {
  5222. // 替换 {product_name} 为 product_name
  5223. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  5224. }
  5225. }
  5226. }
  5227. // 处理文本模型
  5228. $model = getProp($data, 'model');
  5229. if (!$model) {
  5230. // 用户没有输入,从anime表获取
  5231. $model = getProp($anime, 'model');
  5232. if (!$model) {
  5233. // anime表也没有,使用默认值
  5234. $model = 'doubao-seed-2-0-mini-260215';
  5235. }
  5236. }
  5237. // 验证模型是否在可用模型表中
  5238. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5239. $model = 'doubao-seed-2-0-mini-260215';
  5240. }
  5241. $is_multi = getProp($anime, 'is_multi');
  5242. $is_single = (int)$is_multi !== 1;
  5243. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  5244. if ($prompt) {
  5245. $question .= "本次修改要求如下:\n{$prompt}";
  5246. }
  5247. // if (!$file && !$content && !$bid) {
  5248. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5249. // }
  5250. // 提取文件内容
  5251. if ($file) {
  5252. $content = $this->extractFileContent($file);
  5253. if (!$content) {
  5254. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5255. }
  5256. } elseif ($script_id) {
  5257. $content = $this->getContentByScriptId($script_id);
  5258. if (!$content) {
  5259. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5260. }
  5261. } elseif ($bid) {
  5262. $content = $this->getContentByBid($bid);
  5263. if (!$content) {
  5264. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5265. }
  5266. } elseif ($content) {
  5267. $content = filterContent($content);
  5268. } else {
  5269. $content = getProp($anime, 'content');
  5270. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5271. $need_generate_content = true;
  5272. }
  5273. }
  5274. // 美术风格
  5275. $input_art_style = getProp($data, 'art_style');
  5276. if (!$input_art_style) {
  5277. $mappedArtStyle = getProp($anime, 'art_style');
  5278. }else {
  5279. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5280. }
  5281. // 判断是否需要生成原文内容
  5282. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5283. // 如果需要生成原文内容,添加额外的要求
  5284. $content_generation_requirement = $need_generate_content
  5285. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5286. : "";
  5287. // 美术风格
  5288. if (!$mappedArtStyle) {
  5289. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5290. }else {
  5291. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5292. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5293. }else {
  5294. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5295. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5296. }
  5297. }
  5298. // 构建主体和场景提示词
  5299. $extra_role_prompt = "\n";
  5300. $extra_scene_prompt = "\n";
  5301. $ref_products = []; // 参考资产
  5302. if ($extra_products) {
  5303. foreach($extra_products as $item) {
  5304. $product = getProp($item, 'product');
  5305. $product_name = getProp($item, 'product_name');
  5306. if ($product_name == '旁白') continue;
  5307. $ref_products[$product_name] = $item;
  5308. $pic_prompt = getProp($item, 'pic_prompt');
  5309. if ((int)$product === 1) {
  5310. // 拼接角色信息
  5311. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5312. } elseif ((int)$product === 2) {
  5313. // 拼接场景信息
  5314. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5315. }
  5316. }
  5317. // 优化提示词,融入剧本
  5318. if (!empty(trim($extra_role_prompt))) {
  5319. $extra_role_prompt = "\n2.5【强制主体设定-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  5320. }
  5321. if (!empty(trim($extra_scene_prompt))) {
  5322. $extra_scene_prompt = "\n3.4【强制场景设定-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  5323. }
  5324. }
  5325. $systemPrompt = $is_single
  5326. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5327. 强制要求:
  5328. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5329. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5330. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5331. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5332. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5333. 普通要求:
  5334. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5335. 3.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5336. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5337. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5338. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5339. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5340. {$extra_role_prompt}
  5341. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5342. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5343. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5344. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5345. {$extra_scene_prompt}
  5346. 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  5347. 4.1片段分割逻辑(优先级从高到低):
  5348. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  5349. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  5350. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  5351. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  5352. 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  5353. - 片段数量格式为: 片段数量:8
  5354. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5355. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  5356. 4.3分镜结构:每个分镜包含以下字段:
  5357. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  5358. - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  5359. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  5360. - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  5361. - 运镜:场景+画面描述+运镜
  5362. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  5363. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  5364. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  5365. 5.{$mappedArtStyle_prompt}\n\n
  5366. 示例如下:\n
  5367. ###剧本名:西昆仑
  5368. ###故事梗概
  5369. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5370. ###剧本亮点
  5371. 亮点1:绝境奇药,生死一线
  5372. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5373. 亮点2:结拜兄妹,化解尴尬
  5374. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5375. 亮点3:纤发夺命,情愫暗涌
  5376. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5377. ###人物关系
  5378. 阿雪与梁萧之间存在兄妹之情。
  5379. ###核心矛盾
  5380. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5381. ###主体列表
  5382. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5383. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5384. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5385. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5386. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5387. 全景,正面拍摄,青年女性,亚洲人。
  5388. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5389. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5390. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5391. ###美术风格
  5392. 基础画风风格词:厚涂古风
  5393. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5394. ###场景列表
  5395. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5396. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5397. 无人物。}
  5398. ###分段剧本
  5399. 片段数量:8
  5400. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  5401. ##片段1
  5402. 时长:12s
  5403. 分镜1
  5404. 场景:边境小镇街道
  5405. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  5406. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  5407. 配音台词:
  5408. 背景音效:
  5409. 分镜2
  5410. 场景:悦来酒馆
  5411. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  5412. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  5413. 配音台词:
  5414. 背景音效:
  5415. 分镜3
  5416. 场景:悦来酒馆
  5417. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  5418. 运镜:从中景推向令牌特写。
  5419. 配音台词:
  5420. 背景音效:
  5421. 分镜4
  5422. 场景:悦来酒馆
  5423. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  5424. 运镜:极速推向酒水溅起的瞬间。
  5425. 配音台词:
  5426. 背景音效:
  5427. 分镜5
  5428. 镜头描述
  5429. 场景:悦来酒馆
  5430. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  5431. 运镜:固定机位,利用倾斜构图制造压迫感。
  5432. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  5433. 背景音效:
  5434. \n\n"
  5435. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5436. 强制要求:\n
  5437. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5438. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5439. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5440. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5441. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5442. 普通要求:\n
  5443. 1.剧本名(必须生成)必须与文档内容高度相关
  5444. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5445. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5446. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5447. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5448. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5449. {$extra_role_prompt}
  5450. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5451. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5452. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5453. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5454. {$extra_scene_prompt}
  5455. 4.{$mappedArtStyle_prompt}\n\n
  5456. 示例如下:\n
  5457. ###剧本名:西昆仑
  5458. ###故事梗概
  5459. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5460. ###剧本亮点
  5461. 亮点1:绝境奇药,生死一线
  5462. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5463. 亮点2:结拜兄妹,化解尴尬
  5464. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5465. 亮点3:纤发夺命,情愫暗涌
  5466. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5467. ###人物关系
  5468. 阿雪与梁萧之间存在兄妹之情。
  5469. ###核心矛盾
  5470. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5471. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5472. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  5473. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  5474. ###主体列表
  5475. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5476. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5477. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5478. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5479. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5480. 全景,正面拍摄,青年女性,亚洲人。
  5481. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5482. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5483. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5484. ###美术风格
  5485. 基础画风风格词:厚涂古风
  5486. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5487. ###场景列表
  5488. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5489. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5490. 无人物。}";
  5491. // 构建消息
  5492. $messages = [
  5493. [
  5494. 'role' => 'system',
  5495. 'content' => $systemPrompt
  5496. ],
  5497. [
  5498. 'role' => 'user',
  5499. 'content' => "以下是文档内容:
  5500. {$content}
  5501. 用户问题:
  5502. {$question}"
  5503. ]
  5504. ];
  5505. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5506. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5507. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5508. if ($model === 'deepseek-chat') {
  5509. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5510. $model = 'deepseek-v4-flash';
  5511. $thinkingMode = 'disabled';
  5512. } elseif ($model === 'deepseek-reasoner') {
  5513. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5514. $model = 'deepseek-v4-flash';
  5515. $thinkingMode = 'enabled';
  5516. }
  5517. $post_data = [
  5518. 'model' => $model,
  5519. 'messages' => $messages,
  5520. // 'max_tokens' => 8192,
  5521. 'temperature' => 0.7,
  5522. 'frequency_penalty' => 0,
  5523. 'presence_penalty' => 0,
  5524. 'response_format' => ['type' => 'text'],
  5525. 'thinking' => ['type'=>$thinkingMode],
  5526. 'stream' => true // 启用流式输出
  5527. ];
  5528. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5529. // 根据模型类型选择调用方法
  5530. $fullContent = '';
  5531. $fullReasoningContent = '';
  5532. $usage = [];
  5533. try {
  5534. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5535. // DeepSeek 官方模型使用 DeepSeek API
  5536. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5537. } else if (in_array($model, $this->gpt_text_models)) {
  5538. // GPT-5.4 模型使用 TokenRouter API
  5539. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5540. } else {
  5541. // 其他模型使用火山引擎API
  5542. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5543. }
  5544. // 验证返回值类型
  5545. if (!is_iterable($streamGenerator)) {
  5546. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5547. dLog('deepseek')->error('addChat流式生成器无效', [
  5548. 'generator_type' => $errorType,
  5549. 'model' => $model,
  5550. 'anime_id' => $anime_id
  5551. ]);
  5552. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5553. 'type' => $errorType,
  5554. 'model' => $model
  5555. ]);
  5556. yield [
  5557. 'type' => 'error',
  5558. 'script' => [],
  5559. 'episode' => [],
  5560. 'answer' => '',
  5561. 'reasoning' => '',
  5562. 'usage' => [],
  5563. 'error' => '接口返回数据异常,请重新请求'
  5564. ];
  5565. return;
  5566. }
  5567. // 处理流式输出
  5568. foreach ($streamGenerator as $chunk) {
  5569. if (isset($chunk['type'])) {
  5570. if ($chunk['type'] === 'done') {
  5571. // 最终结果
  5572. $fullContent = $chunk['full_content'];
  5573. $fullReasoningContent = $chunk['full_reasoning'];
  5574. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5575. } else {
  5576. // 逐块yield数据
  5577. yield $chunk;
  5578. }
  5579. }
  5580. }
  5581. } catch (\Exception $e) {
  5582. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5583. 'model' => $model,
  5584. 'anime_id' => $anime_id,
  5585. 'trace' => $e->getTraceAsString()
  5586. ]);
  5587. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5588. 'error' => $e->getMessage(),
  5589. 'model' => $model
  5590. ]);
  5591. yield [
  5592. 'type' => 'error',
  5593. 'script' => [],
  5594. 'episode' => [],
  5595. 'answer' => '',
  5596. 'reasoning' => '',
  5597. 'usage' => [],
  5598. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5599. ];
  5600. return;
  5601. }
  5602. dLog('deepseek')->info('完整内容: '.$fullContent);
  5603. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5604. // 处理完整内容并返回最终结果
  5605. $script_arr = [];
  5606. if ($fullContent) {
  5607. $script_arr = handleScriptContentForAce($fullContent);
  5608. dLog('deepseek')->info('解析内容', $script_arr);
  5609. logDB('deepseek', 'info', '解析内容', $script_arr);
  5610. }
  5611. if (empty($script_arr['roles'])) {
  5612. // 未生成剧本相关内容,保存对话记录并返回提示
  5613. dLog('deepseek')->info('未生成剧本相关的内容');
  5614. try {
  5615. DB::beginTransaction();
  5616. $now = date('Y-m-d H:i:s');
  5617. // 保存对话记录
  5618. $records = [
  5619. [
  5620. 'uid' => $uid,
  5621. 'anime_id' => $anime_id,
  5622. 'sequence' => 0,
  5623. 'role' => 'user',
  5624. 'content' => $prompt,
  5625. 'created_at' => $now,
  5626. 'updated_at' => $now
  5627. ],
  5628. [
  5629. 'uid' => $uid,
  5630. 'anime_id' => $anime_id,
  5631. 'sequence' => 0,
  5632. 'role' => 'assistant',
  5633. // 'content' => $fullContent,
  5634. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5635. 'created_at' => $now,
  5636. 'updated_at' => $now
  5637. ]
  5638. ];
  5639. DB::table('mp_anime_records')->insert($records);
  5640. DB::commit();
  5641. } catch (\Exception $e) {
  5642. DB::rollBack();
  5643. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5644. }
  5645. yield [
  5646. 'type' => 'done',
  5647. 'script' => [],
  5648. 'episode' => [],
  5649. 'answer' => $fullContent,
  5650. 'reasoning' => $fullReasoningContent,
  5651. 'usage' => $usage,
  5652. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5653. ];
  5654. return;
  5655. }
  5656. // 如果需要生成原文内容,从script_arr中提取
  5657. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5658. $content = $script_arr['content'];
  5659. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5660. if (!$content) {
  5661. yield [
  5662. 'type' => 'done',
  5663. 'script' => [],
  5664. 'episode' => [],
  5665. 'answer' => $fullContent,
  5666. 'reasoning' => $fullReasoningContent,
  5667. 'usage' => $usage,
  5668. 'error' => '未生成剧本内容,请调整提示词再试'
  5669. ];
  5670. return;
  5671. }
  5672. }
  5673. // 替换美术风格
  5674. if ($mappedArtStyle !== '') {
  5675. $script_arr['art_style'] = $mappedArtStyle;
  5676. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5677. }
  5678. // 新建动漫
  5679. if ($user_anime_name == '新剧本策划') {
  5680. $anime_name = getProp($script_arr, 'script_name');
  5681. // if (!$anime_name) {
  5682. // // 未识别到剧本名,保存对话记录并返回提示
  5683. // dLog('deepseek')->info('未能识别到剧本名称');
  5684. // try {
  5685. // DB::beginTransaction();
  5686. // $now = date('Y-m-d H:i:s');
  5687. // // 保存对话记录
  5688. // $records = [
  5689. // [
  5690. // 'uid' => $uid,
  5691. // 'anime_id' => $anime_id,
  5692. // 'sequence' => 0,
  5693. // 'role' => 'user',
  5694. // 'content' => $prompt,
  5695. // 'created_at' => $now,
  5696. // 'updated_at' => $now
  5697. // ],
  5698. // [
  5699. // 'uid' => $uid,
  5700. // 'anime_id' => $anime_id,
  5701. // 'sequence' => 0,
  5702. // 'role' => 'assistant',
  5703. // 'content' => '未能生成剧本名称,请重试',
  5704. // 'created_at' => $now,
  5705. // 'updated_at' => $now
  5706. // ]
  5707. // ];
  5708. // DB::table('mp_anime_records')->insert($records);
  5709. // DB::commit();
  5710. // } catch (\Exception $e) {
  5711. // DB::rollBack();
  5712. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5713. // }
  5714. // yield [
  5715. // 'type' => 'done',
  5716. // 'script' => [],
  5717. // 'episode' => [],
  5718. // 'answer' => $fullContent,
  5719. // 'reasoning' => $fullReasoningContent,
  5720. // 'usage' => $usage,
  5721. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  5722. // ];
  5723. // return;
  5724. // }
  5725. // 确认对话名称唯一性
  5726. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5727. $anime_name = $anime_name . '_' . date('YmdHis');
  5728. }
  5729. }else {
  5730. $anime_name = $user_anime_name;
  5731. }
  5732. $table_data = [
  5733. 'user_id' => $uid,
  5734. 'anime_name' => $anime_name,
  5735. 'model' => $model,
  5736. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5737. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5738. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5739. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5740. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5741. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5742. 'art_style_type' => $input_art_style,
  5743. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5744. 'status' => '解析完成',
  5745. 'content' => $content,
  5746. 'is_multi' => $is_multi,
  5747. 'ace_mode' => $ace_mode,
  5748. 'generate_status' => '待执行',
  5749. 'updated_at' => date('Y-m-d H:i:s')
  5750. ];
  5751. if ($table_data['content']) {
  5752. $chapters = $this->splitContent($table_data['content']);
  5753. $chapter_count = count($chapters);
  5754. if ($chapter_count > 0) {
  5755. $table_data['start_episode_sequence'] = 1;
  5756. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5757. }
  5758. }
  5759. if ($extra_products) {
  5760. $table_data['extra_products'] = json_encode($extra_products, 256);
  5761. }
  5762. // 如果有剧本ID则进行绑定
  5763. if ($script_id) {
  5764. $table_data['script_id'] = $script_id;
  5765. }
  5766. $single_episode = [];
  5767. try {
  5768. DB::beginTransaction();
  5769. $now = date('Y-m-d H:i:s');
  5770. // 更新动漫大纲
  5771. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5772. if (!$boolen) {
  5773. dLog('deepseek')->info('动漫保存失败', $table_data);
  5774. Utils::throwError('20003:动漫保存失败');
  5775. }
  5776. // 保存对话记录
  5777. $records = [
  5778. [
  5779. 'uid' => $uid,
  5780. 'anime_id' => $anime_id,
  5781. 'sequence' => 0,
  5782. 'role' => 'user',
  5783. 'content' => $prompt,
  5784. 'created_at' => date('Y-m-d H:i:s'),
  5785. 'updated_at' => date('Y-m-d H:i:s')
  5786. ],
  5787. [
  5788. 'uid' => $uid,
  5789. 'anime_id' => $anime_id,
  5790. 'sequence' => 0,
  5791. 'role' => 'assistant',
  5792. 'content' => $fullContent,
  5793. 'created_at' => date('Y-m-d H:i:s'),
  5794. 'updated_at' => date('Y-m-d H:i:s')
  5795. ]
  5796. ];
  5797. // 保存对话记录
  5798. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5799. if (!$boolen3) {
  5800. Utils::throwError('20003:对话记录保存失败');
  5801. }
  5802. if ($is_single) {
  5803. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5804. if (empty($episode_arr['acts'])) {
  5805. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5806. }
  5807. $saveResult = $this->saveEpisodeVersionData(
  5808. $anime_id,
  5809. 1,
  5810. $episode_arr,
  5811. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5812. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5813. null,
  5814. null,
  5815. false,
  5816. $content,
  5817. $now,
  5818. $ref_products
  5819. );
  5820. $single_episode = $saveResult['episode'];
  5821. $episode_id = $saveResult['episode_id'];
  5822. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5823. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5824. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5825. 'updated_at' => $now
  5826. ]);
  5827. if ($boolen5 === false) {
  5828. Utils::throwError('20003:单剧集主表资源同步失败');
  5829. }
  5830. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5831. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5832. $episode_record_content = '确认分镜大纲';
  5833. if ($content !== '') {
  5834. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5835. }
  5836. $episode_records = [
  5837. [
  5838. 'uid' => $uid,
  5839. 'anime_id' => $anime_id,
  5840. 'role' => 'user',
  5841. 'content' => $episode_record_content,
  5842. 'sequence' => 1,
  5843. 'episode_id' => $episode_id,
  5844. 'created_at' => $now,
  5845. 'updated_at' => $now
  5846. ],
  5847. [
  5848. 'uid' => $uid,
  5849. 'anime_id' => $anime_id,
  5850. 'role' => 'assistant',
  5851. 'content' => $fullContent,
  5852. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5853. 'sequence' => 1,
  5854. 'episode_id' => $episode_id,
  5855. 'created_at' => $now,
  5856. 'updated_at' => $now
  5857. ]
  5858. ];
  5859. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5860. if (!$boolen4) {
  5861. Utils::throwError('20003:单剧集分镜记录保存失败');
  5862. }
  5863. }
  5864. }catch (\Exception $e) {
  5865. DB::rollBack();
  5866. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5867. yield [
  5868. 'type' => 'done',
  5869. 'answer' => $fullContent,
  5870. 'reasoning' => $fullReasoningContent,
  5871. 'usage' => $usage,
  5872. 'error' => $e->getMessage(),
  5873. ];
  5874. return;
  5875. }
  5876. DB::commit();
  5877. dLog('deepseek')->info('保存完毕');
  5878. if ($is_single && !empty($single_episode)) {
  5879. // $this->batchSetGlobalRoleImg([
  5880. // 'anime_id' => $anime_id,
  5881. // ]);
  5882. // $this->batchSetGlobalSceneImg([
  5883. // 'anime_id' => $anime_id,
  5884. // ]);
  5885. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5886. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5887. }
  5888. $table_data['anime_id'] = $anime_id;
  5889. $table_data['roles'] = json_decode($table_data['roles'], true);
  5890. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5891. // $table_data['episodes'] = $script_arr['episodes'];
  5892. unset($table_data['created_at']);
  5893. unset($table_data['updated_at']);
  5894. unset($table_data['status']);
  5895. dLog('deepseek')->info('开始返回');
  5896. yield [
  5897. 'type' => 'done',
  5898. 'script' => $table_data,
  5899. 'episode' => $single_episode,
  5900. 'answer' => $fullContent,
  5901. 'reasoning' => $fullReasoningContent,
  5902. 'usage' => $usage
  5903. ];
  5904. }
  5905. public function reGenerateAnimeForAce($data) {
  5906. $uid = Site::getUid();
  5907. $file = getProp($data, 'file');
  5908. $content = getProp($data, 'content', '');
  5909. $bid = getProp($data, 'bid', 0);
  5910. $script_id = getProp($data, 'script_id', 0);
  5911. $anime_id = getProp($data, 'anime_id');
  5912. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5913. if (!$anime) {
  5914. Utils::throwError('20003:该对话不存在');
  5915. }
  5916. $extra_products = getProp($data, 'products', []);
  5917. if (!$extra_products) {
  5918. $extra_products = getProp($anime, 'extra_products');
  5919. if ($extra_products) {
  5920. $extra_products = json_decode($extra_products, true);
  5921. }else {
  5922. $extra_products = [];
  5923. }
  5924. }else {
  5925. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  5926. }
  5927. $user_anime_name = getProp($anime, 'anime_name');
  5928. $prompt = getProp($data, 'prompt');
  5929. // 处理提示词
  5930. if ($prompt && $extra_products) {
  5931. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  5932. foreach($extra_products as $item) {
  5933. $product_name = getProp($item, 'product_name');
  5934. if ($product_name) {
  5935. // 替换 {product_name} 为 product_name
  5936. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  5937. }
  5938. }
  5939. }
  5940. // 处理文本模型
  5941. $model = getProp($data, 'model');
  5942. if (!$model) {
  5943. // 用户没有输入,从anime表获取
  5944. $model = getProp($anime, 'model');
  5945. if (!$model) {
  5946. // anime表也没有,使用默认值
  5947. $model = 'doubao-seed-2-0-mini-260215';
  5948. }
  5949. }
  5950. // 验证模型是否在可用模型表中
  5951. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5952. $model = 'doubao-seed-2-0-mini-260215';
  5953. }
  5954. $is_multi = getProp($anime, 'is_multi', 1);
  5955. $is_single = (int)$is_multi !== 1;
  5956. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  5957. if ($is_single) {
  5958. $episode_exists = DB::table('mp_anime_episodes')
  5959. ->where('anime_id', $anime_id)
  5960. ->where('sequence', 1)
  5961. ->exists();
  5962. if ($episode_exists) {
  5963. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  5964. }
  5965. }
  5966. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  5967. if ($prompt) {
  5968. $question .= "本次修改要求如下:\n{$prompt}";
  5969. }
  5970. // 提取文件内容
  5971. if ($file) {
  5972. $content = $this->extractFileContent($file);
  5973. if (!$content) {
  5974. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5975. }
  5976. } elseif ($script_id) {
  5977. $content = $this->getContentByScriptId($script_id);
  5978. if (!$content) {
  5979. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5980. }
  5981. } elseif ($bid) {
  5982. $content = $this->getContentByBid($bid);
  5983. if (!$content) {
  5984. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5985. }
  5986. } elseif ($content) {
  5987. $content = filterContent($content);
  5988. }else {
  5989. $content = filterContent(getProp($anime, 'content'));
  5990. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5991. $need_generate_content = true;
  5992. }
  5993. }
  5994. // 判断是否需要生成原文内容
  5995. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5996. // 如果需要生成原文内容,添加额外的要求
  5997. $content_generation_requirement = $need_generate_content
  5998. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5999. : "";
  6000. // 美术风格
  6001. $input_art_style = getProp($data, 'art_style');
  6002. if (!$input_art_style) {
  6003. $mappedArtStyle = getProp($anime, 'art_style');
  6004. }else {
  6005. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6006. }
  6007. if (!$mappedArtStyle) {
  6008. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6009. }else {
  6010. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6011. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6012. }else {
  6013. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6014. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6015. }
  6016. }
  6017. // 构建主体和场景提示词
  6018. $extra_role_prompt = "\n";
  6019. $extra_scene_prompt = "\n";
  6020. $ref_products = []; // 参考资产
  6021. if ($extra_products) {
  6022. foreach($extra_products as $item) {
  6023. $product = getProp($item, 'product');
  6024. $product_name = getProp($item, 'product_name');
  6025. if ($product_name == '旁白') continue;
  6026. $ref_products[$product_name] = $item;
  6027. $pic_prompt = getProp($item, 'pic_prompt');
  6028. if ((int)$product === 1) {
  6029. // 拼接角色信息
  6030. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6031. } elseif ((int)$product === 2) {
  6032. // 拼接场景信息
  6033. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6034. }
  6035. }
  6036. // 优化提示词,融入剧本
  6037. if (!empty(trim($extra_role_prompt))) {
  6038. $extra_role_prompt = "\n2.5【强制主体设定-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6039. }
  6040. if (!empty(trim($extra_scene_prompt))) {
  6041. $extra_scene_prompt = "\n3.4【强制场景设定-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6042. }
  6043. }
  6044. $system_message = ['role'=>'system', 'content'=>$is_single
  6045. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6046. 强制要求:
  6047. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6048. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6049. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6050. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6051. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6052. 普通要求:
  6053. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6054. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6055. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6056. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6057. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6058. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6059. {$extra_role_prompt}
  6060. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6061. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6062. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6063. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6064. {$extra_scene_prompt}
  6065. 3.$mappedArtStyle_prompt\n\n
  6066. 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6067. 4.1片段分割逻辑(优先级从高到低):
  6068. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6069. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6070. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6071. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6072. 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6073. - 片段数量格式为: 片段数量:8
  6074. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6075. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6076. 4.3分镜结构:每个分镜包含以下字段:
  6077. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  6078. - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  6079. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6080. - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  6081. - 运镜:场景+画面描述+运镜
  6082. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  6083. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6084. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6085. 示例如下:\n
  6086. ###剧本名:西昆仑
  6087. ###故事梗概
  6088. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6089. ###剧本亮点
  6090. 亮点1:绝境奇药,生死一线
  6091. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6092. 亮点2:结拜兄妹,化解尴尬
  6093. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6094. 亮点3:纤发夺命,情愫暗涌
  6095. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6096. ###人物关系
  6097. 阿雪与梁萧之间存在兄妹之情。
  6098. ###核心矛盾
  6099. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6100. ###主体列表
  6101. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6102. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6103. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6104. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6105. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6106. 全景,正面拍摄,青年女性,亚洲人。
  6107. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6108. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6109. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6110. ###美术风格
  6111. 基础画风风格词:厚涂古风
  6112. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6113. ###场景列表
  6114. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6115. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6116. 无人物。}
  6117. ###分段剧本
  6118. 片段数量:8
  6119. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6120. ##片段1
  6121. 时长:12s
  6122. 分镜1
  6123. 场景:边境小镇街道
  6124. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6125. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6126. 配音台词:
  6127. 背景音效:
  6128. 分镜2
  6129. 场景:悦来酒馆
  6130. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6131. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6132. 配音台词:
  6133. 背景音效:
  6134. 分镜3
  6135. 场景:悦来酒馆
  6136. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6137. 运镜:从中景推向令牌特写。
  6138. 配音台词:
  6139. 背景音效:
  6140. 分镜4
  6141. 场景:悦来酒馆
  6142. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6143. 运镜:极速推向酒水溅起的瞬间。
  6144. 配音台词:
  6145. 背景音效:
  6146. 分镜5
  6147. 镜头描述
  6148. 场景:悦来酒馆
  6149. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6150. 运镜:固定机位,利用倾斜构图制造压迫感。
  6151. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6152. 背景音效:
  6153. \n\n"
  6154. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6155. 强制要求:\n
  6156. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6157. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6158. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6159. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6160. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6161. 普通要求:\n
  6162. 1.剧本名(必须生成)必须与文档内容高度相关
  6163. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6164. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6165. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6166. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6167. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6168. {$extra_role_prompt}
  6169. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6170. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6171. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6172. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6173. {$extra_scene_prompt}
  6174. 4.$mappedArtStyle_prompt\n\n
  6175. 示例如下:\n
  6176. ###剧本名:西昆仑
  6177. ###故事梗概
  6178. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6179. ###剧本亮点
  6180. 亮点1:绝境奇药,生死一线
  6181. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6182. 亮点2:结拜兄妹,化解尴尬
  6183. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6184. 亮点3:纤发夺命,情愫暗涌
  6185. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6186. ###人物关系
  6187. 阿雪与梁萧之间存在兄妹之情。
  6188. ###核心矛盾
  6189. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6190. ###主体列表
  6191. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6192. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6193. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6194. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6195. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6196. 全景,正面拍摄,青年女性,亚洲人。
  6197. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6198. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6199. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6200. ###美术风格
  6201. 基础画风风格词:厚涂古风
  6202. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6203. ###场景列表
  6204. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6205. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6206. 无人物。}"];
  6207. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6208. $episode_count = $this->extractEpisodeNumber($prompt);
  6209. if ((int)getProp($anime, 'is_multi') !== 1) {
  6210. yield [
  6211. 'type' => 'done',
  6212. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6213. 'reasoning' => '',
  6214. 'usage' => []
  6215. ];
  6216. return;
  6217. }
  6218. if ($episode_count) {
  6219. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6220. $system_message = [
  6221. 'role' => 'system',
  6222. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6223. 强制要求:\n
  6224. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6225. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6226. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6227. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6228. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6229. 普通要求:\n
  6230. 1.<故事梗概>控制在200-300字左右
  6231. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6232. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6233. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6234. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6235. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6236. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6237. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6238. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6239. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6240. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6241. 示例如下:\n
  6242. ###剧本名:西昆仑
  6243. ###故事梗概
  6244. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6245. ###剧本亮点
  6246. 亮点1:绝境奇药,生死一线
  6247. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6248. 亮点2:结拜兄妹,化解尴尬
  6249. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6250. 亮点3:纤发夺命,情愫暗涌
  6251. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6252. ###人物关系
  6253. 阿雪与梁萧之间存在兄妹之情。
  6254. ###核心矛盾
  6255. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6256. ###主体列表
  6257. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6258. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6259. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6260. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6261. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6262. 全景,正面拍摄,青年女性,亚洲人。
  6263. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6264. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6265. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6266. ###美术风格
  6267. 基础画风风格词:厚涂古风
  6268. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6269. ###场景列表
  6270. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6271. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6272. 无人物。}
  6273. ###分集详细内容
  6274. ##第1章 重生
  6275. 我重生了。
  6276. 源于一个男人偏执的暗恋。
  6277. ##第2章 相救
  6278. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6279. 我眼睛扫向站在锅炉后的卞大伟。"
  6280. ];
  6281. // 构建消息
  6282. $messages = [
  6283. $system_message,
  6284. [
  6285. 'role' => 'user',
  6286. 'content' => "以下是文档内容:
  6287. {$content}
  6288. 用户问题:
  6289. {$question}"
  6290. ]
  6291. ];
  6292. }else {
  6293. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6294. // 构建消息
  6295. $messages = [
  6296. $system_message,
  6297. [
  6298. 'role' => 'user',
  6299. 'content' => "以下是文档内容:
  6300. {$content}
  6301. 用户问题:
  6302. {$question}"
  6303. ]
  6304. ];
  6305. }else {
  6306. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6307. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6308. return (array)$value;
  6309. })->toArray();
  6310. array_unshift($messages, $system_message);
  6311. $messages[] = [
  6312. 'role' => 'user',
  6313. 'content' => $prompt
  6314. ];
  6315. }
  6316. }
  6317. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6318. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6319. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6320. if ($model === 'deepseek-chat') {
  6321. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6322. $model = 'deepseek-v4-flash';
  6323. $thinkingMode = 'disabled';
  6324. } elseif ($model === 'deepseek-reasoner') {
  6325. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6326. $model = 'deepseek-v4-flash';
  6327. $thinkingMode = 'enabled';
  6328. }
  6329. $post_data = [
  6330. 'model' => $model,
  6331. 'messages' => $messages,
  6332. // 'max_tokens' => 8192,
  6333. 'temperature' => 0.7,
  6334. 'frequency_penalty' => 0,
  6335. 'presence_penalty' => 0,
  6336. 'response_format' => ['type' => 'text'],
  6337. 'thinking' => ['type' => $thinkingMode],
  6338. 'stream' => true // 启用流式输出
  6339. ];
  6340. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6341. // 根据模型类型选择调用方法
  6342. $fullContent = '';
  6343. $fullReasoningContent = '';
  6344. $usage = [];
  6345. // dd($post_data);
  6346. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6347. try {
  6348. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6349. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6350. } else if (in_array($model, $this->gpt_text_models)) {
  6351. // GPT-5.4 模型使用 TokenRouter API
  6352. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6353. } else {
  6354. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6355. }
  6356. // 验证返回值类型
  6357. if (!is_iterable($streamGenerator)) {
  6358. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6359. dLog('deepseek')->error('方法名流式生成器无效', [
  6360. 'generator_type' => $errorType,
  6361. 'model' => $model,
  6362. // 添加其他上下文信息
  6363. ]);
  6364. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6365. 'type' => $errorType,
  6366. 'model' => $model
  6367. ]);
  6368. yield [
  6369. 'type' => 'error',
  6370. // 根据方法返回相应的空数据结构
  6371. 'answer' => '',
  6372. 'reasoning' => '',
  6373. 'usage' => [],
  6374. 'error' => '接口返回数据异常,请重新请求'
  6375. ];
  6376. return;
  6377. }
  6378. // 处理流式输出
  6379. foreach ($streamGenerator as $chunk) {
  6380. if (isset($chunk['type'])) {
  6381. if ($chunk['type'] === 'done') {
  6382. $fullContent = $chunk['full_content'];
  6383. $fullReasoningContent = $chunk['full_reasoning'];
  6384. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6385. } else {
  6386. yield $chunk;
  6387. }
  6388. }
  6389. }
  6390. } catch (\Exception $e) {
  6391. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6392. 'model' => $model,
  6393. 'trace' => $e->getTraceAsString()
  6394. ]);
  6395. logDB('deepseek', 'error', '方法名流式处理失败', [
  6396. 'error' => $e->getMessage(),
  6397. 'model' => $model
  6398. ]);
  6399. yield [
  6400. 'type' => 'error',
  6401. // 根据方法返回相应的空数据结构
  6402. 'answer' => '',
  6403. 'reasoning' => '',
  6404. 'usage' => [],
  6405. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6406. ];
  6407. return;
  6408. }
  6409. dLog('deepseek')->info('完整内容: '.$fullContent);
  6410. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6411. // 处理完整内容并返回最终结果
  6412. $script_arr = [];
  6413. if ($fullContent) {
  6414. $script_arr = handleScriptContentForAce($fullContent);
  6415. dLog('deepseek')->info('解析内容', $script_arr);
  6416. logDB('deepseek', 'info', '解析内容', $script_arr);
  6417. }
  6418. if (empty($script_arr['roles'])) {
  6419. // 未生成剧本相关内容,保存对话记录并返回提示
  6420. dLog('deepseek')->info('未生成剧本相关的内容');
  6421. try {
  6422. $now = date('Y-m-d H:i:s');
  6423. // 保存对话记录
  6424. $records = [
  6425. [
  6426. 'uid' => $uid,
  6427. 'anime_id' => $anime_id,
  6428. 'sequence' => 0,
  6429. 'role' => 'user',
  6430. 'content' => $prompt,
  6431. 'created_at' => $now,
  6432. 'updated_at' => $now
  6433. ],
  6434. [
  6435. 'uid' => $uid,
  6436. 'anime_id' => $anime_id,
  6437. 'sequence' => 0,
  6438. 'role' => 'assistant',
  6439. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6440. 'created_at' => $now,
  6441. 'updated_at' => $now
  6442. ]
  6443. ];
  6444. DB::table('mp_anime_records')->insert($records);
  6445. } catch (\Exception $e) {
  6446. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6447. }
  6448. yield [
  6449. 'type' => 'done',
  6450. 'script' => [],
  6451. 'episode' => [],
  6452. 'answer' => $fullContent,
  6453. 'reasoning' => $fullReasoningContent,
  6454. 'usage' => $usage,
  6455. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6456. ];
  6457. return;
  6458. }
  6459. // 替换美术风格
  6460. if ($mappedArtStyle !== '') {
  6461. $script_arr['art_style'] = $mappedArtStyle;
  6462. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6463. }
  6464. if ($user_anime_name != '新剧本策划') {
  6465. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  6466. // 确认对话名称唯一性
  6467. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6468. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6469. }
  6470. }else {
  6471. $anime_name = $user_anime_name;
  6472. }
  6473. $table_data = [
  6474. 'user_id' => $uid,
  6475. 'model' => $model,
  6476. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6477. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6478. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6479. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6480. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6481. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6482. 'art_style_type' => $input_art_style,
  6483. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6484. 'status' => '解析完成',
  6485. 'generate_status' => '待执行',
  6486. 'updated_at' => date('Y-m-d H:i:s')
  6487. ];
  6488. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6489. // 如果是修改集数,则将content内容更新(会改变原文)
  6490. if (isset($episode_count) && $episode_count > 0) {
  6491. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6492. $table_data['start_episode_sequence'] = 1;
  6493. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6494. }else {
  6495. // 如果需要生成原文内容,从script_arr中提取
  6496. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6497. $table_data['content'] = $script_arr['content'];
  6498. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6499. if (!$table_data['content']) {
  6500. yield [
  6501. 'type' => 'done',
  6502. 'script' => [],
  6503. 'episode' => [],
  6504. 'answer' => $fullContent,
  6505. 'reasoning' => $fullReasoningContent,
  6506. 'usage' => $usage,
  6507. 'error' => '未生成剧本内容,请调整提示词再试'
  6508. ];
  6509. return;
  6510. }
  6511. }
  6512. if (isset($table_data['content']) && $table_data['content']) {
  6513. $chapters = $this->splitContent($table_data['content']);
  6514. $chapter_count = count($chapters);
  6515. if ($chapter_count > 0) {
  6516. $table_data['start_episode_sequence'] = 1;
  6517. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6518. }
  6519. }
  6520. }
  6521. if ($extra_products) {
  6522. $table_data['extra_products'] = json_encode($extra_products, 256);
  6523. }
  6524. $single_episode = [];
  6525. try {
  6526. DB::beginTransaction();
  6527. $now = date('Y-m-d H:i:s');
  6528. // 更新动漫大纲
  6529. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6530. if (!$boolen) {
  6531. dLog('deepseek')->info('对话修改失败', $table_data);
  6532. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6533. Utils::throwError('20003:对话修改失败');
  6534. }
  6535. // 保存对话记录
  6536. $records = [
  6537. [
  6538. 'uid' => $uid,
  6539. 'anime_id' => $anime_id,
  6540. 'sequence' => 0,
  6541. 'role' => 'user',
  6542. 'content' => $prompt,
  6543. 'created_at' => $now,
  6544. 'updated_at' => $now
  6545. ],
  6546. [
  6547. 'uid' => $uid,
  6548. 'anime_id' => $anime_id,
  6549. 'sequence' => 0,
  6550. 'role' => 'assistant',
  6551. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6552. 'content' => $fullContent,
  6553. 'created_at' => $now,
  6554. 'updated_at' => $now
  6555. ]
  6556. ];
  6557. // 保存对话记录
  6558. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6559. if (!$boolen3) {
  6560. Utils::throwError('20003:对话记录保存失败');
  6561. }
  6562. // 单剧集模式:生成并保存剧集信息
  6563. if ($is_single) {
  6564. $anime_name = getProp($anime, 'anime_name', '未命名');
  6565. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6566. if (empty($episode_arr['acts'])) {
  6567. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6568. }
  6569. $saveResult = $this->saveEpisodeVersionData(
  6570. $anime_id,
  6571. 1,
  6572. $episode_arr,
  6573. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6574. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6575. null,
  6576. null,
  6577. false,
  6578. $content,
  6579. $now,
  6580. $ref_products
  6581. );
  6582. $single_episode = $saveResult['episode'];
  6583. $episode_id = $saveResult['episode_id'];
  6584. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6585. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6586. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6587. 'updated_at' => $now
  6588. ]);
  6589. if ($boolen5 === false) {
  6590. Utils::throwError('20003:单剧集主表资源同步失败');
  6591. }
  6592. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6593. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6594. $episode_record_content = '确认分镜大纲';
  6595. if ($content !== '') {
  6596. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6597. }
  6598. $episode_records = [
  6599. [
  6600. 'uid' => $uid,
  6601. 'anime_id' => $anime_id,
  6602. 'role' => 'user',
  6603. 'content' => $episode_record_content,
  6604. 'sequence' => 1,
  6605. 'episode_id' => $episode_id,
  6606. 'created_at' => $now,
  6607. 'updated_at' => $now
  6608. ],
  6609. [
  6610. 'uid' => $uid,
  6611. 'anime_id' => $anime_id,
  6612. 'role' => 'assistant',
  6613. 'content' => $fullContent,
  6614. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6615. 'sequence' => 1,
  6616. 'episode_id' => $episode_id,
  6617. 'created_at' => $now,
  6618. 'updated_at' => $now
  6619. ]
  6620. ];
  6621. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6622. if (!$boolen4) {
  6623. Utils::throwError('20003:单剧集分镜记录保存失败');
  6624. }
  6625. }
  6626. }catch (\Exception $e) {
  6627. DB::rollBack();
  6628. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  6629. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  6630. yield [
  6631. 'type' => 'done',
  6632. 'answer' => $fullContent,
  6633. 'reasoning' => $fullReasoningContent,
  6634. 'usage' => $usage,
  6635. 'error' => $e->getMessage(),
  6636. ];
  6637. return;
  6638. }
  6639. DB::commit();
  6640. dLog('deepseek')->info('保存完毕');
  6641. if ($is_single && !empty($single_episode)) {
  6642. // $this->batchSetGlobalRoleImg([
  6643. // 'anime_id' => $anime_id,
  6644. // ]);
  6645. // $this->batchSetGlobalSceneImg([
  6646. // 'anime_id' => $anime_id,
  6647. // ]);
  6648. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6649. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6650. }
  6651. $table_data['anime_id'] = $anime_id;
  6652. $table_data['roles'] = json_decode($table_data['roles'], true);
  6653. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6654. unset($table_data['updated_at']);
  6655. unset($table_data['status']);
  6656. yield [
  6657. 'type' => 'done',
  6658. 'script' => $table_data,
  6659. 'episode' => $single_episode,
  6660. 'answer' => $fullContent,
  6661. 'reasoning' => $fullReasoningContent,
  6662. 'usage' => $usage
  6663. ];
  6664. }
  6665. public function chatForAce($data) {
  6666. $uid = Site::getUid();
  6667. $anime_id = getProp($data, 'anime_id');
  6668. $file = getProp($data, 'file');
  6669. $content = getProp($data, 'content', '');
  6670. $bid = getProp($data, 'bid', 0);
  6671. $script_id = getProp($data, 'script_id', 0);
  6672. $episode_number = getProp($data, 'episode_number', 1);
  6673. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6674. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6675. if (!$anime) Utils::throwError('20003:该对话不存在!');
  6676. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  6677. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  6678. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  6679. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  6680. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  6681. $roles = is_array($roles) ? $roles : [];
  6682. $scenes = is_array($scenes) ? $scenes : [];
  6683. $extra_products = getProp($data, 'products', []);
  6684. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6685. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6686. $anime_script_id = getProp($anime, 'script_id');
  6687. if ($anime_script_id) {
  6688. $cpid = Site::getCpid();
  6689. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6690. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6691. ->where('mapping.script_id', $anime_script_id)
  6692. ->where('product.cpid', $cpid)
  6693. ->where('product.is_deleted', 0);
  6694. // 如果提供了 episode_number,则过滤指定集数
  6695. if ($episode_number !== null && $episode_number !== '') {
  6696. $script_products_mappings->where('mapping.episode_number', $episode_number);
  6697. }
  6698. $mappings = $script_products_mappings->select(
  6699. 'mapping.product_id',
  6700. 'mapping.episode_number',
  6701. 'product.product_name',
  6702. 'product.type',
  6703. 'product.product',
  6704. 'product.pic_prompt',
  6705. 'product.url',
  6706. 'product.pic_task_id',
  6707. 'product.pic_task_status',
  6708. 'product.three_view_image_url'
  6709. )
  6710. ->get();
  6711. // 按 product_id 分组,合并 episode_number
  6712. $productMap = [];
  6713. foreach ($mappings as $item) {
  6714. $product_id = $item->product_id;
  6715. $product_name = $item->product_name;
  6716. // 处理product_name两边的符号
  6717. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6718. if (!isset($productMap[$product_id])) {
  6719. $productMap[$product_id] = [
  6720. 'product_id' => $product_id,
  6721. 'product_name' => $product_name,
  6722. 'type' => (int)$item->type,
  6723. 'product' => (int)$item->product,
  6724. 'pic_prompt' => $item->pic_prompt,
  6725. 'url' => $item->url,
  6726. 'pic_task_id' => $item->pic_task_id,
  6727. 'pic_task_status' => $item->pic_task_status,
  6728. 'episode_numbers' => [],
  6729. ];
  6730. }
  6731. // 添加 episode_number(去重)
  6732. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6733. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6734. }
  6735. }
  6736. // 将查询到的剧本资产合并到extra_products中
  6737. // 先构建extra_products的索引(以product_id+episode_number为key)
  6738. $extraProductsMap = [];
  6739. foreach ($extra_products as $item) {
  6740. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  6741. $extraProductsMap[$key] = $item;
  6742. }
  6743. // 合并剧本资产(去重:product_id+episode_number)
  6744. foreach ($productMap as $product) {
  6745. foreach ($product['episode_numbers'] as $ep_num) {
  6746. $key = $product['product_id'] . '_' . $ep_num;
  6747. // 如果不存在则添加
  6748. if (!isset($extraProductsMap[$key])) {
  6749. $extraProductsMap[$key] = [
  6750. 'product_id' => $product['product_id'],
  6751. 'product_name' => $product['product_name'],
  6752. 'type' => $product['type'],
  6753. 'product' => $product['product'],
  6754. 'pic_prompt' => $product['pic_prompt'],
  6755. 'url' => $product['url'],
  6756. 'pic_task_id' => $product['pic_task_id'],
  6757. 'pic_task_status' => $product['pic_task_status'],
  6758. 'episode_number' => $ep_num,
  6759. ];
  6760. }
  6761. }
  6762. }
  6763. // 重新赋值给extra_products
  6764. $extra_products = array_values($extraProductsMap);
  6765. }
  6766. // 处理提示词
  6767. if ($prompt && $extra_products) {
  6768. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6769. foreach($extra_products as $item) {
  6770. $product_name = getProp($item, 'product_name');
  6771. if ($product_name) {
  6772. // 替换 {product_name} 为 product_name
  6773. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6774. }
  6775. }
  6776. }
  6777. // 获取最后一集序号
  6778. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  6779. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  6780. // 转换主体列表和场景列表的格式
  6781. // 获取参考主体或场景
  6782. if ((int)$episode_number === 1) {
  6783. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  6784. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  6785. }else {
  6786. $prev_episode_number = $episode_number - 1;
  6787. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  6788. }
  6789. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  6790. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  6791. // 合并anime_products和extra_products(extra_products优先,去重)
  6792. $anime_products = getProp($anime, 'extra_products');
  6793. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  6794. $ref_products = [];
  6795. foreach($anime_products as $item) {
  6796. $product_name = getProp($item, 'product_name');
  6797. $ref_products[$product_name] = $item;
  6798. }
  6799. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  6800. $extra_roles = []; // 从extra_products中提取的角色
  6801. $extra_scenes = []; // 从extra_products中提取的场景
  6802. if ($extra_products && is_array($extra_products)) {
  6803. foreach($extra_products as $item) {
  6804. $product = (int)getProp($item, 'product');
  6805. $product_name = getProp($item, 'product_name');
  6806. if ($product_name == '旁白') continue;
  6807. $pic_prompt = getProp($item, 'pic_prompt');
  6808. $ref_products[$product_name] = $item;
  6809. if ($product === 1) {
  6810. // 角色
  6811. $extra_roles[$product_name] = [
  6812. 'role' => $product_name,
  6813. 'pic_prompt' => $pic_prompt,
  6814. 'url' => getProp($item, 'url', ''),
  6815. ];
  6816. } elseif ($product === 2) {
  6817. // 场景
  6818. $extra_scenes[$product_name] = [
  6819. 'scene' => $product_name,
  6820. 'pic_prompt' => $pic_prompt,
  6821. 'url' => getProp($item, 'url', ''),
  6822. ];
  6823. }
  6824. }
  6825. }
  6826. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  6827. $merged_roles = [];
  6828. foreach($ref_roles as $role) {
  6829. $role_name = getProp($role, 'role');
  6830. if (!isset($extra_roles[$role_name])) {
  6831. $merged_roles[$role_name] = $role;
  6832. }
  6833. }
  6834. // 添加extra_roles
  6835. foreach($extra_roles as $role_name => $role) {
  6836. $merged_roles[$role_name] = $role;
  6837. }
  6838. $ref_roles = array_values($merged_roles);
  6839. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  6840. $merged_scenes = [];
  6841. foreach($ref_scenes as $scene) {
  6842. $scene_name = getProp($scene, 'scene');
  6843. if (!isset($extra_scenes[$scene_name])) {
  6844. $merged_scenes[$scene_name] = $scene;
  6845. }
  6846. }
  6847. // 添加extra_scenes
  6848. foreach($extra_scenes as $scene_name => $scene) {
  6849. $merged_scenes[$scene_name] = $scene;
  6850. }
  6851. $ref_scenes = array_values($merged_scenes);
  6852. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  6853. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  6854. // 构建强制主体和场景提示词
  6855. $forced_roles_prompt = "";
  6856. $forced_scenes_prompt = "";
  6857. if (!empty($extra_roles)) {
  6858. $forced_roles_list = "";
  6859. foreach($extra_roles as $role_name => $role) {
  6860. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  6861. }
  6862. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6863. }
  6864. if (!empty($extra_scenes)) {
  6865. $forced_scenes_list = "";
  6866. foreach($extra_scenes as $scene_name => $scene) {
  6867. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  6868. }
  6869. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6870. }
  6871. if ($anime_script_id) {
  6872. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  6873. }else if ($roles_content) {
  6874. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  6875. 主体范围:\n {$roles_content}\n
  6876. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  6877. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6878. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6879. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6880. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  6881. }else {
  6882. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6883. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6884. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6885. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6886. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  6887. }
  6888. if ($anime_script_id) {
  6889. $scene_demo = "3.<场景列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  6890. }else if ($scenes_content) {
  6891. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  6892. 场景范围:\n {$scenes_content}\n
  6893. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  6894. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  6895. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6896. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  6897. }else {
  6898. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6899. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6900. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6901. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  6902. }
  6903. // 提取文件内容
  6904. if ($file) {
  6905. $uploaded_content = $this->extractFileContent($file);
  6906. if (!$uploaded_content) {
  6907. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6908. }
  6909. } elseif ($script_id) {
  6910. $uploaded_content = $this->getContentByScriptId($script_id);
  6911. if (!$uploaded_content) {
  6912. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6913. }
  6914. } elseif ($bid) {
  6915. $uploaded_content = $this->getContentByBid($bid);
  6916. if (!$uploaded_content) {
  6917. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6918. }
  6919. } elseif ($content) {
  6920. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  6921. }
  6922. // elseif ($prompt) {
  6923. // $uploaded_content = filterContent($prompt);
  6924. // }
  6925. else {
  6926. $uploaded_content = '';
  6927. }
  6928. // 美术风格
  6929. $input_art_style = getProp($data, 'art_style');
  6930. if (!$input_art_style) {
  6931. $mappedArtStyle = getProp($anime, 'art_style');
  6932. }else {
  6933. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6934. }
  6935. if (!$mappedArtStyle) {
  6936. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6937. }else {
  6938. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6939. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6940. }else {
  6941. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6942. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6943. }
  6944. }
  6945. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6946. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6947. // 强制要求:
  6948. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6949. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6950. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6951. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  6952. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  6953. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  6954. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  6955. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  6956. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  6957. // 10.分镜要和场景列表、人物主体保持一致\n
  6958. // 普通要求:
  6959. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6960. // {$role_demo}
  6961. // {$scene_demo}
  6962. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6963. // 4.1片段分割逻辑(优先级从高到低):
  6964. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6965. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6966. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6967. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6968. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6969. // - 片段数量格式为: 片段数量:8
  6970. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6971. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6972. // 4.3分镜结构:每个分镜包含以下字段:
  6973. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  6974. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  6975. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6976. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  6977. // - 运镜:场景+画面描述+运镜
  6978. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  6979. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6980. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  6981. // 5.$mappedArtStyle_prompt\n\n
  6982. // 示例格式:\n
  6983. // 第1集:隐形的守护者
  6984. // ###故事梗概
  6985. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6986. // ###美术风格
  6987. // 基础画风风格词:胡金铨武侠
  6988. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  6989. // ###主体列表
  6990. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6991. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  6992. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  6993. // ###场景列表
  6994. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  6995. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  6996. // ###分段剧本
  6997. // 片段数量:8
  6998. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6999. // ##片段1
  7000. // 时长:12s
  7001. // 分镜1
  7002. // 场景:边境小镇街道
  7003. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7004. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7005. // 配音台词:
  7006. // 背景音效:
  7007. // 分镜2
  7008. // 场景:悦来酒馆
  7009. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7010. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7011. // 配音台词:
  7012. // 背景音效:
  7013. // 分镜3
  7014. // 场景:悦来酒馆
  7015. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7016. // 运镜:从中景推向令牌特写。
  7017. // 配音台词:
  7018. // 背景音效:
  7019. // 分镜4
  7020. // 场景:悦来酒馆
  7021. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7022. // 运镜:极速推向酒水溅起的瞬间。
  7023. // 配音台词:
  7024. // 背景音效:
  7025. // 分镜5
  7026. // 镜头描述
  7027. // 场景:悦来酒馆
  7028. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7029. // 运镜:固定机位,利用倾斜构图制造压迫感。
  7030. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7031. // 背景音效:
  7032. // \n\n";
  7033. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7034. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7035. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  7036. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  7037. 普通要求:
  7038. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7039. {$role_demo}
  7040. {$scene_demo}
  7041. 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7042. 4.1片段分割逻辑(优先级从高到低):
  7043. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7044. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7045. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7046. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7047. 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7048. - 片段数量格式为: 片段数量:8
  7049. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7050. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7051. 4.3分镜结构:每个分镜包含以下字段:
  7052. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7053. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”后面“:”前面的任何内容,不能自创)
  7054. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7055. - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”后面“:”前面的任何内容,不能自创)
  7056. - 运镜:场景+画面描述+运镜
  7057. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”后面“:”前面的任何内容,不能自创)
  7058. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7059. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7060. 5.{$mappedArtStyle_prompt}
  7061. 6.《情绪-视听语言映射表》:
  7062. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7063. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7064. -----|---------|------------|----------------
  7065. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7066. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7067. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7068. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7069. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7070. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7071. -----|---------|------------|----------------
  7072. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7073. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7074. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7075. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7076. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7077. --------|---------|--------------|-------------
  7078. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7079. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7080. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7081. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7082. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7083. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7084. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7085. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7086. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7087. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7088. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7089. -----|---------|------------|------------
  7090. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7091. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7092. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7093. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7094. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7095. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7096. --------|---------|--------------|----------
  7097. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7098. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7099. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7100. 6.6 声音设计与潜意识影响 (Soundscape)
  7101. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7102. -----|---------|------------|------------------
  7103. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7104. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7105. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7106. 理论基石:
  7107. - The Five C's of Cinematography by Joseph V. Mascelli
  7108. - Film Art: An Introduction by David Bordwell
  7109. - Sight, Sound, Motion by Herbert Zettl
  7110. - Notes on the Cinematograph by Robert Bresson
  7111. \n\n
  7112. 示例格式:\n
  7113. 第1集:隐形的守护者
  7114. ###故事梗概
  7115. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7116. ###美术风格
  7117. 基础画风风格词:胡金铨武侠
  7118. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7119. ###主体列表
  7120. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7121. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7122. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7123. ###场景列表
  7124. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7125. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7126. ###分段剧本
  7127. 片段数量:8
  7128. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7129. ##片段1
  7130. 时长:12s
  7131. 分镜1
  7132. 场景:边境小镇街道
  7133. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7134. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7135. 配音台词:
  7136. 背景音效:
  7137. 分镜2
  7138. 场景:悦来酒馆
  7139. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7140. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7141. 配音台词:
  7142. 背景音效:
  7143. 分镜3
  7144. 场景:悦来酒馆
  7145. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7146. 运镜:从中景推向令牌特写。
  7147. 配音台词:
  7148. 背景音效:
  7149. 分镜4
  7150. 场景:悦来酒馆
  7151. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7152. 运镜:极速推向酒水溅起的瞬间。
  7153. 配音台词:
  7154. 背景音效:
  7155. 分镜5
  7156. 镜头描述
  7157. 场景:悦来酒馆
  7158. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7159. 运镜:固定机位,利用倾斜构图制造压迫感。
  7160. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7161. 背景音效:
  7162. \n\n";
  7163. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7164. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  7165. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7166. $prompt = $origin_prompt;
  7167. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7168. // 获取章节内容
  7169. $full_content = getProp($anime, 'content');
  7170. if ($uploaded_content) {
  7171. $full_content = $uploaded_content;
  7172. }
  7173. // 根据章节内容拆分章节
  7174. $chapters = $this->splitContent($full_content);
  7175. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7176. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7177. $messages = [];
  7178. if ($prompt == '确认分镜大纲') {
  7179. // 暂时保留
  7180. $content = $chapter_content;
  7181. if ($is_single) $content = $full_content; // 单剧集使用全文
  7182. if (!$content) {
  7183. Utils::throwError('20003:章节内容无法获取,请确认');
  7184. }
  7185. $question = $is_single
  7186. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7187. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7188. // 构建消息
  7189. $messages[] =
  7190. [
  7191. 'role' => 'user',
  7192. 'content' => $question
  7193. ];
  7194. }else if ($prompt == '继续策划下一集') {
  7195. if ($is_single) {
  7196. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7197. }
  7198. $content = $chapter_content;
  7199. if (!$content) {
  7200. Utils::throwError('20003:章节内容无法获取,请确认');
  7201. }
  7202. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7203. // 获取上一集最后记录
  7204. $prev_sequence = $episode_number - 1;
  7205. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7206. // 构建消息
  7207. $messages[] =
  7208. [
  7209. 'role' => 'user',
  7210. 'content' => $question
  7211. ];
  7212. // dd($messages);
  7213. }else {
  7214. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7215. if (!$content) {
  7216. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7217. }
  7218. if (!$content) {
  7219. Utils::throwError('20003:章节内容无法获取,请确认');
  7220. }
  7221. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7222. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7223. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7224. if ($origin_prompt) {
  7225. $question .= "本次修改要求如下:\n{$origin_prompt}";
  7226. }
  7227. $messages[] =
  7228. [
  7229. 'role' => 'user',
  7230. 'content' => $question
  7231. ];
  7232. }
  7233. // 处理文本模型
  7234. $model = getProp($data, 'model');
  7235. if (!$model) {
  7236. // 用户没有输入,从anime表获取
  7237. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7238. $model = getProp($anime, 'model');
  7239. if (!$model) {
  7240. // anime表也没有,使用默认值
  7241. $model = 'doubao-seed-2-0-mini-260215';
  7242. }
  7243. }
  7244. // 验证模型是否在可用模型表中
  7245. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7246. $model = 'doubao-seed-2-0-mini-260215';
  7247. }
  7248. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7249. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7250. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7251. if ($model === 'deepseek-chat') {
  7252. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7253. $model = 'deepseek-v4-flash';
  7254. $thinkingMode = 'disabled';
  7255. } elseif ($model === 'deepseek-reasoner') {
  7256. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7257. $model = 'deepseek-v4-flash';
  7258. $thinkingMode = 'enabled';
  7259. }
  7260. $post_data = [
  7261. 'model' => $model,
  7262. 'messages' => $messages,
  7263. // 'max_tokens' => 8192,
  7264. 'temperature' => 0.7,
  7265. 'frequency_penalty' => 0,
  7266. 'presence_penalty' => 0,
  7267. 'response_format' => ['type' => 'text'],
  7268. 'thinking' => ['type' => $thinkingMode],
  7269. 'stream' => true // 启用流式输出
  7270. ];
  7271. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7272. // 根据模型类型选择调用方法
  7273. $fullContent = '';
  7274. $fullReasoningContent = '';
  7275. $usage = [];
  7276. try {
  7277. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7278. // DeepSeek 官方模型使用 DeepSeek API
  7279. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7280. } else if (in_array($model, $this->gpt_text_models)) {
  7281. // GPT-5.4 模型使用 TokenRouter API
  7282. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7283. } else {
  7284. // 其他模型使用火山引擎API
  7285. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7286. }
  7287. // 验证返回值类型
  7288. if (!is_iterable($streamGenerator)) {
  7289. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7290. dLog('deepseek')->error('chat流式生成器无效', [
  7291. 'generator_type' => $errorType,
  7292. 'model' => $model,
  7293. 'anime_id' => $anime_id,
  7294. 'episode_number' => $episode_number
  7295. ]);
  7296. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7297. 'type' => $errorType,
  7298. 'model' => $model
  7299. ]);
  7300. yield [
  7301. 'type' => 'error',
  7302. 'episode' => [],
  7303. 'answer' => '',
  7304. 'reasoning' => '',
  7305. 'usage' => [],
  7306. 'error' => '接口返回数据异常,请重新请求'
  7307. ];
  7308. return;
  7309. }
  7310. // 处理流式输出
  7311. foreach ($streamGenerator as $chunk) {
  7312. if (isset($chunk['type'])) {
  7313. if ($chunk['type'] === 'done') {
  7314. // 最终结果
  7315. $fullContent = $chunk['full_content'];
  7316. $fullReasoningContent = $chunk['full_reasoning'];
  7317. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7318. } else {
  7319. // 逐块yield数据
  7320. yield $chunk;
  7321. }
  7322. }
  7323. }
  7324. } catch (\Exception $e) {
  7325. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7326. 'model' => $model,
  7327. 'anime_id' => $anime_id,
  7328. 'episode_number' => $episode_number,
  7329. 'trace' => $e->getTraceAsString()
  7330. ]);
  7331. logDB('deepseek', 'error', 'chat流式处理失败', [
  7332. 'error' => $e->getMessage(),
  7333. 'model' => $model
  7334. ]);
  7335. yield [
  7336. 'type' => 'error',
  7337. 'episode' => [],
  7338. 'answer' => '',
  7339. 'reasoning' => '',
  7340. 'usage' => [],
  7341. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7342. ];
  7343. return;
  7344. }
  7345. dLog('deepseek')->info('完整内容: '.$fullContent);
  7346. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7347. // 处理完整内容并返回最终结果
  7348. $episode_arr = handleEpisodeContentForAce($fullContent);
  7349. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7350. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  7351. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7352. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7353. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  7354. // }
  7355. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  7356. $max_retries = 3;
  7357. $retry_count = 0;
  7358. $validation_failed = false;
  7359. $validation_error_msg = '';
  7360. // 验证生成的内容
  7361. if ($anime_script_id) {
  7362. // 检查是否有acts数据
  7363. if (empty($episode_arr['acts'])) {
  7364. $validation_failed = true;
  7365. $validation_error_msg = '未生成分镜剧本相关的内容';
  7366. } else {
  7367. // 检查主体列表是否匹配 - 只验证生成的主体名是否都在预期列表中
  7368. $generated_roles = array_column($episode_arr['roles'], 'role');
  7369. // 过滤掉"旁白"角色
  7370. $generated_roles = array_filter($generated_roles, function($role) {
  7371. return $role !== '旁白';
  7372. });
  7373. $expected_roles = array_keys($extra_roles);
  7374. // 找出生成的主体中不在预期列表中的主体
  7375. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7376. if (!empty($invalid_roles)) {
  7377. $validation_failed = true;
  7378. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7379. }
  7380. // 检查场景列表是否匹配 - 只验证生成的场景名是否都在预期列表中
  7381. if (!$validation_failed) {
  7382. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7383. $expected_scenes = array_keys($extra_scenes);
  7384. // 找出生成的场景中不在预期列表中的场景
  7385. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7386. if (!empty($invalid_scenes)) {
  7387. $validation_failed = true;
  7388. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7389. }
  7390. }
  7391. }
  7392. } else {
  7393. // 如果没有anime_script_id,只检查是否有acts数据
  7394. if (empty($episode_arr['acts'])) {
  7395. $validation_failed = true;
  7396. $validation_error_msg = '未生成分镜剧本相关的内容';
  7397. }
  7398. }
  7399. // 重试逻辑
  7400. while ($validation_failed && $retry_count < $max_retries) {
  7401. $retry_count++;
  7402. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  7403. 'reason' => $validation_error_msg,
  7404. 'anime_id' => $anime_id,
  7405. 'episode_number' => $episode_number
  7406. ]);
  7407. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  7408. 'reason' => $validation_error_msg,
  7409. 'anime_id' => $anime_id
  7410. ]);
  7411. // 发送流式重试提示
  7412. yield [
  7413. 'type' => 'retry',
  7414. 'retry_count' => $retry_count,
  7415. 'reason' => $validation_error_msg
  7416. ];
  7417. // 构建重试提示词
  7418. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  7419. if ($anime_script_id) {
  7420. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  7421. $retry_prompt .= "2. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  7422. $retry_prompt .= "3. 必须包含完整的分镜剧本内容\n";
  7423. } else {
  7424. $retry_prompt .= "1. 必须包含完整的分镜剧本内容\n";
  7425. }
  7426. // 添加重试消息到messages
  7427. $messages[] = [
  7428. 'role' => 'assistant',
  7429. 'content' => $fullContent
  7430. ];
  7431. $messages[] = [
  7432. 'role' => 'user',
  7433. 'content' => $retry_prompt
  7434. ];
  7435. // 更新post_data的messages
  7436. $post_data['messages'] = $messages;
  7437. // 重新调用API
  7438. try {
  7439. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7440. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7441. } else if (in_array($model, $this->gpt_text_models)) {
  7442. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7443. } else {
  7444. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7445. }
  7446. // 处理流式输出
  7447. $fullContent = '';
  7448. $fullReasoningContent = '';
  7449. foreach ($streamGenerator as $chunk) {
  7450. if (isset($chunk['type'])) {
  7451. if ($chunk['type'] === 'done') {
  7452. $fullContent = $chunk['full_content'];
  7453. $fullReasoningContent = $chunk['full_reasoning'];
  7454. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7455. } else {
  7456. yield $chunk;
  7457. }
  7458. }
  7459. }
  7460. // 重新解析内容
  7461. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  7462. $episode_arr = handleEpisodeContentForAce($fullContent);
  7463. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  7464. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7465. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7466. // }
  7467. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  7468. // 重新验证
  7469. $validation_failed = false;
  7470. $validation_error_msg = '';
  7471. if ($anime_script_id) {
  7472. if (empty($episode_arr['acts'])) {
  7473. $validation_failed = true;
  7474. $validation_error_msg = '未生成分镜剧本相关的内容';
  7475. } else {
  7476. // 检查主体列表 - 只验证生成的主体名是否都在预期列表中
  7477. $generated_roles = array_column($episode_arr['roles'], 'role');
  7478. // 过滤掉"旁白"角色
  7479. $generated_roles = array_filter($generated_roles, function($role) {
  7480. return $role !== '旁白';
  7481. });
  7482. $expected_roles = array_keys($extra_roles);
  7483. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7484. if (!empty($invalid_roles)) {
  7485. $validation_failed = true;
  7486. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7487. }
  7488. // 检查场景列表 - 只验证生成的场景名是否都在预期列表中
  7489. if (!$validation_failed) {
  7490. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7491. $expected_scenes = array_keys($extra_scenes);
  7492. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7493. if (!empty($invalid_scenes)) {
  7494. $validation_failed = true;
  7495. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7496. }
  7497. }
  7498. }
  7499. } else {
  7500. if (empty($episode_arr['acts'])) {
  7501. $validation_failed = true;
  7502. $validation_error_msg = '未生成分镜剧本相关的内容';
  7503. }
  7504. }
  7505. } catch (\Exception $e) {
  7506. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  7507. 'trace' => $e->getTraceAsString()
  7508. ]);
  7509. break;
  7510. }
  7511. }
  7512. // 如果重试后仍然失败
  7513. if ($validation_failed) {
  7514. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  7515. 'retry_count' => $retry_count,
  7516. 'last_error' => $validation_error_msg
  7517. ]);
  7518. try {
  7519. $now = date('Y-m-d H:i:s');
  7520. $records = [
  7521. [
  7522. 'uid' => $uid,
  7523. 'anime_id' => $anime_id,
  7524. 'sequence' => $episode_number,
  7525. 'role' => 'user',
  7526. 'content' => $prompt,
  7527. 'created_at' => $now,
  7528. 'updated_at' => $now
  7529. ],
  7530. [
  7531. 'uid' => $uid,
  7532. 'anime_id' => $anime_id,
  7533. 'sequence' => $episode_number,
  7534. 'role' => 'assistant',
  7535. 'content' => $fullContent,
  7536. 'created_at' => $now,
  7537. 'updated_at' => $now
  7538. ]
  7539. ];
  7540. DB::table('mp_anime_records')->insert($records);
  7541. } catch (\Exception $e) {
  7542. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7543. }
  7544. yield [
  7545. 'type' => 'done',
  7546. 'episode' => [],
  7547. 'answer' => $fullContent,
  7548. 'reasoning' => $fullReasoningContent,
  7549. 'usage' => $usage,
  7550. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  7551. ];
  7552. return;
  7553. }
  7554. // 验证成功,记录日志
  7555. if ($retry_count > 0) {
  7556. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  7557. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  7558. }
  7559. // 老逻辑
  7560. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  7561. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  7562. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  7563. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  7564. $now = date('Y-m-d H:i:s');
  7565. try {
  7566. DB::beginTransaction();
  7567. $saveResult = $this->saveEpisodeVersionData(
  7568. $anime_id,
  7569. $episode_number,
  7570. $episode_arr,
  7571. $existing_roles,
  7572. $existing_scenes,
  7573. $current_episode,
  7574. $base_episode,
  7575. $is_regenerate_version,
  7576. $content,
  7577. $now,
  7578. $ref_products
  7579. );
  7580. $episode = $saveResult['episode'];
  7581. $episode_id = $saveResult['episode_id'];
  7582. $merged_roles = $saveResult['merged_roles'];
  7583. $merged_scenes = $saveResult['merged_scenes'];
  7584. $record_content = $origin_prompt;
  7585. if ($uploaded_content !== '') {
  7586. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  7587. }
  7588. $records = [
  7589. [
  7590. 'uid' => $uid,
  7591. 'anime_id' => $anime_id,
  7592. 'role' => 'user',
  7593. 'content' => $record_content,
  7594. 'sequence' => $episode_number,
  7595. 'episode_id' => $episode_id,
  7596. 'created_at' => $now,
  7597. 'updated_at' => $now
  7598. ],
  7599. [
  7600. 'uid' => $uid,
  7601. 'anime_id' => $anime_id,
  7602. 'role' => 'assistant',
  7603. 'content' => $fullContent,
  7604. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7605. 'sequence' => $episode_number,
  7606. 'episode_id' => $episode_id,
  7607. 'created_at' => $now,
  7608. 'updated_at' => $now
  7609. ]
  7610. ];
  7611. $boolen4 = DB::table('mp_anime_records')->insert($records);
  7612. if (!$boolen4) {
  7613. Utils::throwError('20003:对话记录保存失败');
  7614. }
  7615. // 保存模型到anime表
  7616. $update_anime_data = [
  7617. 'model' => $model,
  7618. 'updated_at' => $now
  7619. ];
  7620. if ($uploaded_content) {
  7621. $update_anime_data['content'] = $uploaded_content;
  7622. }
  7623. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  7624. }catch (\Exception $e) {
  7625. DB::rollBack();
  7626. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7627. yield [
  7628. 'type' => 'done',
  7629. 'answer' => $fullContent,
  7630. 'reasoning' => $fullReasoningContent,
  7631. 'usage' => $usage,
  7632. 'error' => $e->getMessage(),
  7633. ];
  7634. return;
  7635. }
  7636. DB::commit();
  7637. if ($is_global_generate_pics) {
  7638. // // 批量生成全局角色图片
  7639. // $this->batchSetGlobalRoleImg([
  7640. // 'anime_id' => $anime_id,
  7641. // ], true);
  7642. // // 批量生成全局场景图片
  7643. // $this->batchSetGlobalSceneImg([
  7644. // 'anime_id' => $anime_id,
  7645. // ], true);
  7646. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7647. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7648. }
  7649. $episode['episode_id'] = $episode_id;
  7650. $episode['roles'] = $merged_roles;
  7651. $episode['scenes'] = $merged_scenes;
  7652. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  7653. yield [
  7654. 'type' => 'done',
  7655. 'episode' => $episode,
  7656. 'answer' => $fullContent,
  7657. 'reasoning' => $fullReasoningContent,
  7658. 'usage' => $usage
  7659. ];
  7660. }
  7661. /**
  7662. * 智能匹配并替换主体和场景名称
  7663. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  7664. *
  7665. * @param array $episode_arr 解析后的剧集数据
  7666. * @param array $extra_roles 强制主体设定(key为主体名称)
  7667. * @param array $extra_scenes 强制场景设定(key为场景名称)
  7668. * @return array 替换后的剧集数据
  7669. */
  7670. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  7671. $replaced_count = 0;
  7672. // 1. 处理主体列表
  7673. if (!empty($episode_arr['roles'])) {
  7674. foreach ($episode_arr['roles'] as &$role) {
  7675. $generated_role_name = $role['role'] ?? '';
  7676. // 跳过旁白
  7677. if ($generated_role_name === '旁白') {
  7678. continue;
  7679. }
  7680. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  7681. if (!isset($extra_roles[$generated_role_name])) {
  7682. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  7683. if ($matched_role) {
  7684. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  7685. $role['role'] = $matched_role;
  7686. $replaced_count++;
  7687. }
  7688. }
  7689. }
  7690. }
  7691. // 2. 处理场景列表
  7692. if (!empty($episode_arr['scenes'])) {
  7693. foreach ($episode_arr['scenes'] as &$scene) {
  7694. $generated_scene_name = $scene['scene'] ?? '';
  7695. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  7696. if (!isset($extra_scenes[$generated_scene_name])) {
  7697. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  7698. if ($matched_scene) {
  7699. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  7700. $scene['scene'] = $matched_scene;
  7701. $replaced_count++;
  7702. }
  7703. }
  7704. }
  7705. }
  7706. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  7707. if (!empty($episode_arr['acts'])) {
  7708. foreach ($episode_arr['acts'] as &$act) {
  7709. if (!empty($act['segments'])) {
  7710. foreach ($act['segments'] as &$segment) {
  7711. if (!empty($segment['segment_content'])) {
  7712. $original_content = $segment['segment_content'];
  7713. $replaced_content = $original_content;
  7714. // 替换场景名 - 在文本中查找并替换
  7715. foreach (array_keys($extra_scenes) as $full_scene_name) {
  7716. // 尝试找到可能的短名称
  7717. $potential_short_names = [];
  7718. // 提取场景名的主要部分(冒号之前)
  7719. if (mb_strpos($full_scene_name, ':') !== false) {
  7720. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  7721. $potential_short_names[] = $short_name;
  7722. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  7723. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  7724. $potential_short_names[] = $short_name;
  7725. }
  7726. // 替换场景字段中的短名称
  7727. foreach ($potential_short_names as $short_name) {
  7728. if ($short_name !== $full_scene_name) {
  7729. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  7730. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  7731. if ($new_content !== $replaced_content) {
  7732. $replaced_content = $new_content;
  7733. $replaced_count++;
  7734. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  7735. }
  7736. }
  7737. }
  7738. }
  7739. // 替换配音角色名(跳过旁白)
  7740. foreach (array_keys($extra_roles) as $full_role_name) {
  7741. if ($full_role_name === '旁白') {
  7742. continue;
  7743. }
  7744. // 尝试找到可能的短名称
  7745. $potential_short_names = [];
  7746. // 提取角色名的主要部分(短横线之前)
  7747. if (mb_strpos($full_role_name, '-') !== false) {
  7748. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  7749. $potential_short_names[] = $short_name;
  7750. }
  7751. // 替换配音台词中的短名称
  7752. foreach ($potential_short_names as $short_name) {
  7753. if ($short_name !== $full_role_name) {
  7754. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  7755. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  7756. if ($new_content !== $replaced_content) {
  7757. $replaced_content = $new_content;
  7758. $replaced_count++;
  7759. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  7760. }
  7761. }
  7762. }
  7763. }
  7764. // 如果有替换,更新segment_content
  7765. if ($replaced_content !== $original_content) {
  7766. $segment['segment_content'] = $replaced_content;
  7767. }
  7768. }
  7769. }
  7770. }
  7771. }
  7772. }
  7773. if ($replaced_count > 0) {
  7774. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  7775. 'replaced_count' => $replaced_count
  7776. ]);
  7777. }
  7778. return $episode_arr;
  7779. }
  7780. /**
  7781. * 查找匹配的名称
  7782. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  7783. *
  7784. * @param string $generated_name 生成的名称
  7785. * @param array $expected_names 预期的名称列表
  7786. * @return string|null 匹配到的名称,如果没有匹配则返回null
  7787. */
  7788. private function findMatchingName($generated_name, $expected_names) {
  7789. if (empty($generated_name)) {
  7790. return null;
  7791. }
  7792. // 尝试精确匹配
  7793. if (in_array($generated_name, $expected_names)) {
  7794. return $generated_name;
  7795. }
  7796. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  7797. foreach ($expected_names as $expected_name) {
  7798. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  7799. if (mb_strpos($expected_name, $generated_name) === 0) {
  7800. return $expected_name;
  7801. }
  7802. }
  7803. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  7804. // 这样可以处理一些变体,但优先级较低
  7805. foreach ($expected_names as $expected_name) {
  7806. if (mb_strpos($expected_name, $generated_name) !== false) {
  7807. return $expected_name;
  7808. }
  7809. }
  7810. return null;
  7811. }
  7812. /**
  7813. * 重新生成分段剧本
  7814. * @param array $data 包含以下字段:
  7815. * - prompt: string|null 用户修改要求(可选)
  7816. * - template_id: int|null 提示词模板ID(可选)
  7817. * - act_id: int|null 单个片段ID(与episode_id二选一)
  7818. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  7819. * @return array 返回生成结果
  7820. */
  7821. public function regenerateSegmentScript($data) {
  7822. $uid = Site::getUid();
  7823. $prompt = trim((string)getProp($data, 'prompt', ''));
  7824. $template_id = getProp($data, 'template_id', 0);
  7825. $act_id = getProp($data, 'act_id', 0);
  7826. $episode_id = getProp($data, 'episode_id', 0);
  7827. // 验证:prompt和template_id至少提供一个
  7828. if (empty($prompt) && empty($template_id)) {
  7829. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  7830. }
  7831. // 验证:act_id和episode_id二选一
  7832. if (empty($act_id) && empty($episode_id)) {
  7833. Utils::throwError('20003:请提供片段ID或剧集ID');
  7834. }
  7835. if (!empty($act_id) && !empty($episode_id)) {
  7836. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  7837. }
  7838. // 如果提供了template_id,获取模板提示词
  7839. $template_prompt = '';
  7840. if ($template_id > 0) {
  7841. $template = DB::table('mp_prompt_templates')
  7842. ->where('id', $template_id)
  7843. ->where('is_deleted', 0)
  7844. ->first();
  7845. if (!$template) {
  7846. Utils::throwError('20003:提示词模板不存在或已删除');
  7847. }
  7848. $template_prompt = $template->template_prompt ?? '';
  7849. }
  7850. // 合并用户提示词和模板提示词
  7851. $final_prompt = '';
  7852. if (!empty($template_prompt)) {
  7853. $final_prompt = $template_prompt;
  7854. if (!empty($prompt)) {
  7855. $final_prompt .= "\n\n补充要求:" . $prompt;
  7856. }
  7857. } else {
  7858. $final_prompt = $prompt;
  7859. }
  7860. // 获取需要重新生成的内容参考
  7861. $reference_content = '';
  7862. $target_episode_id = 0;
  7863. $target_anime_id = 0;
  7864. $target_episode_number = 0;
  7865. if ($act_id > 0) {
  7866. // 单个片段模式:获取该片段的内容
  7867. $segment = DB::table('mp_episode_segments')
  7868. ->where('id', $act_id)
  7869. ->first();
  7870. if (!$segment) {
  7871. Utils::throwError('20003:片段不存在');
  7872. }
  7873. $target_episode_id = $segment->episode_id;
  7874. $target_anime_id = $segment->anime_id;
  7875. $target_episode_number = $segment->episode_number;
  7876. $reference_content = $segment->act_content ?? '';
  7877. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  7878. } else {
  7879. // 整个剧集模式:获取所有片段的内容
  7880. $segments = DB::table('mp_episode_segments')
  7881. ->where('episode_id', $episode_id)
  7882. ->orderBy('act_number')
  7883. ->get();
  7884. if ($segments->isEmpty()) {
  7885. Utils::throwError('20003:该剧集没有片段数据');
  7886. }
  7887. $target_episode_id = $episode_id;
  7888. $target_anime_id = $segments[0]->anime_id;
  7889. $target_episode_number = $segments[0]->episode_number;
  7890. // 拼接所有片段内容,保留格式用于AI理解
  7891. $act_contents = [];
  7892. foreach ($segments as $seg) {
  7893. $act_number = $seg->act_number;
  7894. $act_content = $seg->act_content ?? '';
  7895. if (!empty($act_content)) {
  7896. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  7897. }
  7898. }
  7899. $reference_content = implode("\n\n", $act_contents);
  7900. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  7901. if ($episode_content) {
  7902. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  7903. }else {
  7904. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  7905. }
  7906. }
  7907. if (empty($reference_content)) {
  7908. Utils::throwError('20003:没有可参考的片段内容');
  7909. }
  7910. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  7911. $episode = DB::table('mp_anime_episodes')
  7912. ->where('id', $target_episode_id)
  7913. ->first();
  7914. if (!$episode) {
  7915. Utils::throwError('20003:剧集不存在');
  7916. }
  7917. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  7918. $anime_script_id = getProp($anime, 'script_id');
  7919. $intro = $episode->intro ?? '';
  7920. $art_style = $episode->art_style ?? '';
  7921. $roles = json_decode($episode->roles ?? '[]', true);
  7922. $scenes = json_decode($episode->scenes ?? '[]', true);
  7923. // 构建提示词中的主体列表和场景列表参考
  7924. $roles_ref = '';
  7925. if (!empty($roles) && is_array($roles)) {
  7926. $roles_list = [];
  7927. foreach ($roles as $role) {
  7928. $role_name = getProp($role, 'role', '');
  7929. $role_desc = getProp($role, 'description', '');
  7930. $pic_prompt = getProp($role, 'pic_prompt', '');
  7931. $voice_prompt = getProp($role, 'voice_prompt', '');
  7932. if (!empty($role_name)) {
  7933. $role_line = $role_name;
  7934. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  7935. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  7936. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  7937. $roles_list[] = $role_line;
  7938. }
  7939. }
  7940. if (!empty($roles_list)) {
  7941. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  7942. }
  7943. }
  7944. $scenes_ref = '';
  7945. if (!empty($scenes) && is_array($scenes)) {
  7946. $scenes_list = [];
  7947. foreach ($scenes as $scene) {
  7948. $scene_name = getProp($scene, 'scene', '');
  7949. $scene_desc = getProp($scene, 'description', '');
  7950. $pic_prompt = getProp($scene, 'pic_prompt', '');
  7951. if (!empty($scene_name)) {
  7952. $scene_line = $scene_name;
  7953. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  7954. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  7955. $scenes_list[] = $scene_line;
  7956. }
  7957. }
  7958. if (!empty($scenes_list)) {
  7959. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  7960. }
  7961. }
  7962. // 构建美术风格参考
  7963. $art_style_ref = '';
  7964. if (!empty($art_style)) {
  7965. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  7966. }
  7967. // 构建内容简介参考
  7968. $intro_ref = '';
  7969. if (!empty($intro)) {
  7970. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  7971. }
  7972. // 构建完整的AI提示词
  7973. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  7974. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  7975. $user_prompt .= $intro_ref;
  7976. $user_prompt .= $art_style_ref;
  7977. $user_prompt .= $reference_content;
  7978. // $user_prompt .= $roles_ref;
  7979. // $user_prompt .= $scenes_ref;
  7980. $system_prompt = "\n\n【强制要求】\n";
  7981. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  7982. $system_prompt .= "- 每个分镜包含:分镜序号、场景、画面、运镜、配音台词、背景音效\n";
  7983. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”后面“:”前面的任何内容,不能自创){$scenes_ref}\n";
  7984. $system_prompt .= "- 出场角色必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”后面“:”前面的任何内容,不能自创){$roles_ref}\n";
  7985. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  7986. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  7987. ###分段剧本
  7988. 片段数量:8
  7989. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7990. ##片段1
  7991. 时长:12s
  7992. 分镜1
  7993. 场景:边境小镇街道
  7994. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7995. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7996. 配音台词:
  7997. 背景音效:
  7998. 分镜2
  7999. 场景:悦来酒馆
  8000. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8001. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8002. 配音台词:
  8003. 背景音效:
  8004. 分镜3
  8005. 场景:悦来酒馆
  8006. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8007. 运镜:从中景推向令牌特写。
  8008. 配音台词:
  8009. 背景音效:
  8010. 分镜4
  8011. 场景:悦来酒馆
  8012. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8013. 运镜:极速推向酒水溅起的瞬间。
  8014. 配音台词:
  8015. 背景音效:
  8016. 分镜5
  8017. 镜头描述
  8018. 场景:悦来酒馆
  8019. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8020. 运镜:固定机位,利用倾斜构图制造压迫感。
  8021. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8022. 背景音效:";
  8023. // 获取模型配置
  8024. $model = getProp($data, 'model');
  8025. if (!$model) {
  8026. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  8027. }
  8028. // 验证模型是否在可用模型表中
  8029. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8030. $model = 'deepseek-v4-pro';
  8031. }
  8032. // 模型兼容性处理
  8033. $thinkingMode = 'disabled';
  8034. $reasoningEffort = 'high';
  8035. if ($model === 'deepseek-chat') {
  8036. $model = 'deepseek-v4-flash';
  8037. $thinkingMode = 'disabled';
  8038. } elseif ($model === 'deepseek-reasoner') {
  8039. $model = 'deepseek-v4-flash';
  8040. $thinkingMode = 'enabled';
  8041. }
  8042. // 构建消息
  8043. $messages = [
  8044. [
  8045. 'role' => 'system',
  8046. 'content' => $system_prompt
  8047. ],
  8048. [
  8049. 'role' => 'user',
  8050. 'content' => $user_prompt
  8051. ]
  8052. ];
  8053. // dd($messages);
  8054. // 构建请求参数
  8055. $post_data = [
  8056. 'model' => $model,
  8057. 'messages' => $messages,
  8058. 'temperature' => 0.7,
  8059. 'frequency_penalty' => 0,
  8060. 'presence_penalty' => 0,
  8061. 'response_format' => ['type' => 'text'],
  8062. 'thinking' => ['type' => $thinkingMode],
  8063. 'stream' => false // 非流式输出
  8064. ];
  8065. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8066. // 调用AI生成新的分段剧本
  8067. try {
  8068. $fullContent = '';
  8069. $usage = [];
  8070. // 根据模型类型选择调用方法
  8071. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8072. // DeepSeek 官方模型使用 DeepSeek API
  8073. $chatResult = $this->chatOnly($post_data);
  8074. } else if (in_array($model, $this->gpt_text_models)) {
  8075. // GPT 模型使用 TokenRouter API
  8076. $chatResult = $this->gpt54ChatOnly($post_data);
  8077. } else {
  8078. // 其他模型使用火山引擎API
  8079. $chatResult = $this->volcEngineChatCompletion($post_data);
  8080. }
  8081. if (is_array($chatResult)) {
  8082. $fullContent = $chatResult['fullContent'] ?? '';
  8083. $usage = $chatResult['usage'] ?? [];
  8084. }
  8085. $generated_content = $fullContent;
  8086. if (empty($generated_content)) {
  8087. Utils::throwError('20003:AI生成内容为空,请重试');
  8088. }
  8089. // 解析生成的内容 - 按片段分割
  8090. $parsed_segments = [];
  8091. // 先在开头添加换行符,确保第1片段也能被正确分割
  8092. $normalizedText = "\n" . $generated_content;
  8093. $parts = preg_split('/\n\s*##/', $normalizedText);
  8094. foreach ($parts as $part) {
  8095. $part = trim($part);
  8096. if (empty($part)) continue;
  8097. // 匹配"片段X"格式
  8098. if (!preg_match('/^片段\d+/', $part)) {
  8099. continue;
  8100. }
  8101. // 分离标题和内容
  8102. $lines = explode("\n", $part, 2);
  8103. $actTitle = trim($lines[0]);
  8104. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  8105. // 解析标题,提取序号
  8106. $actNumber = 0;
  8107. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  8108. $actNumber = intval($segmentTitleMatch[1]);
  8109. } else {
  8110. $actNumber = count($parsed_segments) + 1;
  8111. }
  8112. // 提取时长(仅保留数字)
  8113. $actDuration = 0;
  8114. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  8115. $actDurationStr = trim($actDurationMatch[1]);
  8116. // 提取数字部分(支持整数和小数)
  8117. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  8118. $actDuration = (float)$numMatch[1];
  8119. }
  8120. }
  8121. // 清理act_content:去除时长、旁白音色等非分镜内容行
  8122. // 只保留分镜内容,并确保分镜标记使用【】格式
  8123. $cleaned_content = '';
  8124. $content_lines = explode("\n", $actContent);
  8125. $is_capturing = false; // 标记是否开始捕获分镜内容
  8126. $count = 0;
  8127. foreach ($content_lines as $line) {
  8128. $trimmed_line = trim($line);
  8129. // 跳过时长和旁白音色行
  8130. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  8131. continue;
  8132. }
  8133. // 检测是否是分镜开始
  8134. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  8135. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  8136. $count++;
  8137. $is_capturing = true;
  8138. // 如果没有【】,则添加
  8139. if (!preg_match('/^【/u', $trimmed_line)) {
  8140. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  8141. }
  8142. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  8143. }
  8144. // 如果已经开始捕获,则添加该行
  8145. if ($is_capturing && !empty($trimmed_line)) {
  8146. $cleaned_content .= $trimmed_line."\n";
  8147. }
  8148. }
  8149. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  8150. $parsed_segments[] = [
  8151. 'act_number' => $actNumber,
  8152. 'act_title' => $actTitle,
  8153. 'act_duration' => $actDuration,
  8154. 'act_content' => $cleaned_content,
  8155. ];
  8156. }
  8157. if (empty($parsed_segments)) {
  8158. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  8159. }
  8160. // 获取角色和场景名称用于标记
  8161. $role_names = [];
  8162. $scene_names = [];
  8163. if (!empty($roles) && is_array($roles)) {
  8164. foreach ($roles as $role) {
  8165. $role_name = getProp($role, 'role', '');
  8166. if (!empty($role_name)) {
  8167. $role_names[] = $role_name;
  8168. }
  8169. }
  8170. }
  8171. if (!empty($scenes) && is_array($scenes)) {
  8172. foreach ($scenes as $scene) {
  8173. $scene_name = getProp($scene, 'scene', '');
  8174. if (!empty($scene_name)) {
  8175. $scene_names[] = $scene_name;
  8176. }
  8177. }
  8178. }
  8179. // 处理每个片段的 act_show_content
  8180. foreach ($parsed_segments as &$segment) {
  8181. $act_content = getProp($segment, 'act_content', '');
  8182. if (empty($act_content)) {
  8183. $segment['act_show_content'] = '';
  8184. continue;
  8185. }
  8186. $processed_content = $act_content;
  8187. // 先匹配场景(在"场景:"后面)
  8188. foreach ($scene_names as $scene_name) {
  8189. // 转义特殊字符
  8190. $escaped_scene = preg_quote($scene_name, '/');
  8191. // 匹配场景:后面的场景名称(可能换行,也可能不换行)
  8192. $pattern = '/(场景:[\s\r\n]*)(' . $escaped_scene . ')/u';
  8193. $processed_content = preg_replace_callback($pattern, function($matches) {
  8194. $prefix = $matches[1];
  8195. $scene_name = $matches[2];
  8196. // 检查是否已经被标记
  8197. if (strpos($scene_name, '{') === false && strpos($scene_name, '}') === false) {
  8198. return $prefix . '{' . $scene_name . '}';
  8199. }
  8200. return $matches[0];
  8201. }, $processed_content);
  8202. }
  8203. // 再匹配角色名称(只在"画面:"部分)
  8204. foreach ($role_names as $role_name) {
  8205. // 转义特殊字符
  8206. $escaped_role = preg_quote($role_name, '/');
  8207. // 只匹配"画面:"开始到换行之前的内容
  8208. $pattern = '/(画面:[^\n]*)/u';
  8209. $processed_content = preg_replace_callback($pattern, function($matches) use ($escaped_role) {
  8210. $line = $matches[1]; // 整行"画面:xxxxx"
  8211. // 在这一行中匹配所有角色名(避免重复标记)
  8212. $new_line = preg_replace(
  8213. '/(?<![{])(' . $escaped_role . ')(?![}])/u',
  8214. '{$1}',
  8215. $line
  8216. );
  8217. return $new_line;
  8218. }, $processed_content);
  8219. }
  8220. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  8221. $shot_counter = 0;
  8222. $processed_content = preg_replace_callback(
  8223. '/【(?:镜头|分镜)(\d+)】/u',
  8224. function($matches) use (&$shot_counter) {
  8225. $shot_counter++;
  8226. return '【镜头' . $shot_counter . '】';
  8227. },
  8228. $processed_content
  8229. );
  8230. $segment['act_show_content'] = $processed_content;
  8231. }
  8232. unset($segment); // 解除引用
  8233. // 保存到数据库
  8234. $now = date('Y-m-d H:i:s');
  8235. $saved_acts = []; // 用于记录保存后的片段信息
  8236. if ($act_id > 0) {
  8237. // 单个片段模式:更新单条记录
  8238. if (count($parsed_segments) > 0) {
  8239. $new_segment = $parsed_segments[0];
  8240. $update_data = [
  8241. 'act_content' => getProp($new_segment, 'act_content', ''),
  8242. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  8243. 'act_title' => getProp($new_segment, 'act_title', ''),
  8244. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  8245. 'updated_at' => $now,
  8246. ];
  8247. DB::table('mp_episode_segments')
  8248. ->where('id', $act_id)
  8249. ->update($update_data);
  8250. // 获取更新后的记录
  8251. $updated_act = DB::table('mp_episode_segments')
  8252. ->where('id', $act_id)
  8253. ->first();
  8254. if ($updated_act) {
  8255. $saved_acts[] = [
  8256. 'act_id' => $updated_act->id,
  8257. 'act_number' => $updated_act->act_number,
  8258. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  8259. 'act_content' => $updated_act->act_content,
  8260. 'act_show_content' => $updated_act->act_show_content,
  8261. 'video_url' => $updated_act->video_url ?? '',
  8262. 'video_duration' => $updated_act->video_duration ?? 0,
  8263. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  8264. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  8265. ];
  8266. }
  8267. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  8268. }
  8269. } else {
  8270. // 整个剧集模式:删除原有记录并批量保存新记录
  8271. DB::beginTransaction();
  8272. try {
  8273. // 删除原有的所有片段记录
  8274. DB::table('mp_episode_segments')
  8275. ->where('episode_id', $target_episode_id)
  8276. ->delete();
  8277. // 批量插入新的片段记录
  8278. $segments_to_insert = [];
  8279. foreach ($parsed_segments as $index => $segment) {
  8280. $act_number = $index + 1;
  8281. $segments_to_insert[] = [
  8282. 'anime_id' => $target_anime_id,
  8283. 'episode_id' => $target_episode_id,
  8284. 'episode_number' => $target_episode_number,
  8285. 'act_number' => $act_number,
  8286. 'act_title' => getProp($segment, 'act_title', ''),
  8287. 'act_duration' => getProp($segment, 'act_duration', 0),
  8288. 'act_content' => getProp($segment, 'act_content', ''),
  8289. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  8290. 'created_at' => $now,
  8291. 'updated_at' => $now,
  8292. ];
  8293. }
  8294. if (!empty($segments_to_insert)) {
  8295. DB::table('mp_episode_segments')->insert($segments_to_insert);
  8296. }
  8297. DB::commit();
  8298. // 查询保存后的所有片段记录
  8299. $saved_segments = DB::table('mp_episode_segments')
  8300. ->where('episode_id', $target_episode_id)
  8301. ->orderBy('act_number')
  8302. ->get();
  8303. foreach ($saved_segments as $saved_segment) {
  8304. $saved_acts[] = [
  8305. 'act_id' => $saved_segment->id,
  8306. 'act_number' => $saved_segment->act_number,
  8307. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  8308. 'act_content' => $saved_segment->act_content,
  8309. 'act_show_content' => $saved_segment->act_show_content,
  8310. 'video_url' => $saved_segment->video_url ?? '',
  8311. 'video_duration' => $saved_segment->video_duration ?? 0,
  8312. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  8313. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  8314. ];
  8315. }
  8316. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  8317. 'episode_id' => $target_episode_id,
  8318. 'segments_count' => count($segments_to_insert)
  8319. ]);
  8320. } catch (\Exception $e) {
  8321. DB::rollBack();
  8322. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  8323. Utils::throwError('20003:保存失败,请重试');
  8324. }
  8325. }
  8326. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  8327. return [
  8328. 'anime_id' => $target_anime_id,
  8329. 'episode_id' => $target_episode_id,
  8330. 'title' => getProp($episode, 'title', ''),
  8331. 'episode_number' => $target_episode_number,
  8332. 'is_generated' => getProp($episode, 'is_generated', 0),
  8333. 'acts' => $saved_acts,
  8334. ];
  8335. } catch (\Exception $e) {
  8336. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  8337. throw $e;
  8338. }
  8339. }
  8340. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  8341. {
  8342. $episode_arr = [
  8343. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  8344. 'intro' => getProp($script_arr, 'intro'),
  8345. 'art_style' => getProp($script_arr, 'art_style'),
  8346. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8347. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8348. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  8349. ];
  8350. if (empty($episode_arr['acts'])) {
  8351. $fallback_episode_arr = handleEpisodeContent($fullContent);
  8352. if (!empty($fallback_episode_arr['acts'])) {
  8353. $episode_arr = array_merge($fallback_episode_arr, [
  8354. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  8355. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  8356. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  8357. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  8358. ]);
  8359. }
  8360. }
  8361. // if (!getProp($episode_arr, 'episode_title')) {
  8362. // $episode_title = '';
  8363. // $episodes = getProp($script_arr, 'episodes', []);
  8364. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  8365. // $episode_title = '第1集:' . $episodes[0]['title'];
  8366. // }
  8367. // if (!$episode_title) {
  8368. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  8369. // }
  8370. // $episode_arr['episode_title'] = $episode_title;
  8371. // }
  8372. return $episode_arr;
  8373. }
  8374. private function saveEpisodeVersionData(
  8375. int $anime_id,
  8376. int $episode_number,
  8377. array $episode_arr,
  8378. array $existing_roles,
  8379. array $existing_scenes,
  8380. $current_episode,
  8381. $base_episode,
  8382. bool $is_regenerate_version,
  8383. string $content,
  8384. string $now,
  8385. array $ref_products = []
  8386. ): array {
  8387. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  8388. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  8389. $merged_roles = $generated_roles;
  8390. $merged_scenes = $generated_scenes;
  8391. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  8392. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  8393. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  8394. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8395. $ace_mode = getProp($anime, 'ace_mode');
  8396. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  8397. $global_roles = json_decode(getProp($anime, 'roles'), true);
  8398. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  8399. $global_roles = is_array($global_roles) ? $global_roles : [];
  8400. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  8401. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  8402. $art_style_type = getProp($anime, 'art_style_type');
  8403. // 检查并创建 roles 的图片生成任务
  8404. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  8405. // 检查并创建 scenes 的图片生成任务
  8406. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  8407. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $ref_products, $art_style_type);
  8408. if ($arr && is_array($arr)) {
  8409. $merged_roles = $arr['roles'];
  8410. $merged_scenes = $arr['scenes'];
  8411. }
  8412. // 确保数据是数组类型
  8413. if (!is_array($merged_roles)) {
  8414. dLog('deepseek')->error('merged_roles不是数组类型', [
  8415. 'type' => gettype($merged_roles),
  8416. 'value' => $merged_roles
  8417. ]);
  8418. $merged_roles = [];
  8419. }
  8420. if (!is_array($merged_scenes)) {
  8421. dLog('deepseek')->error('merged_scenes不是数组类型', [
  8422. 'type' => gettype($merged_scenes),
  8423. 'value' => $merged_scenes
  8424. ]);
  8425. $merged_scenes = [];
  8426. }
  8427. // 同步新出现的主体和场景到全局
  8428. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  8429. $role_arr = [];
  8430. foreach ($merged_roles as $item) {
  8431. $role_arr[$item['role']] = $item;
  8432. }
  8433. $version_count = DB::table('mp_anime_episodes')
  8434. ->where('anime_id', $anime_id)
  8435. ->where('episode_number', $episode_number)
  8436. ->count('id');
  8437. $episode = [
  8438. 'anime_id' => $anime_id,
  8439. 'episode_number' => $episode_number,
  8440. 'title' => getProp($episode_arr, 'episode_title'),
  8441. 'content' => $content,
  8442. 'intro' => getProp($episode_arr, 'intro'),
  8443. 'art_style' => getProp($episode_arr, 'art_style'),
  8444. 'roles' => json_encode($merged_roles, 256),
  8445. 'scenes' => json_encode($merged_scenes, 256),
  8446. 'generate_status' => '待执行',
  8447. 'generate_at' => $now,
  8448. 'is_default' => 1,
  8449. 'updated_at' => $now,
  8450. ];
  8451. $del_flag = false;
  8452. if ($is_regenerate_version) {
  8453. DB::table('mp_anime_episodes')
  8454. ->where('anime_id', $anime_id)
  8455. ->where('episode_number', $episode_number)
  8456. ->update(['is_default' => 0, 'updated_at' => $now]);
  8457. $episode['sequence'] = $version_count + 1;
  8458. $episode['created_at'] = $now;
  8459. $episode['cpid'] = Site::getCpid();
  8460. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  8461. if (!$episode_id) {
  8462. Utils::throwError('20003:创建剧集版本失败');
  8463. }
  8464. } else {
  8465. $target_episode = $current_episode ?: $base_episode;
  8466. if ($target_episode) {
  8467. $episode_id = getProp($target_episode, 'id');
  8468. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  8469. DB::table('mp_anime_episodes')
  8470. ->where('anime_id', $anime_id)
  8471. ->where('episode_number', $episode_number)
  8472. ->where('id', '<>', $episode_id)
  8473. ->update(['is_default' => 0, 'updated_at' => $now]);
  8474. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  8475. if ($boolen === false) {
  8476. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  8477. Utils::throwError('20003:分集内容保存失败');
  8478. }
  8479. $del_flag = true;
  8480. } else {
  8481. DB::table('mp_anime_episodes')
  8482. ->where('anime_id', $anime_id)
  8483. ->where('episode_number', $episode_number)
  8484. ->update(['is_default' => 0, 'updated_at' => $now]);
  8485. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  8486. $episode['created_at'] = $now;
  8487. $episode['cpid'] = Site::getCpid();
  8488. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  8489. if (!$episode_id) {
  8490. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  8491. Utils::throwError('20003:分集内容保存失败');
  8492. }
  8493. }
  8494. }
  8495. $segments = [];
  8496. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  8497. // 如果是第2集及以后,获取上一集的主体音色数据
  8498. $previous_roles_voice = [];
  8499. if ($episode_number >= 2) {
  8500. $previous_episode = DB::table('mp_anime_episodes')
  8501. ->where('anime_id', $anime_id)
  8502. ->where('episode_number', $episode_number - 1)
  8503. ->where('is_default', 1)
  8504. ->first();
  8505. if ($previous_episode) {
  8506. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  8507. if (is_array($previous_roles)) {
  8508. foreach ($previous_roles as $prev_role) {
  8509. $role_name = getProp($prev_role, 'role');
  8510. if ($role_name) {
  8511. $previous_roles_voice[$role_name] = [
  8512. 'voice_name' => getProp($prev_role, 'voice_name'),
  8513. 'voice_type' => getProp($prev_role, 'voice_type'),
  8514. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  8515. ];
  8516. $voice_prompt = getProp($prev_role, 'voice_prompt');
  8517. if ($voice_prompt) {
  8518. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  8519. }
  8520. }
  8521. }
  8522. }
  8523. }
  8524. }
  8525. // 将继承的音色数据同步到当前集的主体列表
  8526. if (!empty($previous_roles_voice)) {
  8527. foreach ($merged_roles as &$role) {
  8528. $role_name = getProp($role, 'role');
  8529. if ($role_name && isset($previous_roles_voice[$role_name])) {
  8530. // 强制继承上一集的音色数据
  8531. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  8532. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  8533. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  8534. // 如果上一集有 voice_prompt 则继承,否则跳过
  8535. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  8536. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  8537. }
  8538. }
  8539. }
  8540. unset($role); // 解除引用
  8541. // 更新 role_arr 以便后续使用
  8542. $role_arr = [];
  8543. foreach ($merged_roles as $item) {
  8544. $role_arr[$item['role']] = $item;
  8545. }
  8546. }
  8547. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  8548. $emotion_list = array_flip($emotion_list);
  8549. foreach ($acts as $act) {
  8550. $act_segments = getProp($act, 'segments', []);
  8551. if (!is_array($act_segments)) {
  8552. continue;
  8553. }
  8554. if ((int)$ace_mode === 1) {
  8555. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  8556. $merged_parts = [];
  8557. foreach ($act_segments as $seg) {
  8558. $seg_num = getProp($seg, 'segment_number');
  8559. $seg_content = getProp($seg, 'segment_content');
  8560. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  8561. }
  8562. $act_content = implode("\n", $merged_parts);
  8563. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  8564. $segments[] = [
  8565. 'anime_id' => $anime_id,
  8566. 'episode_id' => $episode_id,
  8567. 'episode_number' => $episode_number,
  8568. 'act_number' => getProp($act, 'act_number'),
  8569. 'act_title' => getProp($act, 'act_title'),
  8570. 'act_duration' => getProp($act, 'act_duration'),
  8571. 'act_content' => $act_content,
  8572. 'created_at' => $now,
  8573. 'updated_at' => $now
  8574. ];
  8575. } else {
  8576. foreach ($act_segments as $segment) {
  8577. $voice_actor = getProp($segment, 'voice_actor');
  8578. // 优先从上一集继承音色数据
  8579. $timbre_info = [];
  8580. if (isset($previous_roles_voice[$voice_actor])) {
  8581. // 从上一集继承音色数据
  8582. $timbre_info = $previous_roles_voice[$voice_actor];
  8583. } elseif (isset($role_arr[$voice_actor])) {
  8584. // 使用当前集的主体音色数据
  8585. $timbre_info = $role_arr[$voice_actor];
  8586. }
  8587. $voice_type = getProp($timbre_info, 'voice_type');
  8588. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  8589. if ($timbre_emotion) {
  8590. $timbre_emotion = explode(',', $timbre_emotion);
  8591. } else {
  8592. $timbre_emotion = [];
  8593. }
  8594. $emotion = getProp($segment, 'emotion', '中性');
  8595. if (!in_array($emotion, $timbre_emotion)) {
  8596. $emotion = '中性';
  8597. }
  8598. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  8599. $segments[] = [
  8600. 'anime_id' => $anime_id,
  8601. 'episode_id' => $episode_id,
  8602. 'episode_number' => $episode_number,
  8603. 'act_number' => getProp($act, 'act_number'),
  8604. 'act_title' => getProp($act, 'act_title'),
  8605. 'act_duration' => getProp($act, 'act_duration'),
  8606. 'segment_id' => getProp($segment, 'segment_id'),
  8607. 'segment_number' => getProp($segment, 'segment_number'),
  8608. 'segment_content' => getProp($segment, 'segment_content'),
  8609. 'description' => getProp($segment, 'description'),
  8610. 'composition' => getProp($segment, 'composition'),
  8611. 'camera_movement' => getProp($segment, 'camera_movement'),
  8612. 'voice_actor' => $voice_actor,
  8613. 'dialogue' => getProp($segment, 'dialogue'),
  8614. 'frame_type' => getProp($segment, 'frame_type'),
  8615. 'scene' => getProp($segment, 'scene'),
  8616. 'characters' => getProp($segment, 'characters'),
  8617. 'tail_frame' => getProp($segment, 'tail_frame'),
  8618. 'voice_name' => getProp($timbre_info, 'voice_name'),
  8619. 'voice_type' => $voice_type,
  8620. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  8621. 'emotion' => $emotion,
  8622. 'emotion_type' => $emotion_type,
  8623. 'gender' => getProp($segment, 'gender', '0'),
  8624. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  8625. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  8626. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  8627. 'pitch' => getProp($segment, 'pitch', 0),
  8628. 'created_at' => $now,
  8629. 'updated_at' => $now
  8630. ];
  8631. }
  8632. }
  8633. }
  8634. if ($segments) {
  8635. if ($del_flag) {
  8636. DB::table('mp_episode_segments')
  8637. ->where('anime_id', $anime_id)
  8638. ->where('episode_id', $episode_id)
  8639. ->delete();
  8640. }
  8641. $boolen = DB::table('mp_episode_segments')->insert($segments);
  8642. if (!$boolen) {
  8643. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  8644. Utils::throwError('20003:分镜内容保存失败');
  8645. }
  8646. }
  8647. dLog('deepseek')->info('segments', $segments);
  8648. // ace_mode=1: acts 返回值按合并格式调整
  8649. if ((int)$ace_mode === 1) {
  8650. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  8651. $act_map = [];
  8652. foreach ($table_act_data as $item) {
  8653. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  8654. }
  8655. $restructured_acts = [];
  8656. foreach ($acts as $act) {
  8657. $act_segments = getProp($act, 'segments', []);
  8658. if (!is_array($act_segments)) {
  8659. continue;
  8660. }
  8661. $merged_parts = [];
  8662. foreach ($act_segments as $seg) {
  8663. $seg_num = getProp($seg, 'segment_number');
  8664. $seg_content = getProp($seg, 'segment_content');
  8665. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  8666. }
  8667. $act_content = implode("\n", $merged_parts);
  8668. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  8669. $restructured_acts[] = [
  8670. 'anime_id' => $anime_id,
  8671. 'episode_id' => $episode_id,
  8672. 'episode_number' => $episode_number,
  8673. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  8674. 'act_number' => getProp($act, 'act_number'),
  8675. 'act_title' => getProp($act, 'act_title'),
  8676. 'act_duration' => getProp($act, 'act_duration'),
  8677. 'act_content' => $act_content,
  8678. 'created_at' => $now,
  8679. 'updated_at' => $now,
  8680. ];
  8681. }
  8682. $acts = $restructured_acts;
  8683. }
  8684. $episode['episode_id'] = $episode_id;
  8685. $episode['roles'] = $merged_roles;
  8686. $episode['scenes'] = $merged_scenes;
  8687. $episode['acts'] = $acts;
  8688. return [
  8689. 'episode' => $episode,
  8690. 'episode_id' => $episode_id,
  8691. 'merged_roles' => $merged_roles,
  8692. 'merged_scenes' => $merged_scenes,
  8693. ];
  8694. }
  8695. private function buildEpisodeItemContent(array $items, string $nameKey): string
  8696. {
  8697. $content = '';
  8698. foreach ($items as $item) {
  8699. $name = trim((string)getProp($item, $nameKey));
  8700. if ($name === '' || $name === '旁白') {
  8701. continue;
  8702. }
  8703. $description = trim((string)getProp($item, 'description'));
  8704. $content .= $name . ': ' . $description;
  8705. if ($nameKey == 'role') {
  8706. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  8707. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  8708. $voice_name = trim(getProp($item, 'voice_name'));
  8709. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  8710. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  8711. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  8712. }else {
  8713. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  8714. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  8715. }
  8716. $content .= "\n";
  8717. }
  8718. return trim($content);
  8719. }
  8720. private function getEpisodeChatContent($animeId, $sequence, $content) {
  8721. if ((int)$sequence <= 0) {
  8722. return [];
  8723. }
  8724. $origin_content = '';
  8725. if ($content) {
  8726. $origin_content = '本集剧情内容:'.$content;
  8727. }else {
  8728. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  8729. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  8730. }
  8731. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  8732. // 获取分集信息
  8733. $episode = DB::table('mp_anime_episodes')
  8734. ->where('anime_id', $animeId)
  8735. ->where('episode_number', $sequence)
  8736. ->where('is_default', 1)
  8737. ->first();
  8738. if (!$episode) {
  8739. return [];
  8740. }
  8741. $episode_id = getProp($episode, 'id');
  8742. $episode_number = getProp($episode, 'episode_number');
  8743. $title = getProp($episode, 'title');
  8744. $intro = getProp($episode, 'intro');
  8745. $art_style = getProp($episode, 'art_style');
  8746. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  8747. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  8748. // 组装纯文本内容
  8749. $content = '';
  8750. // 添加分集标题和梗概
  8751. $content .= "###第{$episode_number}集:{$title}\n\n";
  8752. $content .= "###故事梗概\n";
  8753. $content .= trim($intro) . "\n\n";
  8754. // 添加美术风格
  8755. $content .= "###美术风格\n";
  8756. $content .= trim($art_style) . "\n\n";
  8757. // 添加主体列表
  8758. $content .= "###主体列表\n";
  8759. $pangbai_voice_prompt = "";
  8760. foreach ($roles as $role) {
  8761. $name = getProp($role, 'role');
  8762. $description = getProp($role, 'description');
  8763. $pic_prompt = getProp($role, 'pic_prompt');
  8764. $voice_prompt = getProp($role, 'voice_prompt');
  8765. $voice_name = getProp($role, 'voice_name');
  8766. $content .= "{$name}: {$description}";
  8767. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  8768. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  8769. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  8770. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  8771. $content .= "\n";
  8772. }
  8773. $content .= "\n";
  8774. // 添加场景列表
  8775. $content .= "###场景列表\n";
  8776. foreach ($scenes as $scene) {
  8777. $name = getProp($scene, 'scene');
  8778. $description = getProp($scene, 'description');
  8779. $pic_prompt = getProp($scene, 'pic_prompt');
  8780. $content .= "{$name}: {$description}";
  8781. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  8782. $content .= "\n";
  8783. }
  8784. $content .= "\n";
  8785. // 获取分镜信息
  8786. $segments = DB::table('mp_episode_segments')
  8787. ->where('anime_id', $animeId)
  8788. ->where('episode_id', $episode_id)
  8789. ->orderBy('segment_number')
  8790. ->get();
  8791. if ($segments && count($segments) > 0) {
  8792. if ((int)$ace_mode === 1) {
  8793. $content .= "###分段剧本\n";
  8794. // 获取片段数量
  8795. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  8796. $content .= "片段数量:{$act_count}\n";
  8797. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  8798. $content .= "\n";
  8799. }else {
  8800. $content .= "###分镜剧本\n";
  8801. }
  8802. // 按幕分组
  8803. $currentAct = null;
  8804. foreach ($segments as $segment) {
  8805. $act_number = getProp($segment, 'act_number');
  8806. $act_title = getProp($segment, 'act_title');
  8807. $act_duration = getProp($segment, 'act_duration');
  8808. $segment_number = getProp($segment, 'segment_number');
  8809. $segment_content = getProp($segment, 'segment_content');
  8810. $scene_description = getProp($segment, 'scene_description');
  8811. $scene_name = getProp($segment, 'scene_name');
  8812. $composition = getProp($segment, 'composition');
  8813. $camera_movement = getProp($segment, 'camera_movement');
  8814. $voice_type = getProp($segment, 'voice_type');
  8815. $characters = getProp($segment, 'characters');
  8816. $dialogue = getProp($segment, 'dialogue');
  8817. $frame_type = getProp($segment, 'frame_type');
  8818. $tail_frame_description = getProp($segment, 'tail_frame_description');
  8819. // 判断是否是全能模式
  8820. if ((int)$ace_mode === 1) { // 全能模式
  8821. // 如果是新的分段,添加分段标题
  8822. if ($act_number !== $currentAct) {
  8823. $currentAct = $act_number;
  8824. $content .= "##{$act_title}\n";
  8825. $content .= "时长:{$act_duration}s\n";
  8826. }
  8827. }else {
  8828. // 如果是新的幕,添加幕标题
  8829. if ($act_number !== $currentAct) {
  8830. $currentAct = $act_number;
  8831. $content .= "##第{$act_number}幕:{$scene_name}\n";
  8832. }
  8833. }
  8834. // 添加分镜信息
  8835. $content .= "分镜{$segment_number}\n";
  8836. $content .= "分镜内容:\n{$segment_content}\n";
  8837. // $content .= "画面描述:{$scene_description}\n";
  8838. // $content .= "场景:{$scene_name}\n";
  8839. // $content .= "构图设计:{$composition}\n";
  8840. // $content .= "运镜调度:{$camera_movement}\n";
  8841. // if (!empty($voice_type)) {
  8842. // $content .= "配音角色:{$voice_type}\n";
  8843. // }
  8844. // if (!empty($characters)) {
  8845. // $content .= "出镜角色:{$characters}\n";
  8846. // }
  8847. // if (!empty($dialogue)) {
  8848. // $content .= "台词内容:\"{$dialogue}\"\n";
  8849. // }
  8850. // $content .= "画面类型:{$frame_type}\n";
  8851. // $content .= "尾帧描述:{$tail_frame_description}\n";
  8852. $content .= "\n";
  8853. }
  8854. }
  8855. $content = trim($content);
  8856. if($content) $content = "上集剧本内容:\n{$content}";
  8857. return [
  8858. [
  8859. 'role' => 'user',
  8860. 'content' => $origin_content
  8861. ],
  8862. [
  8863. 'role' => 'assistant',
  8864. 'content' => $content
  8865. ]
  8866. ];
  8867. }
  8868. private function getEpisodeChatMessages($animeId, $sequence): array
  8869. {
  8870. if ((int)$sequence <= 0) {
  8871. return [];
  8872. }
  8873. return DB::table('mp_anime_records')
  8874. ->where('anime_id', $animeId)
  8875. ->where('sequence', $sequence)
  8876. ->where('episode_id', '>', 0)
  8877. ->select('role', 'content')
  8878. ->orderBy('created_at')
  8879. ->orderBy('id')
  8880. ->get()
  8881. ->map(function ($value) {
  8882. return (array)$value;
  8883. })
  8884. ->toArray();
  8885. }
  8886. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  8887. {
  8888. $existingMap = [];
  8889. foreach ($existingItems as $item) {
  8890. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  8891. if ($itemKey === '') {
  8892. continue;
  8893. }
  8894. $existingMap[$itemKey] = $item;
  8895. }
  8896. if (!$generatedItems) {
  8897. return array_values($existingItems);
  8898. }
  8899. $merged = [];
  8900. foreach ($generatedItems as $item) {
  8901. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  8902. if ($itemKey === '') {
  8903. continue;
  8904. }
  8905. if (isset($existingMap[$itemKey])) {
  8906. if (trim((string)getProp($item, 'description')) === '') {
  8907. $merged[] = $existingMap[$itemKey];
  8908. continue;
  8909. }
  8910. // 检查内容是否发生变化
  8911. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  8912. if (!$isChanged) {
  8913. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  8914. $mergedItem = [
  8915. $nameKey => trim((string)getProp($item, $nameKey)),
  8916. 'description' => trim((string)getProp($item, 'description')),
  8917. ];
  8918. // 如果有 pic_prompt,添加到合并项中
  8919. $picPrompt = getProp($item, 'pic_prompt');
  8920. if (!empty($picPrompt)) {
  8921. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  8922. }
  8923. // 继承现有项的 URL
  8924. $existingUrl = getProp($existingMap[$itemKey], 'url');
  8925. if (!empty($existingUrl)) {
  8926. $mergedItem['url'] = $existingUrl;
  8927. }
  8928. // 继承现有项的 task_id
  8929. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  8930. if (!empty($existingTaskId)) {
  8931. $mergedItem['task_id'] = $existingTaskId;
  8932. }
  8933. // 继承现有项的 task_status
  8934. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  8935. if (!empty($existingTaskStatus)) {
  8936. $mergedItem['task_status'] = $existingTaskStatus;
  8937. }
  8938. // 保留生成项的音色字段
  8939. $voiceName = getProp($item, 'voice_name');
  8940. if (!empty($voiceName)) {
  8941. $mergedItem['voice_name'] = $voiceName;
  8942. }
  8943. $voiceType = getProp($item, 'voice_type');
  8944. if (!empty($voiceType)) {
  8945. $mergedItem['voice_type'] = $voiceType;
  8946. }
  8947. $audioUrl = getProp($item, 'voice_audio_url');
  8948. if (!empty($audioUrl)) {
  8949. $mergedItem['voice_audio_url'] = $audioUrl;
  8950. }
  8951. $merged[] = $mergedItem;
  8952. } else {
  8953. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  8954. $mergedItem = [
  8955. $nameKey => trim((string)getProp($item, $nameKey)),
  8956. 'description' => trim((string)getProp($item, 'description')),
  8957. ];
  8958. // 如果有 pic_prompt,添加到合并项中
  8959. $picPrompt = getProp($item, 'pic_prompt');
  8960. if (!empty($picPrompt)) {
  8961. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  8962. }
  8963. // 保留生成项的音色字段
  8964. $voiceName = getProp($item, 'voice_name');
  8965. if (!empty($voiceName)) {
  8966. $mergedItem['voice_name'] = $voiceName;
  8967. }
  8968. $voiceType = getProp($item, 'voice_type');
  8969. if (!empty($voiceType)) {
  8970. $mergedItem['voice_type'] = $voiceType;
  8971. }
  8972. $audioUrl = getProp($item, 'voice_audio_url');
  8973. if (!empty($audioUrl)) {
  8974. $mergedItem['voice_audio_url'] = $audioUrl;
  8975. }
  8976. // 不继承 URL、task_id 和 task_status(重置状态)
  8977. $merged[] = $mergedItem;
  8978. }
  8979. } else {
  8980. // 新增项,保留生成项的所有字段
  8981. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  8982. }
  8983. }
  8984. return $merged ?: array_values($existingItems);
  8985. }
  8986. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  8987. {
  8988. $resetItem = [
  8989. $nameKey => trim((string)getProp($item, $nameKey)),
  8990. 'description' => trim((string)getProp($item, 'description')),
  8991. ];
  8992. // 保留指定的字段
  8993. foreach ($preserveFields as $field) {
  8994. $value = getProp($item, $field);
  8995. if (!empty($value)) {
  8996. $resetItem[$field] = $value;
  8997. }
  8998. }
  8999. return $resetItem;
  9000. }
  9001. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  9002. {
  9003. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  9004. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  9005. if ($existingKey !== $generatedKey) {
  9006. return true;
  9007. }
  9008. // 比较 description 是否变化
  9009. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  9010. return true;
  9011. }
  9012. // 比较 pic_prompt 是否变化
  9013. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  9014. }
  9015. private function normalizeEpisodeResourceKey($value): string
  9016. {
  9017. $value = trim((string)$value);
  9018. if ($value === '') {
  9019. return '';
  9020. }
  9021. return strtolower((string)preg_replace('/\s+/u', '', $value));
  9022. }
  9023. // 生成全局角色图片
  9024. private function batchSetGlobalRoleImg($data, $is_force=false) {
  9025. $anime_id = getProp($data, 'anime_id');
  9026. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9027. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9028. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9029. $art_style = getProp($anime, 'art_style');
  9030. $update_flag = false;
  9031. foreach ($roles as &$role) {
  9032. $role_name = getProp($role, 'role');
  9033. if ($role_name == '旁白') continue;
  9034. // 优先使用 pic_prompt,如果没有则使用 description
  9035. $pic_prompt = getProp($role, 'pic_prompt');
  9036. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  9037. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9038. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9039. // 参考图地址
  9040. $ref_img_url = getProp($role, 'url');
  9041. if (!$is_force && $ref_img_url) continue;
  9042. $update_flag = true;
  9043. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9044. try {
  9045. $params = [
  9046. 'prompt' => $description,
  9047. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  9048. 'ref_img_urls' => []
  9049. ];
  9050. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9051. $task_id = $task->id;
  9052. if (!$task_id) {
  9053. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  9054. }
  9055. $role['task_id'] = $task_id;
  9056. $role['task_status'] = 'processing';
  9057. } catch (\Exception $e) {
  9058. Utils::throwError("20003:" . $e->getMessage());
  9059. }
  9060. }
  9061. if (!$update_flag) return true;
  9062. // 保存角色信息
  9063. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9064. 'roles' => json_encode($roles, 256),
  9065. 'generate_status' => '执行中',
  9066. 'generate_at' => date('Y-m-d H:i:s'),
  9067. 'updated_at' => date('Y-m-d H:i:s')
  9068. ]);
  9069. if (!$boolen) {
  9070. Utils::throwError('20003:保存角色信息失败');
  9071. }
  9072. return $boolen;
  9073. }
  9074. // 生成全局场景图片
  9075. private function batchSetGlobalSceneImg($data, $is_force=false) {
  9076. $anime_id = getProp($data, 'anime_id');
  9077. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9078. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9079. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  9080. $art_style = getProp($anime, 'art_style');
  9081. $update_flag = false;
  9082. foreach ($scenes as &$scene) {
  9083. $scene_name = getProp($scene, 'scene');
  9084. // 优先使用 pic_prompt,如果没有则使用 description
  9085. $pic_prompt = getProp($scene, 'pic_prompt');
  9086. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  9087. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  9088. // 参考图地址
  9089. $ref_img_url = getProp($scene, 'url');
  9090. if (!$is_force && $ref_img_url) continue;
  9091. $update_flag = true;
  9092. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9093. try {
  9094. $params = [
  9095. 'prompt' => $description,
  9096. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  9097. 'ref_img_urls' => []
  9098. ];
  9099. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9100. $task_id = $task->id;
  9101. if (!$task_id) {
  9102. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  9103. }
  9104. $scene['task_id'] = $task_id;
  9105. $scene['task_status'] = 'processing';
  9106. } catch (\Exception $e) {
  9107. Utils::throwError("20003:" . $e->getMessage());
  9108. }
  9109. }
  9110. if (!$update_flag) return true;
  9111. // 保存角色信息
  9112. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9113. 'scenes' => json_encode($scenes, 256),
  9114. 'generate_status' => '执行中',
  9115. 'generate_at' => date('Y-m-d H:i:s'),
  9116. 'updated_at' => date('Y-m-d H:i:s')
  9117. ]);
  9118. if (!$boolen) {
  9119. Utils::throwError('20003:保存角色信息失败');
  9120. }
  9121. return $boolen;
  9122. }
  9123. // 生成分镜主体和场景图片
  9124. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $ref_products=[], $art_style_type='', $is_force=false) {
  9125. $character_prefix = '';
  9126. $scene_prefix = '';
  9127. if ($art_style_type) {
  9128. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  9129. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  9130. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  9131. }
  9132. $update_flag = false;
  9133. // 获取上一集的roles和scenes数据
  9134. $prev_roles = [];
  9135. $prev_scenes = [];
  9136. if ($episode_number > 1) {
  9137. $prev_episode = DB::table('mp_anime_episodes')
  9138. ->where('anime_id', $anime_id)
  9139. ->where('episode_number', $episode_number - 1)
  9140. ->where('is_default', 1)
  9141. ->first();
  9142. if ($prev_episode) {
  9143. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  9144. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  9145. dLog('deepseek')->info("获取上一集数据成功", [
  9146. 'anime_id' => $anime_id,
  9147. 'prev_episode_number' => $episode_number - 1,
  9148. 'prev_roles_count' => count($prev_roles),
  9149. 'prev_scenes_count' => count($prev_scenes)
  9150. ]);
  9151. }
  9152. }
  9153. // 处理角色图片生成
  9154. foreach ($roles as &$role) {
  9155. $role_name = getProp($role, 'role');
  9156. if ($role_name == '旁白') continue;
  9157. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  9158. if (isset($ref_products[$role_name])) {
  9159. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  9160. if ($role['url']) continue;
  9161. }
  9162. $role_description = getProp($role, 'description');
  9163. $role_pic_prompt = getProp($role, 'pic_prompt');
  9164. $role_url = getProp($role, 'url');
  9165. // 检查是否可以从上一集继承
  9166. $inherited = false;
  9167. if (!$is_force && !empty($prev_roles)) {
  9168. foreach ($prev_roles as $prev_role) {
  9169. $prev_role_name = getProp($prev_role, 'role');
  9170. $prev_description = getProp($prev_role, 'description');
  9171. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  9172. $prev_url = getProp($prev_role, 'url');
  9173. $prev_task_id = getProp($prev_role, 'task_id');
  9174. $prev_task_status = getProp($prev_role, 'task_status');
  9175. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  9176. if ($role_name == $prev_role_name
  9177. && $role_description == $prev_description
  9178. && $role_pic_prompt == $prev_pic_prompt
  9179. && !empty($prev_url)) {
  9180. $role['task_id'] = $prev_task_id;
  9181. $role['task_status'] = $prev_task_status;
  9182. $role['url'] = $prev_url;
  9183. $inherited = true;
  9184. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  9185. 'anime_id' => $anime_id,
  9186. 'episode_number' => $episode_number,
  9187. 'task_id' => $prev_task_id,
  9188. 'url' => $prev_url
  9189. ]);
  9190. break;
  9191. }
  9192. }
  9193. }
  9194. // 如果已继承或已有url,跳过生成
  9195. if ($inherited || (!$is_force && $role_url)) {
  9196. continue;
  9197. }
  9198. // 优先使用 pic_prompt,如果没有则使用 description
  9199. $pic_prompt = getProp($role, 'pic_prompt');
  9200. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  9201. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  9202. $update_flag = true;
  9203. // 调用AIImageGenerationService的生成图片任务接口
  9204. try {
  9205. $params = [
  9206. 'prompt' => $description,
  9207. 'ref_img_urls' => []
  9208. ];
  9209. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9210. $task_id = $task->id;
  9211. if (!$task_id) {
  9212. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  9213. continue; // 不中断,继续处理其他角色
  9214. }
  9215. $role['task_id'] = $task_id;
  9216. $role['task_status'] = 'processing';
  9217. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  9218. 'anime_id' => $anime_id,
  9219. 'episode_number' => $episode_number,
  9220. 'task_id' => $task_id
  9221. ]);
  9222. } catch (\Exception $e) {
  9223. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  9224. // 不抛出异常,继续处理其他角色
  9225. }
  9226. }
  9227. // 处理场景图片生成
  9228. foreach ($scenes as &$scene) {
  9229. $scene_name = getProp($scene, 'scene');
  9230. $scene_description = getProp($scene, 'description');
  9231. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  9232. $scene_url = getProp($scene, 'url');
  9233. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  9234. if (isset($ref_products[$scene_name])) {
  9235. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  9236. if ($scene['url']) continue;
  9237. }
  9238. // 检查是否可以从上一集继承
  9239. $inherited = false;
  9240. if (!$is_force && !empty($prev_scenes)) {
  9241. foreach ($prev_scenes as $prev_scene) {
  9242. $prev_scene_name = getProp($prev_scene, 'scene');
  9243. $prev_description = getProp($prev_scene, 'description');
  9244. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  9245. $prev_url = getProp($prev_scene, 'url');
  9246. $prev_task_id = getProp($prev_scene, 'task_id');
  9247. $prev_task_status = getProp($prev_scene, 'task_status');
  9248. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  9249. if ($scene_name == $prev_scene_name
  9250. && $scene_description == $prev_description
  9251. && $scene_pic_prompt == $prev_pic_prompt
  9252. && !empty($prev_url)) {
  9253. $scene['task_id'] = $prev_task_id;
  9254. $scene['task_status'] = $prev_task_status;
  9255. $scene['url'] = $prev_url;
  9256. $inherited = true;
  9257. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  9258. 'anime_id' => $anime_id,
  9259. 'episode_number' => $episode_number,
  9260. 'task_id' => $prev_task_id,
  9261. 'url' => $prev_url
  9262. ]);
  9263. break;
  9264. }
  9265. }
  9266. }
  9267. // 如果已继承或已有url,跳过生成
  9268. if ($inherited || (!$is_force && $scene_url)) {
  9269. continue;
  9270. }
  9271. // 优先使用 pic_prompt,如果没有则使用 description
  9272. $pic_prompt = getProp($scene, 'pic_prompt');
  9273. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  9274. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  9275. $update_flag = true;
  9276. // 调用AIImageGenerationService的生成图片任务接口
  9277. try {
  9278. $params = [
  9279. 'prompt' => $description,
  9280. 'ref_img_urls' => []
  9281. ];
  9282. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9283. $task_id = $task->id;
  9284. if (!$task_id) {
  9285. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  9286. continue; // 不中断,继续处理其他场景
  9287. }
  9288. $scene['task_id'] = $task_id;
  9289. $scene['task_status'] = 'processing';
  9290. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  9291. 'anime_id' => $anime_id,
  9292. 'episode_number' => $episode_number,
  9293. 'task_id' => $task_id
  9294. ]);
  9295. } catch (\Exception $e) {
  9296. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  9297. // 不抛出异常,继续处理其他场景
  9298. }
  9299. }
  9300. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes];
  9301. // 将处理完毕的roles和scenes与全局(mp_animes)数据对比并合并
  9302. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes);
  9303. // // 保存剧集的角色和场景信息
  9304. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  9305. // 'roles' => json_encode($roles, 256),
  9306. // 'scenes' => json_encode($scenes, 256),
  9307. // 'generate_status' => '执行中',
  9308. // 'generate_at' => date('Y-m-d H:i:s'),
  9309. // 'updated_at' => date('Y-m-d H:i:s')
  9310. // ]);
  9311. // if (!$boolen) {
  9312. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  9313. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  9314. // }
  9315. dLog('deepseek')->info('剧集角色和场景图片任务创建完成', [
  9316. // 'episode_id' => $episode_id,
  9317. 'roles_count' => count($roles),
  9318. 'scenes_count' => count($scenes)
  9319. ]);
  9320. return ['roles' => $roles, 'scenes' => $scenes];
  9321. }
  9322. /**
  9323. * 将剧集的roles和scenes同步到全局(mp_animes)
  9324. * 如果全局中不存在相同的role/scene(role、description、pic_prompt三项一致),则添加到全局
  9325. *
  9326. * @param int $anime_id 动漫对话ID
  9327. * @param array $episode_roles 剧集角色数据
  9328. * @param array $episode_scenes 剧集场景数据
  9329. * @return bool
  9330. */
  9331. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes) {
  9332. // 获取全局数据
  9333. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9334. if (!$anime) {
  9335. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  9336. return false;
  9337. }
  9338. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9339. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  9340. $roles_added = false;
  9341. $roles_updated = false;
  9342. $scenes_added = false;
  9343. // 处理角色同步
  9344. foreach ($episode_roles as $episode_role) {
  9345. $episode_role_name = getProp($episode_role, 'role');
  9346. $episode_description = getProp($episode_role, 'description');
  9347. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  9348. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  9349. // 跳过旁白
  9350. if ($episode_role_name == '旁白') {
  9351. continue;
  9352. }
  9353. // 检查全局中是否已存在相同的角色
  9354. $exists = false;
  9355. $global_role_index = -1;
  9356. foreach ($global_roles as $index => $global_role) {
  9357. $global_role_name = getProp($global_role, 'role');
  9358. $global_description = getProp($global_role, 'description');
  9359. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  9360. // 如果role、description、pic_prompt三项都一致,则认为已存在
  9361. if ($episode_role_name == $global_role_name
  9362. && $episode_description == $global_description
  9363. && $episode_pic_prompt == $global_pic_prompt) {
  9364. $exists = true;
  9365. $global_role_index = $index;
  9366. break;
  9367. }
  9368. }
  9369. // 如果不存在,则添加到全局
  9370. if (!$exists) {
  9371. $global_roles[] = $episode_role;
  9372. $roles_added = true;
  9373. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  9374. 'anime_id' => $anime_id,
  9375. 'role' => $episode_role_name
  9376. ]);
  9377. } else {
  9378. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  9379. if (!empty($episode_voice_prompt)) {
  9380. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  9381. // 如果全局没有voice_prompt或与剧集不一致,则更新
  9382. if ($global_voice_prompt !== $episode_voice_prompt) {
  9383. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  9384. $roles_updated = true;
  9385. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  9386. 'anime_id' => $anime_id,
  9387. 'role' => $episode_role_name,
  9388. 'voice_prompt' => $episode_voice_prompt
  9389. ]);
  9390. }
  9391. }
  9392. }
  9393. }
  9394. // 处理场景同步
  9395. foreach ($episode_scenes as $episode_scene) {
  9396. $episode_scene_name = getProp($episode_scene, 'scene');
  9397. $episode_description = getProp($episode_scene, 'description');
  9398. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  9399. // 检查全局中是否已存在相同的场景
  9400. $exists = false;
  9401. foreach ($global_scenes as $global_scene) {
  9402. $global_scene_name = getProp($global_scene, 'scene');
  9403. $global_description = getProp($global_scene, 'description');
  9404. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  9405. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  9406. if ($episode_scene_name == $global_scene_name
  9407. && $episode_description == $global_description
  9408. && $episode_pic_prompt == $global_pic_prompt) {
  9409. $exists = true;
  9410. break;
  9411. }
  9412. }
  9413. // 如果不存在,则添加到全局
  9414. if (!$exists) {
  9415. $global_scenes[] = $episode_scene;
  9416. $scenes_added = true;
  9417. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  9418. 'anime_id' => $anime_id,
  9419. 'scene' => $episode_scene_name
  9420. ]);
  9421. }
  9422. }
  9423. // 如果有新增或更新,则更新全局数据
  9424. if ($roles_added || $roles_updated || $scenes_added) {
  9425. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  9426. if ($roles_added || $roles_updated) {
  9427. $update_data['roles'] = json_encode($global_roles, 256);
  9428. }
  9429. if ($scenes_added) {
  9430. $update_data['scenes'] = json_encode($global_scenes, 256);
  9431. }
  9432. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  9433. dLog('deepseek')->info('剧集数据同步到全局完成', [
  9434. 'anime_id' => $anime_id,
  9435. 'roles_added' => $roles_added,
  9436. 'roles_updated' => $roles_updated,
  9437. 'scenes_added' => $scenes_added,
  9438. 'global_roles_count' => count($global_roles),
  9439. 'global_scenes_count' => count($global_scenes)
  9440. ]);
  9441. }
  9442. return true;
  9443. }
  9444. /**
  9445. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  9446. *
  9447. * @param int $anime_id 动漫对话ID
  9448. * @param int $episode_id 分集ID
  9449. * @return bool
  9450. */
  9451. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  9452. // 获取全局角色和场景数据
  9453. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9454. if (!$anime) {
  9455. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  9456. return false;
  9457. }
  9458. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9459. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  9460. // 获取指定的分集
  9461. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  9462. if (!$episode) {
  9463. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  9464. return false;
  9465. }
  9466. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9467. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9468. $roles_updated = false;
  9469. $scenes_updated = false;
  9470. // 继承角色的task_id、task_status和url
  9471. foreach ($episode_roles as &$episode_role) {
  9472. $episode_role_name = getProp($episode_role, 'role');
  9473. $episode_description = getProp($episode_role, 'description');
  9474. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  9475. $episode_url = getProp($episode_role, 'url');
  9476. // 跳过旁白角色
  9477. if ($episode_role_name == '旁白') {
  9478. continue;
  9479. }
  9480. // 如果剧集中已有URL,跳过
  9481. if (!empty($episode_url)) {
  9482. continue;
  9483. }
  9484. // 遍历全局角色数据,查找匹配的角色
  9485. foreach ($global_roles as $global_role) {
  9486. $global_role_name = getProp($global_role, 'role');
  9487. $global_description = getProp($global_role, 'description');
  9488. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  9489. $global_url = getProp($global_role, 'url');
  9490. $global_task_id = getProp($global_role, 'task_id');
  9491. $global_task_status = getProp($global_role, 'task_status');
  9492. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  9493. if ($episode_role_name == $global_role_name
  9494. && $episode_description == $global_description
  9495. && $episode_pic_prompt == $global_pic_prompt) {
  9496. // 继承 task_id、task_status 和 url
  9497. if (!empty($global_task_id)) {
  9498. $episode_role['task_id'] = $global_task_id;
  9499. $episode_role['task_status'] = $global_task_status;
  9500. $roles_updated = true;
  9501. dLog('deepseek')->info('剧集角色继承全局task_id', [
  9502. 'episode_id' => $episode_id,
  9503. 'role' => $episode_role_name,
  9504. 'task_id' => $global_task_id,
  9505. 'task_status' => $global_task_status
  9506. ]);
  9507. }
  9508. if (!empty($global_url)) {
  9509. $episode_role['url'] = $global_url;
  9510. $roles_updated = true;
  9511. dLog('deepseek')->info('剧集角色继承全局url', [
  9512. 'episode_id' => $episode_id,
  9513. 'role' => $episode_role_name,
  9514. 'url' => $global_url
  9515. ]);
  9516. }
  9517. break;
  9518. }
  9519. }
  9520. }
  9521. // 继承场景的task_id、task_status和url
  9522. foreach ($episode_scenes as &$episode_scene) {
  9523. $episode_scene_name = getProp($episode_scene, 'scene');
  9524. $episode_description = getProp($episode_scene, 'description');
  9525. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  9526. $episode_url = getProp($episode_scene, 'url');
  9527. // 如果剧集中已有URL,跳过
  9528. if (!empty($episode_url)) {
  9529. continue;
  9530. }
  9531. // 遍历全局场景数据,查找匹配的场景
  9532. foreach ($global_scenes as $global_scene) {
  9533. $global_scene_name = getProp($global_scene, 'scene');
  9534. $global_description = getProp($global_scene, 'description');
  9535. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  9536. $global_url = getProp($global_scene, 'url');
  9537. $global_task_id = getProp($global_scene, 'task_id');
  9538. $global_task_status = getProp($global_scene, 'task_status');
  9539. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  9540. if ($episode_scene_name == $global_scene_name
  9541. && $episode_description == $global_description
  9542. && $episode_pic_prompt == $global_pic_prompt) {
  9543. // 继承 task_id、task_status 和 url
  9544. if (!empty($global_task_id)) {
  9545. $episode_scene['task_id'] = $global_task_id;
  9546. $episode_scene['task_status'] = $global_task_status;
  9547. $scenes_updated = true;
  9548. dLog('deepseek')->info('剧集场景继承全局task_id', [
  9549. 'episode_id' => $episode_id,
  9550. 'scene' => $episode_scene_name,
  9551. 'task_id' => $global_task_id,
  9552. 'task_status' => $global_task_status
  9553. ]);
  9554. }
  9555. if (!empty($global_url)) {
  9556. $episode_scene['url'] = $global_url;
  9557. $scenes_updated = true;
  9558. dLog('deepseek')->info('剧集场景继承全局url', [
  9559. 'episode_id' => $episode_id,
  9560. 'scene' => $episode_scene_name,
  9561. 'url' => $global_url
  9562. ]);
  9563. }
  9564. break;
  9565. }
  9566. }
  9567. }
  9568. // 如果有更新,则保存到数据库
  9569. if ($roles_updated || $scenes_updated) {
  9570. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  9571. if ($roles_updated) {
  9572. $update_data['roles'] = json_encode($episode_roles, 256);
  9573. }
  9574. if ($scenes_updated) {
  9575. $update_data['scenes'] = json_encode($episode_scenes, 256);
  9576. }
  9577. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  9578. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  9579. 'episode_id' => $episode_id,
  9580. 'roles_updated' => $roles_updated,
  9581. 'scenes_updated' => $scenes_updated
  9582. ]);
  9583. }
  9584. return true;
  9585. }
  9586. public function chatChangeImg($data) {
  9587. $segment = getProp($data, 'segment');
  9588. $segment_content = getProp($segment, 'segment_content');
  9589. $prompt = getProp($data, 'prompt');
  9590. $ref_img = getProp($data, 'ref_img');
  9591. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  9592. // 处理文本模型
  9593. $model = getProp($data, 'model');
  9594. if (!$model) {
  9595. // 用户没有输入,从anime表获取
  9596. $segment_id = getProp($segment, 'segment_id');
  9597. if ($segment_id) {
  9598. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  9599. if ($episode_id) {
  9600. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  9601. if ($anime_id) {
  9602. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  9603. }
  9604. }
  9605. }
  9606. if (!$model) {
  9607. // anime表也没有,使用默认值
  9608. $model = 'doubao-seed-2-0-mini-260215';
  9609. }
  9610. }
  9611. // 验证模型是否在可用模型表中
  9612. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9613. $model = 'doubao-seed-2-0-mini-260215';
  9614. }
  9615. $messages[] =
  9616. [
  9617. 'role' => 'user',
  9618. 'content' => $question
  9619. ];
  9620. $post_data = [
  9621. 'model' => $model,
  9622. 'messages' => $messages,
  9623. // 'max_tokens' => 8192,
  9624. 'temperature' => 0.7,
  9625. 'frequency_penalty' => 0,
  9626. 'presence_penalty' => 0,
  9627. 'response_format' => ['type' => 'text'],
  9628. 'stream' => false // 是否启用流式输出
  9629. ];
  9630. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9631. // DeepSeek 官方模型使用 DeepSeek API
  9632. $chatResult = $this->chatOnly($post_data);
  9633. } else if (in_array($model, $this->gpt_text_models)) {
  9634. // GPT-5.4 模型使用 TokenRouter API
  9635. $chatResult = $this->gpt54ChatOnly($post_data);
  9636. } else {
  9637. // 其他模型使用火山引擎API
  9638. $chatResult = $this->volcEngineChatCompletion($post_data);
  9639. }
  9640. if (is_array($chatResult)) {
  9641. extract($chatResult);
  9642. }else {
  9643. Utils::throwError('20003: 接口调用失败!');
  9644. }
  9645. return [
  9646. 'type' => 'done',
  9647. // 'episode' => $episode,
  9648. 'answer' => $fullContent,
  9649. 'reasoning' => $fullReasoningContent,
  9650. 'usage' => $usage
  9651. ];
  9652. }
  9653. // 仅调用deepseek对话接口
  9654. private function chatOnly($post_data) {
  9655. $post_data['max_tokens'] = 300000;
  9656. $client = new Client(['timeout' => 1800, 'verify' => false]);
  9657. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  9658. $response = $result->getBody()->getContents();
  9659. $response_arr = json_decode($response, true);
  9660. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  9661. $fullContent = '';
  9662. $fullReasoningContent = [];
  9663. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  9664. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  9665. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  9666. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  9667. }
  9668. return [
  9669. 'fullContent' => $fullContent,
  9670. 'fullReasoningContent' => $fullReasoningContent,
  9671. 'usage' => $usage
  9672. ];
  9673. }
  9674. // 仅调用 GPT-5.4 对话接口(非流式)
  9675. private function gpt54ChatOnly($post_data) {
  9676. $apiKey = env('GPT_54_API_KEY');
  9677. if (empty($apiKey)) {
  9678. Utils::throwError('20003:GPT-5.4 API Key未配置');
  9679. }
  9680. $client = new Client(['timeout' => 1800, 'verify' => false]);
  9681. $headers = [
  9682. 'Authorization' => 'Bearer ' . $apiKey,
  9683. 'Content-Type' => 'application/json'
  9684. ];
  9685. // 移除 thinking 参数,GPT-5.4 不支持
  9686. if (isset($post_data['thinking'])) {
  9687. unset($post_data['thinking']);
  9688. }
  9689. if (isset($post_data['reasoning_effort'])) {
  9690. unset($post_data['reasoning_effort']);
  9691. }
  9692. $post_data['max_completion_tokens'] = 100000;
  9693. // 确保 stream 为 false
  9694. $post_data['stream'] = false;
  9695. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  9696. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  9697. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  9698. 'json' => $post_data,
  9699. 'headers' => $headers
  9700. ]);
  9701. $response = $result->getBody()->getContents();
  9702. $response_arr = json_decode($response, true);
  9703. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  9704. $fullContent = '';
  9705. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  9706. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  9707. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  9708. }
  9709. return [
  9710. 'fullContent' => $fullContent,
  9711. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  9712. 'usage' => $usage
  9713. ];
  9714. }
  9715. private function splitContent($content) {
  9716. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  9717. $chapters = [];
  9718. // 匹配章节标题格式:
  9719. // 1. 标题独占一行
  9720. // 2. 格式支持:
  9721. // - **第一集**
  9722. // - 第一集:
  9723. // - ###第1章 重生
  9724. // - ##第2章 相救
  9725. // - 第三章 共处一室
  9726. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  9727. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  9728. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  9729. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  9730. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  9731. // 先用正则找出所有章节标题的位置
  9732. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  9733. $titleCount = count($matches[0]);
  9734. for ($i = 0; $i < $titleCount; $i++) {
  9735. // 获取当前章节标题
  9736. $titleLine = trim($matches[0][$i][0]);
  9737. // 去除标题开头的特殊符号
  9738. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  9739. // 去除标题结尾的冒号
  9740. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  9741. $cleanTitle = trim($cleanTitle);
  9742. // 获取当前标题的结束位置
  9743. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  9744. // 获取下一个章节标题的开始位置(如果存在)
  9745. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  9746. // 提取章节内容(从标题结束到下一个标题开始)
  9747. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  9748. // 清理内容:去除前后空白和分隔线
  9749. $chapterContent = trim($chapterContent);
  9750. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  9751. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  9752. if (!empty($cleanTitle) && !empty($chapterContent)) {
  9753. $chapters[] = [
  9754. 'title' => $cleanTitle,
  9755. 'content' => $chapterContent
  9756. ];
  9757. }
  9758. }
  9759. } else {
  9760. // 如果没有匹配到章节,返回整个内容
  9761. $chapters[] = [
  9762. 'title' => '',
  9763. 'content' => $content
  9764. ];
  9765. }
  9766. return $chapters;
  9767. }
  9768. public function getContentByBid($bid) {
  9769. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  9770. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  9771. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  9772. $content = '';
  9773. foreach ($chapters as $chapter) {
  9774. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  9775. }
  9776. return $content;
  9777. }
  9778. public function getContentByScriptId($script_id) {
  9779. $content = '';
  9780. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  9781. if ($contents) {
  9782. $content = implode(PHP_EOL, $contents);
  9783. }else {
  9784. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  9785. }
  9786. return $content;
  9787. }
  9788. /**
  9789. * 根据文件类型提取文本内容
  9790. *
  9791. * @param mixed $file 文件对象或文件路径
  9792. * @return string
  9793. */
  9794. public function extractFileContent($file) {
  9795. // 获取文件路径和扩展名
  9796. if (is_string($file)) {
  9797. $filePath = $file;
  9798. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  9799. } else {
  9800. // Laravel UploadedFile 对象
  9801. $filePath = $file->getRealPath();
  9802. $extension = strtolower($file->getClientOriginalExtension());
  9803. }
  9804. $content = '';
  9805. switch ($extension) {
  9806. case 'txt':
  9807. $content = $this->extractTxtContent($filePath);
  9808. break;
  9809. case 'pdf':
  9810. $content = $this->extractPdfContent($filePath);
  9811. break;
  9812. case 'doc':
  9813. case 'docx':
  9814. $content = $this->extractWordContent($filePath);
  9815. break;
  9816. // case 'jpg':
  9817. // case 'jpeg':
  9818. // case 'png':
  9819. // case 'gif':
  9820. // case 'bmp':
  9821. // case 'webp':
  9822. // $content = $this->extractImageContent($filePath);
  9823. // break;
  9824. default:
  9825. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  9826. }
  9827. return $content;
  9828. }
  9829. /**
  9830. * 提取 TXT 文件内容
  9831. */
  9832. private function extractTxtContent($filePath) {
  9833. if (!file_exists($filePath)) {
  9834. Utils::throwError('20003:文件不存在');
  9835. }
  9836. $content = file_get_contents($filePath);
  9837. // 尝试检测并转换编码
  9838. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  9839. if ($encoding && $encoding !== 'UTF-8') {
  9840. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  9841. }
  9842. return trim($content);
  9843. }
  9844. /**
  9845. * 提取 PDF 文件内容
  9846. */
  9847. private function extractPdfContent($filePath) {
  9848. if (!file_exists($filePath)) {
  9849. Utils::throwError('20003:文件不存在');
  9850. }
  9851. try {
  9852. $parser = new PdfParser();
  9853. $pdf = $parser->parseFile($filePath);
  9854. $content = $pdf->getText();
  9855. return trim($content);
  9856. } catch (\Exception $e) {
  9857. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  9858. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  9859. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  9860. }
  9861. }
  9862. /**
  9863. * 提取 Word 文件内容(支持 doc 和 docx)
  9864. */
  9865. private function extractWordContent($filePath) {
  9866. if (!file_exists($filePath)) {
  9867. Utils::throwError('20003:文件不存在');
  9868. }
  9869. try {
  9870. $phpWord = WordIOFactory::load($filePath);
  9871. $content = '';
  9872. foreach ($phpWord->getSections() as $section) {
  9873. foreach ($section->getElements() as $element) {
  9874. $content .= $this->extractWordElementText($element);
  9875. }
  9876. }
  9877. return trim($content);
  9878. } catch (\Exception $e) {
  9879. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  9880. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  9881. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  9882. }
  9883. }
  9884. /**
  9885. * 递归提取 Word 元素中的文本
  9886. */
  9887. private function extractWordElementText($element) {
  9888. $text = '';
  9889. if (method_exists($element, 'getText')) {
  9890. $text .= $element->getText() . "\n";
  9891. } elseif (method_exists($element, 'getElements')) {
  9892. foreach ($element->getElements() as $childElement) {
  9893. $text .= $this->extractWordElementText($childElement);
  9894. }
  9895. }
  9896. return $text;
  9897. }
  9898. /**
  9899. * 提取图片内容(使用火山引擎 OCR)
  9900. */
  9901. private function extractImageContent($filePath) {
  9902. if (!file_exists($filePath)) {
  9903. Utils::throwError('20003:文件不存在');
  9904. }
  9905. try {
  9906. // 读取图片并转换为 base64
  9907. $imageData = file_get_contents($filePath);
  9908. $base64Image = base64_encode($imageData);
  9909. // 调用火山引擎 OCR 服务
  9910. $content = $this->callVolcEngineOCR($base64Image);
  9911. return trim($content);
  9912. } catch (\Exception $e) {
  9913. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  9914. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  9915. Utils::throwError('20003:图片识别失败');
  9916. }
  9917. }
  9918. /**
  9919. * 调用火山引擎 OCR 服务识别图片文字
  9920. *
  9921. * @param string $base64Image base64 编码的图片数据
  9922. * @return string 识别的文字内容
  9923. */
  9924. private function callVolcEngineOCR($base64Image) {
  9925. $method = 'POST';
  9926. $service = 'cv';
  9927. $host = 'visual.volcengineapi.com';
  9928. $region = env('VOLC_REGION', 'cn-north-1');
  9929. $access_key = env('VOLC_AK');
  9930. $secret_key = env('VOLC_SK');
  9931. $action = 'OCRNormal';
  9932. $version = '2020-08-26';
  9933. if (!$access_key || !$secret_key) {
  9934. Utils::throwError('20003:请配置火山引擎 AK/SK');
  9935. }
  9936. // 请求体
  9937. $body = json_encode([
  9938. 'image_base64' => $base64Image
  9939. ]);
  9940. // 生成签名
  9941. $headers = $this->getVolcEngineSignHeaders(
  9942. $method, $service, $host, $region,
  9943. "Action={$action}&Version={$version}",
  9944. $access_key, $secret_key, $body
  9945. );
  9946. $client = new Client(['timeout' => 1800, 'verify' => false]);
  9947. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  9948. 'headers' => $headers,
  9949. 'body' => $body
  9950. ]);
  9951. $response_arr = json_decode($response->getBody()->getContents(), true);
  9952. // 提取识别的文字
  9953. $textLines = [];
  9954. if (isset($response_arr['data']['line_texts'])) {
  9955. $textLines = $response_arr['data']['line_texts'];
  9956. } elseif (isset($response_arr['data']['ocr_infos'])) {
  9957. foreach ($response_arr['data']['ocr_infos'] as $info) {
  9958. if (isset($info['text'])) {
  9959. $textLines[] = $info['text'];
  9960. }
  9961. }
  9962. }
  9963. if (empty($textLines)) {
  9964. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  9965. return '';
  9966. }
  9967. return implode("\n", $textLines);
  9968. }
  9969. /**
  9970. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  9971. */
  9972. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  9973. $contentType = 'application/json';
  9974. $accept = 'application/json';
  9975. // 获取当前UTC时间
  9976. $t = new DateTime('now', new DateTimeZone('UTC'));
  9977. $xDate = $t->format('Ymd\THis\Z');
  9978. $dateStamp = $t->format('Ymd');
  9979. // 计算 body 的 sha256 哈希
  9980. $payloadHash = hash('sha256', $body);
  9981. // 1. 拼接规范请求串
  9982. $canonicalUri = '/';
  9983. $canonicalQueryString = $queryString;
  9984. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  9985. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  9986. $canonicalRequest = implode("\n", [
  9987. $method,
  9988. $canonicalUri,
  9989. $canonicalQueryString,
  9990. $canonicalHeaders,
  9991. $signedHeaders,
  9992. $payloadHash
  9993. ]);
  9994. // 2. 拼接待签名字符串
  9995. $algorithm = 'HMAC-SHA256';
  9996. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  9997. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  9998. $stringToSign = implode("\n", [
  9999. $algorithm,
  10000. $xDate,
  10001. $credentialScope,
  10002. $hashedCanonicalRequest
  10003. ]);
  10004. // 3. 计算签名
  10005. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  10006. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  10007. // 4. 添加签名到请求头
  10008. $authorizationHeader = sprintf(
  10009. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  10010. $algorithm,
  10011. $access_key,
  10012. $credentialScope,
  10013. $signedHeaders,
  10014. $signature
  10015. );
  10016. return [
  10017. 'Accept' => $accept,
  10018. 'Content-Type' => $contentType,
  10019. 'Host' => $host,
  10020. 'X-Date' => $xDate,
  10021. 'X-Content-Sha256'=> $payloadHash,
  10022. 'Authorization' => $authorizationHeader
  10023. ];
  10024. }
  10025. public function generateScriptWords($cid, $model = 'r1') {
  10026. ini_set('max_execution_time', 0);
  10027. if (!$cid) Utils::throwError('20003: 请选择章节!');
  10028. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  10029. // 模型兼容性处理和思考模式设置
  10030. $thinkingMode = 'disabled';
  10031. $reasoningEffort = 'high';
  10032. if ($model == 'r1') {
  10033. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  10034. $thinkingMode = 'enabled';
  10035. } else {
  10036. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  10037. $thinkingMode = 'disabled';
  10038. }
  10039. $messages = [
  10040. [
  10041. 'role' => 'system',
  10042. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  10043. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  10044. 2.非对话部分请全部用旁白角色代替
  10045. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  10046. ],
  10047. [
  10048. 'role' => 'user',
  10049. 'content' => $content
  10050. ]
  10051. ];
  10052. $post_data = [
  10053. 'model' => $model,
  10054. 'messages' => $messages,
  10055. // 'max_tokens' => 8192,
  10056. 'temperature' => 1,
  10057. 'frequency_penalty' => 0,
  10058. 'presence_penalty' => 0,
  10059. 'thinking' => ['type' => $thinkingMode],
  10060. 'response_format' => [
  10061. 'type' => 'text'
  10062. ],
  10063. 'stream' => false
  10064. ];
  10065. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  10066. // 根据模型类型选择调用方法
  10067. $fullContent = '';
  10068. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10069. // DeepSeek 官方模型使用 DeepSeek API
  10070. $chatResult = $this->chatOnly($post_data);
  10071. } else if (in_array($model, $this->gpt_text_models)) {
  10072. // GPT-5.4 模型使用 TokenRouter API
  10073. $chatResult = $this->gpt54ChatOnly($post_data);
  10074. } else {
  10075. // 其他模型使用火山引擎API
  10076. $chatResult = $this->volcEngineChatCompletion($post_data);
  10077. }
  10078. if (is_array($chatResult)) {
  10079. $fullContent = $chatResult['fullContent'];
  10080. }
  10081. return $fullContent;
  10082. }
  10083. /**
  10084. * 智能化解析集数信息
  10085. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  10086. *
  10087. * @param string $prompt 用户输入的提示词
  10088. * @return int|null 解析出的集数,如果没有找到则返回null
  10089. */
  10090. private function extractEpisodeNumber($prompt)
  10091. {
  10092. if (empty($prompt)) {
  10093. return null;
  10094. }
  10095. // 定义各种可能的表达模式
  10096. $patterns = [
  10097. // 基本模式:改成N集、调整成N集、修改成N集
  10098. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  10099. // 扩展模式:分成N集、拆分成N集、分割成N集
  10100. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  10101. // 数量模式:N集、共N集、总共N集
  10102. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  10103. // 制作模式:制作N集、生成N集、创建N集
  10104. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  10105. // 计划模式:计划N集、预计N集、打算N集
  10106. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  10107. // 需要模式:需要N集、要N集
  10108. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  10109. // 中文数字模式:改成三集、调整成五集等
  10110. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  10111. // 英文数字模式
  10112. '/(?: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',
  10113. ];
  10114. // 中文数字转阿拉伯数字的映射
  10115. $chineseNumbers = [
  10116. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  10117. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  10118. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  10119. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  10120. ];
  10121. // 逐个尝试匹配模式
  10122. foreach ($patterns as $pattern) {
  10123. if (preg_match($pattern, $prompt, $matches)) {
  10124. $number = trim($matches[1]);
  10125. // 如果是中文数字,转换为阿拉伯数字
  10126. if (isset($chineseNumbers[$number])) {
  10127. return $chineseNumbers[$number];
  10128. }
  10129. // 如果是阿拉伯数字,直接返回
  10130. if (is_numeric($number)) {
  10131. $episodeNum = intval($number);
  10132. // 合理性检查:集数应该在1-100之间
  10133. if ($episodeNum >= 1 && $episodeNum <= 100) {
  10134. return $episodeNum;
  10135. }
  10136. }
  10137. }
  10138. }
  10139. return null;
  10140. }
  10141. /**
  10142. * 调用火山引擎对话(Chat) API
  10143. *
  10144. * @param array $params 包含以下参数:
  10145. * - model: 模型ID(必填)
  10146. * - messages: 消息列表(必填)
  10147. * - stream: 是否流式输出(可选,默认false)
  10148. * - max_tokens: 最大输出token数(可选)
  10149. * - temperature: 采样温度(可选,默认1)
  10150. * - top_p: 核采样概率(可选,默认0.7)
  10151. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  10152. * - presence_penalty: 存在惩罚系数(可选,默认0)
  10153. * - stop: 停止词(可选)
  10154. * - tools: 工具列表(可选)
  10155. * @return array|Generator 非流式返回数组,流式返回生成器
  10156. */
  10157. public function volcEngineChatCompletion(array $params)
  10158. {
  10159. $apiKey = env('VOLC_AI_API_KEY');
  10160. if (empty($apiKey)) {
  10161. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  10162. }
  10163. // 构建请求参数
  10164. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  10165. $requestData = [
  10166. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  10167. 'messages' => $params['messages'] ?? [],
  10168. ];
  10169. if (!in_array($originalModel, $this->valid_text_models)) {
  10170. Utils::throwError('20003:该模型不支持!');
  10171. }
  10172. // 添加可选参数
  10173. if (isset($params['stream'])) {
  10174. $requestData['stream'] = $params['stream'];
  10175. }
  10176. if (isset($params['stream_options'])) {
  10177. $requestData['stream_options'] = $params['stream_options'];
  10178. }
  10179. if (isset($params['max_tokens'])) {
  10180. $requestData['max_tokens'] = $params['max_tokens'];
  10181. }else if (isset($params['max_completion_tokens'])) {
  10182. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  10183. }else {
  10184. $requestData['max_completion_tokens'] = 100000;
  10185. }
  10186. if (isset($params['temperature'])) {
  10187. $requestData['temperature'] = $params['temperature'];
  10188. }
  10189. if (isset($params['top_p'])) {
  10190. $requestData['top_p'] = $params['top_p'];
  10191. }
  10192. if (isset($params['frequency_penalty'])) {
  10193. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  10194. }
  10195. if (isset($params['presence_penalty'])) {
  10196. $requestData['presence_penalty'] = $params['presence_penalty'];
  10197. }
  10198. if (isset($params['stop'])) {
  10199. $requestData['stop'] = $params['stop'];
  10200. }
  10201. if (isset($params['tools'])) {
  10202. $requestData['tools'] = $params['tools'];
  10203. }
  10204. if (isset($params['tool_choice'])) {
  10205. $requestData['tool_choice'] = $params['tool_choice'];
  10206. }
  10207. if (isset($params['response_format'])) {
  10208. $requestData['response_format'] = $params['response_format'];
  10209. }
  10210. if (isset($params['thinking'])) {
  10211. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  10212. if (is_array($params['thinking'])) {
  10213. $requestData['thinking'] = $params['thinking'];
  10214. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  10215. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  10216. }
  10217. } else {
  10218. $requestData['thinking'] = ['type' => $params['thinking']];
  10219. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  10220. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  10221. }
  10222. }
  10223. } else {
  10224. $requestData['thinking'] = ['type' => 'disabled'];
  10225. }
  10226. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  10227. $client = new Client(['verify' => false, 'timeout' => 1800]);
  10228. try {
  10229. // 判断是否为流式输出
  10230. $isStream = isset($params['stream']) && $params['stream'] === true;
  10231. if ($isStream) {
  10232. // 流式输出
  10233. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  10234. } else {
  10235. // 非流式输出
  10236. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  10237. 'headers' => [
  10238. 'Authorization' => 'Bearer ' . $apiKey,
  10239. 'Content-Type' => 'application/json',
  10240. ],
  10241. 'json' => $requestData
  10242. ]);
  10243. $responseData = json_decode($response->getBody(), true);
  10244. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  10245. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  10246. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  10247. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  10248. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  10249. }
  10250. return [
  10251. 'fullContent' => $fullContent,
  10252. 'fullReasoningContent' => $fullReasoningContent,
  10253. 'usage' => $usage
  10254. ];
  10255. }
  10256. } catch (\Exception $e) {
  10257. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  10258. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  10259. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  10260. }
  10261. }
  10262. /**
  10263. * 火山引擎对话API流式输出
  10264. *
  10265. * @param Client $client HTTP客户端
  10266. * @param string $apiKey API密钥
  10267. * @param array $requestData 请求数据
  10268. * @return Generator
  10269. */
  10270. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  10271. {
  10272. try {
  10273. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  10274. 'headers' => [
  10275. 'Authorization' => 'Bearer ' . $apiKey,
  10276. 'Content-Type' => 'application/json',
  10277. ],
  10278. 'json' => $requestData,
  10279. 'stream' => true
  10280. ]);
  10281. $body = $response->getBody();
  10282. $buffer = '';
  10283. $fullContent = '';
  10284. $fullReasoningContent = '';
  10285. $usage = [];
  10286. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  10287. // 逐行读取流式响应
  10288. while (!$body->eof()) {
  10289. $chunk = $body->read(1024);
  10290. $buffer .= $chunk;
  10291. // 按行分割
  10292. $lines = explode("\n", $buffer);
  10293. $buffer = array_pop($lines);
  10294. foreach ($lines as $line) {
  10295. $line = trim($line);
  10296. if (empty($line)) {
  10297. continue;
  10298. }
  10299. // 检查是否是SSE数据行
  10300. if (strpos($line, 'data: ') !== 0) {
  10301. continue;
  10302. }
  10303. $data = substr($line, 6);
  10304. if ($data === '[DONE]') {
  10305. dLog('deepseek')->info('收到结束标记');
  10306. break 2;
  10307. }
  10308. try {
  10309. $json = json_decode($data, true);
  10310. if (json_last_error() !== JSON_ERROR_NONE) {
  10311. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  10312. continue;
  10313. }
  10314. if (isset($json['choices'][0]['delta'])) {
  10315. $delta = $json['choices'][0]['delta'];
  10316. // 处理思维链内容
  10317. if (isset($delta['reasoning_content'])) {
  10318. $fullReasoningContent .= $delta['reasoning_content'];
  10319. yield [
  10320. 'type' => 'reasoning',
  10321. 'content' => $delta['reasoning_content'],
  10322. 'full_reasoning' => $fullReasoningContent
  10323. ];
  10324. }
  10325. // 处理回答内容
  10326. if (isset($delta['content'])) {
  10327. $fullContent .= $delta['content'];
  10328. yield [
  10329. 'type' => 'content',
  10330. 'content' => $delta['content'],
  10331. ];
  10332. }
  10333. }
  10334. // 获取使用统计信息
  10335. if (isset($json['usage'])) {
  10336. $usage = $json['usage'];
  10337. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  10338. }
  10339. } catch (\Exception $e) {
  10340. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  10341. continue;
  10342. }
  10343. }
  10344. }
  10345. dLog('deepseek')->info('流式读取完成', [
  10346. 'content_length' => strlen($fullContent),
  10347. 'reasoning_length' => strlen($fullReasoningContent)
  10348. ]);
  10349. yield [
  10350. 'type' => 'done',
  10351. 'full_content' => $fullContent,
  10352. 'full_reasoning' => $fullReasoningContent,
  10353. 'usage' => $usage
  10354. ];
  10355. } catch (\Exception $e) {
  10356. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  10357. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  10358. throw $e;
  10359. }
  10360. }
  10361. /**
  10362. * 检查并创建图片生成任务
  10363. *
  10364. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  10365. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  10366. * @param string $nameKey 资源名称字段('role' 或 'scene')
  10367. * @param string $art_style 美术风格
  10368. * @return array 更新后的资源列表
  10369. */
  10370. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  10371. {
  10372. // 确保参数为数组
  10373. $merged_items = is_array($merged_items) ? $merged_items : [];
  10374. $global_items = is_array($global_items) ? $global_items : [];
  10375. // 构建全局资源映射表,用于快速查找
  10376. $global_map = [];
  10377. foreach ($global_items as $item) {
  10378. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  10379. if ($itemKey === '') {
  10380. continue;
  10381. }
  10382. $global_map[$itemKey] = $item;
  10383. }
  10384. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  10385. foreach ($merged_items as &$item) {
  10386. $item_name = getProp($item, $nameKey);
  10387. $item_description = getProp($item, 'description');
  10388. // $item_url = getProp($item, 'url');
  10389. // // 如果已有图片URL,跳过
  10390. // if (!empty($item_url)) {
  10391. // continue;
  10392. // }
  10393. // 如果是旁白角色,跳过
  10394. if ($nameKey === 'role' && $item_name === '旁白') {
  10395. continue;
  10396. }
  10397. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  10398. if ($itemKey === '') {
  10399. continue;
  10400. }
  10401. $need_create_task = false;
  10402. // 条件1:在全局资源中找不到匹配的名称
  10403. if (!isset($global_map[$itemKey])) {
  10404. $need_create_task = true;
  10405. } else {
  10406. // 条件2:名称匹配但描述或 pic_prompt 不一致
  10407. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  10408. $current_description = trim((string)$item_description);
  10409. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  10410. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  10411. // 如果 description 或 pic_prompt 有变化,需要重新生成
  10412. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  10413. $need_create_task = true;
  10414. }
  10415. }
  10416. // 如果需要创建任务,调用图片生成服务
  10417. if ($need_create_task) {
  10418. try {
  10419. // 优先使用 pic_prompt,如果没有则使用 description
  10420. $pic_prompt = getProp($item, 'pic_prompt');
  10421. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  10422. // 添加美术风格前缀
  10423. if ($art_style) {
  10424. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  10425. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  10426. $description = "{$prefix}:{$description}";
  10427. }
  10428. $params = [
  10429. 'prompt' => $description,
  10430. 'ref_img_urls' => []
  10431. ];
  10432. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10433. $task_id = $task->id;
  10434. if ($task_id) {
  10435. $item['task_id'] = $task_id;
  10436. $item['task_status'] = 'processing';
  10437. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  10438. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  10439. }
  10440. } catch (\Exception $e) {
  10441. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  10442. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  10443. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  10444. // 不抛出异常,继续处理其他资源
  10445. }
  10446. }
  10447. }
  10448. return $merged_items;
  10449. }
  10450. /**
  10451. * 同步新出现的主体和场景到全局
  10452. *
  10453. * @param int $anime_id 动漫ID
  10454. * @param array $merged_roles 合并后的角色列表
  10455. * @param array $merged_scenes 合并后的场景列表
  10456. * @param array $global_roles 全局角色列表
  10457. * @param array $global_scenes 全局场景列表
  10458. * @return void
  10459. */
  10460. private function syncNewResourcesToGlobal(
  10461. int $anime_id,
  10462. array $merged_roles,
  10463. array $merged_scenes,
  10464. array $global_roles,
  10465. array $global_scenes
  10466. ): void {
  10467. // 构建全局角色映射表
  10468. $global_role_map = [];
  10469. foreach ($global_roles as $role) {
  10470. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  10471. if ($roleKey !== '') {
  10472. $global_role_map[$roleKey] = $role;
  10473. }
  10474. }
  10475. // 构建全局场景映射表
  10476. $global_scene_map = [];
  10477. foreach ($global_scenes as $scene) {
  10478. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  10479. if ($sceneKey !== '') {
  10480. $global_scene_map[$sceneKey] = $scene;
  10481. }
  10482. }
  10483. $need_update = false;
  10484. $new_global_roles = $global_roles;
  10485. $new_global_scenes = $global_scenes;
  10486. // 检查并添加新角色到全局
  10487. foreach ($merged_roles as $role) {
  10488. $role_name = getProp($role, 'role');
  10489. // 跳过旁白
  10490. if ($role_name === '旁白') {
  10491. continue;
  10492. }
  10493. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  10494. if ($roleKey === '') {
  10495. continue;
  10496. }
  10497. // 如果全局中不存在该角色,添加到全局
  10498. if (!isset($global_role_map[$roleKey])) {
  10499. $new_global_roles[] = [
  10500. 'role' => $role_name,
  10501. 'description' => getProp($role, 'description', ''),
  10502. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  10503. 'voice_name' => getProp($role, 'voice_name', ''),
  10504. 'voice_type' => getProp($role, 'voice_type', ''),
  10505. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  10506. 'url' => getProp($role, 'url', ''),
  10507. 'task_id' => getProp($role, 'task_id', ''),
  10508. 'task_status' => getProp($role, 'task_status', ''),
  10509. ];
  10510. $global_role_map[$roleKey] = true; // 标记已添加
  10511. $need_update = true;
  10512. dLog('deepseek')->info("新角色同步到全局", [
  10513. 'anime_id' => $anime_id,
  10514. 'role' => $role_name,
  10515. 'task_id' => getProp($role, 'task_id', ''),
  10516. ]);
  10517. }
  10518. // else {
  10519. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  10520. // $global_role = $global_role_map[$roleKey];
  10521. // if (is_array($global_role)) {
  10522. // $updated = false;
  10523. // $update_fields = [];
  10524. // // 检查描述是否更新
  10525. // $current_description = trim((string)getProp($role, 'description'));
  10526. // $global_description = trim((string)getProp($global_role, 'description'));
  10527. // if ($current_description !== '' && $current_description !== $global_description) {
  10528. // $updated = true;
  10529. // $update_fields[] = 'description';
  10530. // }
  10531. // // 检查pic_prompt是否更新
  10532. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  10533. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  10534. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  10535. // $updated = true;
  10536. // $update_fields[] = 'pic_prompt';
  10537. // }
  10538. // // 检查图片任务信息是否更新
  10539. // $current_task_id = getProp($role, 'task_id');
  10540. // $global_task_id = getProp($global_role, 'task_id');
  10541. // if ($current_task_id && $current_task_id !== $global_task_id) {
  10542. // $updated = true;
  10543. // $update_fields[] = 'task_id';
  10544. // }
  10545. // // 如果有更新,同步到全局
  10546. // if ($updated) {
  10547. // foreach ($new_global_roles as &$global_role_item) {
  10548. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  10549. // if ($global_role_key === $roleKey) {
  10550. // if (in_array('description', $update_fields)) {
  10551. // $global_role_item['description'] = $current_description;
  10552. // }
  10553. // if (in_array('pic_prompt', $update_fields)) {
  10554. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  10555. // }
  10556. // if (in_array('task_id', $update_fields)) {
  10557. // $global_role_item['task_id'] = $current_task_id;
  10558. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  10559. // $global_role_item['url'] = getProp($role, 'url', '');
  10560. // }
  10561. // break;
  10562. // }
  10563. // }
  10564. // $need_update = true;
  10565. // dLog('deepseek')->info("角色信息更新到全局", [
  10566. // 'anime_id' => $anime_id,
  10567. // 'role' => $role_name,
  10568. // 'update_fields' => implode(',', $update_fields),
  10569. // ]);
  10570. // }
  10571. // }
  10572. // }
  10573. }
  10574. // 检查并添加新场景到全局
  10575. foreach ($merged_scenes as $scene) {
  10576. $scene_name = getProp($scene, 'scene');
  10577. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  10578. if ($sceneKey === '') {
  10579. continue;
  10580. }
  10581. // 如果全局中不存在该场景,添加到全局
  10582. if (!isset($global_scene_map[$sceneKey])) {
  10583. $new_global_scenes[] = [
  10584. 'scene' => $scene_name,
  10585. 'description' => getProp($scene, 'description', ''),
  10586. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  10587. 'url' => getProp($scene, 'url', ''),
  10588. 'task_id' => getProp($scene, 'task_id', ''),
  10589. 'task_status' => getProp($scene, 'task_status', ''),
  10590. ];
  10591. $global_scene_map[$sceneKey] = true; // 标记已添加
  10592. $need_update = true;
  10593. dLog('deepseek')->info("新场景同步到全局", [
  10594. 'anime_id' => $anime_id,
  10595. 'scene' => $scene_name,
  10596. 'task_id' => getProp($scene, 'task_id', ''),
  10597. ]);
  10598. }
  10599. // else {
  10600. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  10601. // $global_scene = $global_scene_map[$sceneKey];
  10602. // if (is_array($global_scene)) {
  10603. // $updated = false;
  10604. // $update_fields = [];
  10605. // // 检查描述是否更新
  10606. // $current_description = trim((string)getProp($scene, 'description'));
  10607. // $global_description = trim((string)getProp($global_scene, 'description'));
  10608. // if ($current_description !== '' && $current_description !== $global_description) {
  10609. // $updated = true;
  10610. // $update_fields[] = 'description';
  10611. // }
  10612. // // 检查pic_prompt是否更新
  10613. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  10614. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  10615. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  10616. // $updated = true;
  10617. // $update_fields[] = 'pic_prompt';
  10618. // }
  10619. // // 检查图片任务信息是否更新
  10620. // $current_task_id = getProp($scene, 'task_id');
  10621. // $global_task_id = getProp($global_scene, 'task_id');
  10622. // if ($current_task_id && $current_task_id !== $global_task_id) {
  10623. // $updated = true;
  10624. // $update_fields[] = 'task_id';
  10625. // }
  10626. // // 如果有更新,同步到全局
  10627. // if ($updated) {
  10628. // foreach ($new_global_scenes as &$global_scene_item) {
  10629. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  10630. // if ($global_scene_key === $sceneKey) {
  10631. // if (in_array('description', $update_fields)) {
  10632. // $global_scene_item['description'] = $current_description;
  10633. // }
  10634. // if (in_array('pic_prompt', $update_fields)) {
  10635. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  10636. // }
  10637. // if (in_array('task_id', $update_fields)) {
  10638. // $global_scene_item['task_id'] = $current_task_id;
  10639. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  10640. // $global_scene_item['url'] = getProp($scene, 'url', '');
  10641. // }
  10642. // break;
  10643. // }
  10644. // }
  10645. // $need_update = true;
  10646. // dLog('deepseek')->info("场景信息更新到全局", [
  10647. // 'anime_id' => $anime_id,
  10648. // 'scene' => $scene_name,
  10649. // 'update_fields' => implode(',', $update_fields),
  10650. // ]);
  10651. // }
  10652. // }
  10653. // }
  10654. }
  10655. // 如果有新增或更新,更新数据库
  10656. if ($need_update) {
  10657. $update_data = [
  10658. 'roles' => json_encode($new_global_roles, 256),
  10659. 'scenes' => json_encode($new_global_scenes, 256),
  10660. 'updated_at' => date('Y-m-d H:i:s'),
  10661. ];
  10662. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  10663. if ($result !== false) {
  10664. dLog('deepseek')->info("全局角色和场景更新成功", [
  10665. 'anime_id' => $anime_id,
  10666. 'roles_count' => count($new_global_roles),
  10667. 'scenes_count' => count($new_global_scenes),
  10668. ]);
  10669. } else {
  10670. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  10671. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  10672. }
  10673. }
  10674. }
  10675. }